Imported Upstream version 2.57.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.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: David Zeuthen <davidz@redhat.com>
19  */
20
21 /*
22  * TODO for GDBus:
23  *
24  * - would be nice to expose GDBusAuthMechanism and an extension point
25  *
26  * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27  *   the mechanism VFuncs need to be able to set an error.
28  *
29  * - Need to document other mechanisms/sources for determining the D-Bus
30  *   address of a well-known bus.
31  *
32  *   - e.g. on Win32 we need code like from here
33  *
34  *     http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
35  *
36  *     that was never copied over here because it originally was copy-paste
37  *     from the GPLv2 / AFL 2.1 libdbus sources.
38  *
39  *   - on OS X we need to look in launchd for the address
40  *
41  *     https://bugs.freedesktop.org/show_bug.cgi?id=14259
42  *
43  *   - on X11 we need to look in a X11 property on the X server
44  *     - (we can also just use dbus-launch(1) from the D-Bus
45  *        distribution)
46  *
47  *   - (ideally) this requires D-Bus spec work because none of
48  *     this has never really been specced out properly (except
49  *     the X11 bits)
50  *
51  * - Related to the above, we also need to be able to launch a message bus
52  *   instance.... Since we don't want to write our own bus daemon we should
53  *   launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
54  *
55  * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56  *   to specify where the nonce is stored. This will allow people to use
57  *   G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58  *   to easily achieve secure RPC via nonce-tcp.
59  *
60  * - need to expose an extension point for resolving D-Bus address and
61  *   turning them into GIOStream objects. This will allow us to implement
62  *   e.g. X11 D-Bus transports without dlopen()'ing or linking against
63  *   libX11 from libgio.
64  *   - see g_dbus_address_connect() in gdbusaddress.c
65  *
66  * - would be cute to use kernel-specific APIs to resolve fds for
67  *   debug output when using G_DBUS_DEBUG=message, e.g. in addition to
68  *
69  *     fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
70  *
71  *   maybe we can show more information about what fd 21 really is.
72  *   Ryan suggests looking in /proc/self/fd for clues / symlinks!
73  *   Initial experiments on Linux 2.6 suggests that the symlink looks
74  *   like this:
75  *
76  *    3 -> /proc/18068/fd
77  *
78  *   e.g. not of much use.
79  *
80  *  - GDBus High-Level docs
81  *    - Proxy: properties, signals...
82  *    - Connection: IOStream based, ::close, connection setup steps
83  *                  mainloop integration, threading
84  *    - Differences from libdbus (extend "Migrating from")
85  *      - the message handling thread
86  *      - Using GVariant instead of GValue
87  *    - Explain why the high-level API is a good thing and what
88  *      kind of pitfalls it avoids
89  *      - Export objects before claiming names
90  *    - Talk about auto-starting services (cf. GBusNameWatcherFlags)
91  *
92  *  - 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-example-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_contains (alive_connections, connection));
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 closes @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; @task is (transfer full) */
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; @task is (transfer full). */
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; @task is (transfer full) */
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; @task is (transfer full) */
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                        g_steal_pointer (&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_contains (alive_connections, user_data);
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               /* This removes @task from @map_method_serial_to_task. */
2287               //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2288               send_message_data_deliver_reply_unlocked (task, message);
2289             }
2290           else
2291             {
2292               //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2293             }
2294           CONNECTION_UNLOCK (connection);
2295         }
2296       else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2297         {
2298           CONNECTION_LOCK (connection);
2299           distribute_signals (connection, message);
2300           CONNECTION_UNLOCK (connection);
2301         }
2302       else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2303         {
2304           CONNECTION_LOCK (connection);
2305           distribute_method_call (connection, message);
2306           CONNECTION_UNLOCK (connection);
2307         }
2308     }
2309
2310   if (message != NULL)
2311     g_object_unref (message);
2312   g_object_unref (connection);
2313 }
2314
2315 /* Called in GDBusWorker's thread, lock is not held */
2316 static GDBusMessage *
2317 on_worker_message_about_to_be_sent (GDBusWorker  *worker,
2318                                     GDBusMessage *message,
2319                                     gpointer      user_data)
2320 {
2321   GDBusConnection *connection;
2322   FilterData **filters;
2323   guint n;
2324   gboolean alive;
2325
2326   G_LOCK (message_bus_lock);
2327   alive = g_hash_table_contains (alive_connections, user_data);
2328   if (!alive)
2329     {
2330       G_UNLOCK (message_bus_lock);
2331       return message;
2332     }
2333   connection = G_DBUS_CONNECTION (user_data);
2334   g_object_ref (connection);
2335   G_UNLOCK (message_bus_lock);
2336
2337   //g_debug ("in on_worker_message_about_to_be_sent");
2338
2339   /* First collect the set of callback functions */
2340   CONNECTION_LOCK (connection);
2341   filters = copy_filter_list (connection->filters);
2342   CONNECTION_UNLOCK (connection);
2343
2344   /* then call the filters in order (without holding the lock) */
2345   for (n = 0; filters[n]; n++)
2346     {
2347       g_dbus_message_lock (message);
2348       message = filters[n]->filter_function (connection,
2349                                              message,
2350                                              FALSE,
2351                                              filters[n]->user_data);
2352       if (message == NULL)
2353         break;
2354     }
2355
2356   CONNECTION_LOCK (connection);
2357   free_filter_list (filters);
2358   CONNECTION_UNLOCK (connection);
2359
2360   g_object_unref (connection);
2361
2362   return message;
2363 }
2364
2365 /* called with connection lock held, in GDBusWorker thread */
2366 static gboolean
2367 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2368 {
2369   GTask *task = value;
2370   SendMessageData *data = g_task_get_task_data (task);
2371
2372   if (data->delivered)
2373     return FALSE;
2374
2375   g_task_return_new_error (task,
2376                            G_IO_ERROR,
2377                            G_IO_ERROR_CLOSED,
2378                            _("The connection is closed"));
2379
2380   /* Ask send_message_with_reply_cleanup not to remove the element from the
2381    * hash table - we're in the middle of a foreach; that would be unsafe.
2382    * Instead, return TRUE from this function so that it gets removed safely.
2383    */
2384   send_message_with_reply_cleanup (task, FALSE);
2385   return TRUE;
2386 }
2387
2388 /* Called in GDBusWorker's thread - we must not block - without lock held */
2389 static void
2390 on_worker_closed (GDBusWorker *worker,
2391                   gboolean     remote_peer_vanished,
2392                   GError      *error,
2393                   gpointer     user_data)
2394 {
2395   GDBusConnection *connection;
2396   gboolean alive;
2397   guint old_atomic_flags;
2398
2399   G_LOCK (message_bus_lock);
2400   alive = g_hash_table_contains (alive_connections, user_data);
2401   if (!alive)
2402     {
2403       G_UNLOCK (message_bus_lock);
2404       return;
2405     }
2406   connection = G_DBUS_CONNECTION (user_data);
2407   g_object_ref (connection);
2408   G_UNLOCK (message_bus_lock);
2409
2410   //g_debug ("in on_worker_closed: %s", error->message);
2411
2412   CONNECTION_LOCK (connection);
2413   /* Even though this is atomic, we do it inside the lock to avoid breaking
2414    * assumptions in remove_match_rule(). We'd need the lock in a moment
2415    * anyway, so, no loss.
2416    */
2417   old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2418
2419   if (!(old_atomic_flags & FLAG_CLOSED))
2420     {
2421       g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2422       schedule_closed_unlocked (connection, remote_peer_vanished, error);
2423     }
2424   CONNECTION_UNLOCK (connection);
2425
2426   g_object_unref (connection);
2427 }
2428
2429 /* ---------------------------------------------------------------------------------------------------- */
2430
2431 /* Determines the biggest set of capabilities we can support on this
2432  * connection.
2433  *
2434  * Called with the init_lock held.
2435  */
2436 static GDBusCapabilityFlags
2437 get_offered_capabilities_max (GDBusConnection *connection)
2438 {
2439       GDBusCapabilityFlags ret;
2440       ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2441 #ifdef G_OS_UNIX
2442       if (G_IS_UNIX_CONNECTION (connection->stream))
2443         ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2444 #endif
2445       return ret;
2446 }
2447
2448 /* Called in a user thread, lock is not held */
2449 static gboolean
2450 initable_init (GInitable     *initable,
2451                GCancellable  *cancellable,
2452                GError       **error)
2453 {
2454   GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2455   gboolean ret;
2456
2457   /* This method needs to be idempotent to work with the singleton
2458    * pattern. See the docs for g_initable_init(). We implement this by
2459    * locking.
2460    *
2461    * Unfortunately we can't use the main lock since the on_worker_*()
2462    * callbacks above needs the lock during initialization (for message
2463    * bus connections we do a synchronous Hello() call on the bus).
2464    */
2465   g_mutex_lock (&connection->init_lock);
2466
2467   ret = FALSE;
2468
2469   /* Make this a no-op if we're already initialized (successfully or
2470    * unsuccessfully)
2471    */
2472   if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2473     {
2474       ret = (connection->initialization_error == NULL);
2475       goto out;
2476     }
2477
2478   /* Because of init_lock, we can't get here twice in different threads */
2479   g_assert (connection->initialization_error == NULL);
2480
2481   /* The user can pass multiple (but mutally exclusive) construct
2482    * properties:
2483    *
2484    *  - stream (of type GIOStream)
2485    *  - address (of type gchar*)
2486    *
2487    * At the end of the day we end up with a non-NULL GIOStream
2488    * object in connection->stream.
2489    */
2490   if (connection->address != NULL)
2491     {
2492       g_assert (connection->stream == NULL);
2493
2494       if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2495           (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2496         {
2497           g_set_error_literal (&connection->initialization_error,
2498                                G_IO_ERROR,
2499                                G_IO_ERROR_INVALID_ARGUMENT,
2500                                _("Unsupported flags encountered when constructing a client-side connection"));
2501           goto out;
2502         }
2503
2504       connection->stream = g_dbus_address_get_stream_sync (connection->address,
2505                                                            NULL, /* TODO: out_guid */
2506                                                            cancellable,
2507                                                            &connection->initialization_error);
2508       if (connection->stream == NULL)
2509         goto out;
2510     }
2511   else if (connection->stream != NULL)
2512     {
2513       /* nothing to do */
2514     }
2515   else
2516     {
2517       g_assert_not_reached ();
2518     }
2519
2520   /* Authenticate the connection */
2521   if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2522     {
2523       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2524       g_assert (connection->guid != NULL);
2525       connection->auth = _g_dbus_auth_new (connection->stream);
2526       if (!_g_dbus_auth_run_server (connection->auth,
2527                                     connection->authentication_observer,
2528                                     connection->guid,
2529                                     (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2530                                     get_offered_capabilities_max (connection),
2531                                     &connection->capabilities,
2532                                     &connection->credentials,
2533                                     cancellable,
2534                                     &connection->initialization_error))
2535         goto out;
2536     }
2537   else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2538     {
2539       g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2540       g_assert (connection->guid == NULL);
2541       connection->auth = _g_dbus_auth_new (connection->stream);
2542       connection->guid = _g_dbus_auth_run_client (connection->auth,
2543                                                   connection->authentication_observer,
2544                                                   get_offered_capabilities_max (connection),
2545                                                   &connection->capabilities,
2546                                                   cancellable,
2547                                                   &connection->initialization_error);
2548       if (connection->guid == NULL)
2549         goto out;
2550     }
2551
2552   if (connection->authentication_observer != NULL)
2553     {
2554       g_object_unref (connection->authentication_observer);
2555       connection->authentication_observer = NULL;
2556     }
2557
2558   //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2559
2560   //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2561
2562 #ifdef G_OS_UNIX
2563   /* We want all IO operations to be non-blocking since they happen in
2564    * the worker thread which is shared by _all_ connections.
2565    */
2566   if (G_IS_SOCKET_CONNECTION (connection->stream))
2567     {
2568       g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2569     }
2570 #endif
2571
2572   G_LOCK (message_bus_lock);
2573   if (alive_connections == NULL)
2574     alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2575   g_hash_table_add (alive_connections, connection);
2576   G_UNLOCK (message_bus_lock);
2577
2578   connection->worker = _g_dbus_worker_new (connection->stream,
2579                                            connection->capabilities,
2580                                            ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2581                                            on_worker_message_received,
2582                                            on_worker_message_about_to_be_sent,
2583                                            on_worker_closed,
2584                                            connection);
2585
2586   /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2587   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2588     {
2589       GVariant *hello_result;
2590
2591       /* we could lift this restriction by adding code in gdbusprivate.c */
2592       if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2593         {
2594           g_set_error_literal (&connection->initialization_error,
2595                                G_IO_ERROR,
2596                                G_IO_ERROR_FAILED,
2597                                "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2598           goto out;
2599         }
2600
2601       hello_result = g_dbus_connection_call_sync (connection,
2602                                                   "org.freedesktop.DBus", /* name */
2603                                                   "/org/freedesktop/DBus", /* path */
2604                                                   "org.freedesktop.DBus", /* interface */
2605                                                   "Hello",
2606                                                   NULL, /* parameters */
2607                                                   G_VARIANT_TYPE ("(s)"),
2608                                                   CALL_FLAGS_INITIALIZING,
2609                                                   -1,
2610                                                   NULL, /* TODO: cancellable */
2611                                                   &connection->initialization_error);
2612       if (hello_result == NULL)
2613         goto out;
2614
2615       g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2616       g_variant_unref (hello_result);
2617       //g_debug ("unique name is '%s'", connection->bus_unique_name);
2618     }
2619
2620   ret = TRUE;
2621  out:
2622   if (!ret)
2623     {
2624       g_assert (connection->initialization_error != NULL);
2625       g_propagate_error (error, g_error_copy (connection->initialization_error));
2626     }
2627
2628   g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2629   g_mutex_unlock (&connection->init_lock);
2630
2631   return ret;
2632 }
2633
2634 static void
2635 initable_iface_init (GInitableIface *initable_iface)
2636 {
2637   initable_iface->init = initable_init;
2638 }
2639
2640 /* ---------------------------------------------------------------------------------------------------- */
2641
2642 static void
2643 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2644 {
2645   /* Use default */
2646 }
2647
2648 /* ---------------------------------------------------------------------------------------------------- */
2649
2650 /**
2651  * g_dbus_connection_new:
2652  * @stream: a #GIOStream
2653  * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2654  * @flags: flags describing how to make the connection
2655  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2656  * @cancellable: (nullable): a #GCancellable or %NULL
2657  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2658  * @user_data: the data to pass to @callback
2659  *
2660  * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2661  * with the end represented by @stream.
2662  *
2663  * If @stream is a #GSocketConnection, then the corresponding #GSocket
2664  * will be put into non-blocking mode.
2665  *
2666  * The D-Bus connection will interact with @stream from a worker thread.
2667  * As a result, the caller should not interact with @stream after this
2668  * method has been called, except by calling g_object_unref() on it.
2669  *
2670  * If @observer is not %NULL it may be used to control the
2671  * authentication process.
2672  *
2673  * When the operation is finished, @callback will be invoked. You can
2674  * then call g_dbus_connection_new_finish() to get the result of the
2675  * operation.
2676  *
2677  * This is a asynchronous failable constructor. See
2678  * g_dbus_connection_new_sync() for the synchronous
2679  * version.
2680  *
2681  * Since: 2.26
2682  */
2683 void
2684 g_dbus_connection_new (GIOStream            *stream,
2685                        const gchar          *guid,
2686                        GDBusConnectionFlags  flags,
2687                        GDBusAuthObserver    *observer,
2688                        GCancellable         *cancellable,
2689                        GAsyncReadyCallback   callback,
2690                        gpointer              user_data)
2691 {
2692   _g_dbus_initialize ();
2693
2694   g_return_if_fail (G_IS_IO_STREAM (stream));
2695
2696   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2697                               G_PRIORITY_DEFAULT,
2698                               cancellable,
2699                               callback,
2700                               user_data,
2701                               "stream", stream,
2702                               "guid", guid,
2703                               "flags", flags,
2704                               "authentication-observer", observer,
2705                               NULL);
2706 }
2707
2708 /**
2709  * g_dbus_connection_new_finish:
2710  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2711  *     passed to g_dbus_connection_new().
2712  * @error: return location for error or %NULL
2713  *
2714  * Finishes an operation started with g_dbus_connection_new().
2715  *
2716  * Returns: a #GDBusConnection or %NULL if @error is set. Free
2717  *     with g_object_unref().
2718  *
2719  * Since: 2.26
2720  */
2721 GDBusConnection *
2722 g_dbus_connection_new_finish (GAsyncResult  *res,
2723                               GError       **error)
2724 {
2725   GObject *object;
2726   GObject *source_object;
2727
2728   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2729   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2730
2731   source_object = g_async_result_get_source_object (res);
2732   g_assert (source_object != NULL);
2733   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2734                                         res,
2735                                         error);
2736   g_object_unref (source_object);
2737   if (object != NULL)
2738     return G_DBUS_CONNECTION (object);
2739   else
2740     return NULL;
2741 }
2742
2743 /**
2744  * g_dbus_connection_new_sync:
2745  * @stream: a #GIOStream
2746  * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2747  * @flags: flags describing how to make the connection
2748  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2749  * @cancellable: (nullable): a #GCancellable or %NULL
2750  * @error: return location for error or %NULL
2751  *
2752  * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2753  * with the end represented by @stream.
2754  *
2755  * If @stream is a #GSocketConnection, then the corresponding #GSocket
2756  * will be put into non-blocking mode.
2757  *
2758  * The D-Bus connection will interact with @stream from a worker thread.
2759  * As a result, the caller should not interact with @stream after this
2760  * method has been called, except by calling g_object_unref() on it.
2761  *
2762  * If @observer is not %NULL it may be used to control the
2763  * authentication process.
2764  *
2765  * This is a synchronous failable constructor. See
2766  * g_dbus_connection_new() for the asynchronous version.
2767  *
2768  * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2769  *
2770  * Since: 2.26
2771  */
2772 GDBusConnection *
2773 g_dbus_connection_new_sync (GIOStream             *stream,
2774                             const gchar           *guid,
2775                             GDBusConnectionFlags   flags,
2776                             GDBusAuthObserver     *observer,
2777                             GCancellable          *cancellable,
2778                             GError               **error)
2779 {
2780   _g_dbus_initialize ();
2781   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2782   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2783   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2784                          cancellable,
2785                          error,
2786                          "stream", stream,
2787                          "guid", guid,
2788                          "flags", flags,
2789                          "authentication-observer", observer,
2790                          NULL);
2791 }
2792
2793 /* ---------------------------------------------------------------------------------------------------- */
2794
2795 /**
2796  * g_dbus_connection_new_for_address:
2797  * @address: a D-Bus address
2798  * @flags: flags describing how to make the connection
2799  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2800  * @cancellable: (nullable): a #GCancellable or %NULL
2801  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2802  * @user_data: the data to pass to @callback
2803  *
2804  * Asynchronously connects and sets up a D-Bus client connection for
2805  * exchanging D-Bus messages with an endpoint specified by @address
2806  * which must be in the
2807  * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2808  *
2809  * This constructor can only be used to initiate client-side
2810  * connections - use g_dbus_connection_new() if you need to act as the
2811  * server. In particular, @flags cannot contain the
2812  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2813  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2814  *
2815  * When the operation is finished, @callback will be invoked. You can
2816  * then call g_dbus_connection_new_finish() to get the result of the
2817  * operation.
2818  *
2819  * If @observer is not %NULL it may be used to control the
2820  * authentication process.
2821  *
2822  * This is a asynchronous failable constructor. See
2823  * g_dbus_connection_new_for_address_sync() for the synchronous
2824  * version.
2825  *
2826  * Since: 2.26
2827  */
2828 void
2829 g_dbus_connection_new_for_address (const gchar          *address,
2830                                    GDBusConnectionFlags  flags,
2831                                    GDBusAuthObserver    *observer,
2832                                    GCancellable         *cancellable,
2833                                    GAsyncReadyCallback   callback,
2834                                    gpointer              user_data)
2835 {
2836   _g_dbus_initialize ();
2837
2838   g_return_if_fail (address != NULL);
2839
2840   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2841                               G_PRIORITY_DEFAULT,
2842                               cancellable,
2843                               callback,
2844                               user_data,
2845                               "address", address,
2846                               "flags", flags,
2847                               "authentication-observer", observer,
2848                               NULL);
2849 }
2850
2851 /**
2852  * g_dbus_connection_new_for_address_finish:
2853  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2854  *     to g_dbus_connection_new()
2855  * @error: return location for error or %NULL
2856  *
2857  * Finishes an operation started with g_dbus_connection_new_for_address().
2858  *
2859  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2860  *     g_object_unref().
2861  *
2862  * Since: 2.26
2863  */
2864 GDBusConnection *
2865 g_dbus_connection_new_for_address_finish (GAsyncResult  *res,
2866                                           GError       **error)
2867 {
2868   GObject *object;
2869   GObject *source_object;
2870
2871   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2872   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2873
2874   source_object = g_async_result_get_source_object (res);
2875   g_assert (source_object != NULL);
2876   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2877                                         res,
2878                                         error);
2879   g_object_unref (source_object);
2880   if (object != NULL)
2881     return G_DBUS_CONNECTION (object);
2882   else
2883     return NULL;
2884 }
2885
2886 /**
2887  * g_dbus_connection_new_for_address_sync:
2888  * @address: a D-Bus address
2889  * @flags: flags describing how to make the connection
2890  * @observer: (nullable): a #GDBusAuthObserver or %NULL
2891  * @cancellable: (nullable): a #GCancellable or %NULL
2892  * @error: return location for error or %NULL
2893  *
2894  * Synchronously connects and sets up a D-Bus client connection for
2895  * exchanging D-Bus messages with an endpoint specified by @address
2896  * which must be in the
2897  * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2898  *
2899  * This constructor can only be used to initiate client-side
2900  * connections - use g_dbus_connection_new_sync() if you need to act
2901  * as the server. In particular, @flags cannot contain the
2902  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2903  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2904  *
2905  * This is a synchronous failable constructor. See
2906  * g_dbus_connection_new_for_address() for the asynchronous version.
2907  *
2908  * If @observer is not %NULL it may be used to control the
2909  * authentication process.
2910  *
2911  * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2912  *     g_object_unref().
2913  *
2914  * Since: 2.26
2915  */
2916 GDBusConnection *
2917 g_dbus_connection_new_for_address_sync (const gchar           *address,
2918                                         GDBusConnectionFlags   flags,
2919                                         GDBusAuthObserver     *observer,
2920                                         GCancellable          *cancellable,
2921                                         GError               **error)
2922 {
2923   _g_dbus_initialize ();
2924
2925   g_return_val_if_fail (address != NULL, NULL);
2926   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2927   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2928                          cancellable,
2929                          error,
2930                          "address", address,
2931                          "flags", flags,
2932                          "authentication-observer", observer,
2933                          NULL);
2934 }
2935
2936 /* ---------------------------------------------------------------------------------------------------- */
2937
2938 /**
2939  * g_dbus_connection_set_exit_on_close:
2940  * @connection: a #GDBusConnection
2941  * @exit_on_close: whether the process should be terminated
2942  *     when @connection is closed by the remote peer
2943  *
2944  * Sets whether the process should be terminated when @connection is
2945  * closed by the remote peer. See #GDBusConnection:exit-on-close for
2946  * more details.
2947  *
2948  * Note that this function should be used with care. Most modern UNIX
2949  * desktops tie the notion of a user session the session bus, and expect
2950  * all of a users applications to quit when their bus connection goes away.
2951  * If you are setting @exit_on_close to %FALSE for the shared session
2952  * bus connection, you should make sure that your application exits
2953  * when the user session ends.
2954  *
2955  * Since: 2.26
2956  */
2957 void
2958 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2959                                      gboolean         exit_on_close)
2960 {
2961   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2962
2963   if (exit_on_close)
2964     g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2965   else
2966     g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2967
2968 }
2969
2970 /**
2971  * g_dbus_connection_get_exit_on_close:
2972  * @connection: a #GDBusConnection
2973  *
2974  * Gets whether the process is terminated when @connection is
2975  * closed by the remote peer. See
2976  * #GDBusConnection:exit-on-close for more details.
2977  *
2978  * Returns: whether the process is terminated when @connection is
2979  *     closed by the remote peer
2980  *
2981  * Since: 2.26
2982  */
2983 gboolean
2984 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2985 {
2986   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2987
2988   if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
2989     return TRUE;
2990   else
2991     return FALSE;
2992 }
2993
2994 /**
2995  * g_dbus_connection_get_guid:
2996  * @connection: a #GDBusConnection
2997  *
2998  * The GUID of the peer performing the role of server when
2999  * authenticating. See #GDBusConnection:guid for more details.
3000  *
3001  * Returns: The GUID. Do not free this string, it is owned by
3002  *     @connection.
3003  *
3004  * Since: 2.26
3005  */
3006 const gchar *
3007 g_dbus_connection_get_guid (GDBusConnection *connection)
3008 {
3009   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3010   return connection->guid;
3011 }
3012
3013 /**
3014  * g_dbus_connection_get_unique_name:
3015  * @connection: a #GDBusConnection
3016  *
3017  * Gets the unique name of @connection as assigned by the message
3018  * bus. This can also be used to figure out if @connection is a
3019  * message bus connection.
3020  *
3021  * Returns: the unique name or %NULL if @connection is not a message
3022  *     bus connection. Do not free this string, it is owned by
3023  *     @connection.
3024  *
3025  * Since: 2.26
3026  */
3027 const gchar *
3028 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3029 {
3030   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3031
3032   /* do not use g_return_val_if_fail(), we want the memory barrier */
3033   if (!check_initialized (connection))
3034     return NULL;
3035
3036   return connection->bus_unique_name;
3037 }
3038
3039 /**
3040  * g_dbus_connection_get_peer_credentials:
3041  * @connection: a #GDBusConnection
3042  *
3043  * Gets the credentials of the authenticated peer. This will always
3044  * return %NULL unless @connection acted as a server
3045  * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3046  * when set up and the client passed credentials as part of the
3047  * authentication process.
3048  *
3049  * In a message bus setup, the message bus is always the server and
3050  * each application is a client. So this method will always return
3051  * %NULL for message bus clients.
3052  *
3053  * Returns: (transfer none) (nullable): a #GCredentials or %NULL if not
3054  *     available. Do not free this object, it is owned by @connection.
3055  *
3056  * Since: 2.26
3057  */
3058 GCredentials *
3059 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3060 {
3061   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3062
3063   /* do not use g_return_val_if_fail(), we want the memory barrier */
3064   if (!check_initialized (connection))
3065     return NULL;
3066
3067   return connection->credentials;
3068 }
3069
3070 /* ---------------------------------------------------------------------------------------------------- */
3071
3072 static volatile guint _global_filter_id = 1;
3073
3074 /**
3075  * g_dbus_connection_add_filter:
3076  * @connection: a #GDBusConnection
3077  * @filter_function: a filter function
3078  * @user_data: user data to pass to @filter_function
3079  * @user_data_free_func: function to free @user_data with when filter
3080  *     is removed or %NULL
3081  *
3082  * Adds a message filter. Filters are handlers that are run on all
3083  * incoming and outgoing messages, prior to standard dispatch. Filters
3084  * are run in the order that they were added.  The same handler can be
3085  * added as a filter more than once, in which case it will be run more
3086  * than once.  Filters added during a filter callback won't be run on
3087  * the message being processed. Filter functions are allowed to modify
3088  * and even drop messages.
3089  *
3090  * Note that filters are run in a dedicated message handling thread so
3091  * they can't block and, generally, can't do anything but signal a
3092  * worker thread. Also note that filters are rarely needed - use API
3093  * such as g_dbus_connection_send_message_with_reply(),
3094  * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3095  *
3096  * If a filter consumes an incoming message the message is not
3097  * dispatched anywhere else - not even the standard dispatch machinery
3098  * (that API such as g_dbus_connection_signal_subscribe() and
3099  * g_dbus_connection_send_message_with_reply() relies on) will see the
3100  * message. Similary, if a filter consumes an outgoing message, the
3101  * message will not be sent to the other peer.
3102  *
3103  * If @user_data_free_func is non-%NULL, it will be called (in the
3104  * thread-default main context of the thread you are calling this
3105  * method from) at some point after @user_data is no longer
3106  * needed. (It is not guaranteed to be called synchronously when the
3107  * filter is removed, and may be called after @connection has been
3108  * destroyed.)
3109  *
3110  * Returns: a filter identifier that can be used with
3111  *     g_dbus_connection_remove_filter()
3112  *
3113  * Since: 2.26
3114  */
3115 guint
3116 g_dbus_connection_add_filter (GDBusConnection            *connection,
3117                               GDBusMessageFilterFunction  filter_function,
3118                               gpointer                    user_data,
3119                               GDestroyNotify              user_data_free_func)
3120 {
3121   FilterData *data;
3122
3123   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3124   g_return_val_if_fail (filter_function != NULL, 0);
3125   g_return_val_if_fail (check_initialized (connection), 0);
3126
3127   CONNECTION_LOCK (connection);
3128   data = g_new0 (FilterData, 1);
3129   data->id = g_atomic_int_add (&_global_filter_id, 1); /* TODO: overflow etc. */
3130   data->ref_count = 1;
3131   data->filter_function = filter_function;
3132   data->user_data = user_data;
3133   data->user_data_free_func = user_data_free_func;
3134   data->context = g_main_context_ref_thread_default ();
3135   g_ptr_array_add (connection->filters, data);
3136   CONNECTION_UNLOCK (connection);
3137
3138   return data->id;
3139 }
3140
3141 /* only called from finalize(), removes all filters */
3142 static void
3143 purge_all_filters (GDBusConnection *connection)
3144 {
3145   guint n;
3146   for (n = 0; n < connection->filters->len; n++)
3147     {
3148       FilterData *data = connection->filters->pdata[n];
3149
3150       call_destroy_notify (data->context,
3151                            data->user_data_free_func,
3152                            data->user_data);
3153       g_main_context_unref (data->context);
3154       g_free (data);
3155     }
3156 }
3157
3158 /**
3159  * g_dbus_connection_remove_filter:
3160  * @connection: a #GDBusConnection
3161  * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3162  *
3163  * Removes a filter.
3164  *
3165  * Note that since filters run in a different thread, there is a race
3166  * condition where it is possible that the filter will be running even
3167  * after calling g_dbus_connection_remove_filter(), so you cannot just
3168  * free data that the filter might be using. Instead, you should pass
3169  * a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
3170  * called when it is guaranteed that the data is no longer needed.
3171  *
3172  * Since: 2.26
3173  */
3174 void
3175 g_dbus_connection_remove_filter (GDBusConnection *connection,
3176                                  guint            filter_id)
3177 {
3178   guint n;
3179   gboolean found;
3180   FilterData *to_destroy;
3181
3182   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3183   g_return_if_fail (check_initialized (connection));
3184
3185   CONNECTION_LOCK (connection);
3186   found = FALSE;
3187   to_destroy = NULL;
3188   for (n = 0; n < connection->filters->len; n++)
3189     {
3190       FilterData *data = connection->filters->pdata[n];
3191       if (data->id == filter_id)
3192         {
3193           found = TRUE;
3194           g_ptr_array_remove_index (connection->filters, n);
3195           data->ref_count--;
3196           if (data->ref_count == 0)
3197             to_destroy = data;
3198           break;
3199         }
3200     }
3201   CONNECTION_UNLOCK (connection);
3202
3203   /* do free without holding lock */
3204   if (to_destroy != NULL)
3205     {
3206       if (to_destroy->user_data_free_func != NULL)
3207         to_destroy->user_data_free_func (to_destroy->user_data);
3208       g_main_context_unref (to_destroy->context);
3209       g_free (to_destroy);
3210     }
3211   else if (!found)
3212     {
3213       g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3214     }
3215 }
3216
3217 /* ---------------------------------------------------------------------------------------------------- */
3218
3219 typedef struct
3220 {
3221   gchar *rule;
3222   gchar *sender;
3223   gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3224   gchar *interface_name;
3225   gchar *member;
3226   gchar *object_path;
3227   gchar *arg0;
3228   GDBusSignalFlags flags;
3229   GArray *subscribers;
3230 } SignalData;
3231
3232 typedef struct
3233 {
3234   GDBusSignalCallback callback;
3235   gpointer user_data;
3236   GDestroyNotify user_data_free_func;
3237   guint id;
3238   GMainContext *context;
3239 } SignalSubscriber;
3240
3241 static void
3242 signal_data_free (SignalData *signal_data)
3243 {
3244   g_free (signal_data->rule);
3245   g_free (signal_data->sender);
3246   g_free (signal_data->sender_unique_name);
3247   g_free (signal_data->interface_name);
3248   g_free (signal_data->member);
3249   g_free (signal_data->object_path);
3250   g_free (signal_data->arg0);
3251   g_array_free (signal_data->subscribers, TRUE);
3252   g_free (signal_data);
3253 }
3254
3255 static gchar *
3256 args_to_rule (const gchar      *sender,
3257               const gchar      *interface_name,
3258               const gchar      *member,
3259               const gchar      *object_path,
3260               const gchar      *arg0,
3261               GDBusSignalFlags  flags)
3262 {
3263   GString *rule;
3264
3265   rule = g_string_new ("type='signal'");
3266   if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3267     g_string_prepend_c (rule, '-');
3268   if (sender != NULL)
3269     g_string_append_printf (rule, ",sender='%s'", sender);
3270   if (interface_name != NULL)
3271     g_string_append_printf (rule, ",interface='%s'", interface_name);
3272   if (member != NULL)
3273     g_string_append_printf (rule, ",member='%s'", member);
3274   if (object_path != NULL)
3275     g_string_append_printf (rule, ",path='%s'", object_path);
3276
3277   if (arg0 != NULL)
3278     {
3279       if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3280         g_string_append_printf (rule, ",arg0path='%s'", arg0);
3281       else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3282         g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3283       else
3284         g_string_append_printf (rule, ",arg0='%s'", arg0);
3285     }
3286
3287   return g_string_free (rule, FALSE);
3288 }
3289
3290 static volatile guint _global_subscriber_id = 1;
3291 static volatile guint _global_registration_id = 1;
3292 static volatile guint _global_subtree_registration_id = 1;
3293
3294 /* ---------------------------------------------------------------------------------------------------- */
3295
3296 /* Called in a user thread, lock is held */
3297 static void
3298 add_match_rule (GDBusConnection *connection,
3299                 const gchar     *match_rule)
3300 {
3301   GError *error;
3302   GDBusMessage *message;
3303
3304   if (match_rule[0] == '-')
3305     return;
3306
3307   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3308                                             "/org/freedesktop/DBus", /* path */
3309                                             "org.freedesktop.DBus", /* interface */
3310                                             "AddMatch");
3311   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3312   error = NULL;
3313   if (!g_dbus_connection_send_message_unlocked (connection,
3314                                                 message,
3315                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3316                                                 NULL,
3317                                                 &error))
3318     {
3319       g_critical ("Error while sending AddMatch() message: %s", error->message);
3320       g_error_free (error);
3321     }
3322   g_object_unref (message);
3323 }
3324
3325 /* ---------------------------------------------------------------------------------------------------- */
3326
3327 /* Called in a user thread, lock is held */
3328 static void
3329 remove_match_rule (GDBusConnection *connection,
3330                    const gchar     *match_rule)
3331 {
3332   GError *error;
3333   GDBusMessage *message;
3334
3335   if (match_rule[0] == '-')
3336     return;
3337
3338   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3339                                             "/org/freedesktop/DBus", /* path */
3340                                             "org.freedesktop.DBus", /* interface */
3341                                             "RemoveMatch");
3342   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3343
3344   error = NULL;
3345   if (!g_dbus_connection_send_message_unlocked (connection,
3346                                                 message,
3347                                                 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3348                                                 NULL,
3349                                                 &error))
3350     {
3351       /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3352        * critical; but we're holding the lock, and our caller checked whether
3353        * we were already closed, so we can't get that error.
3354        */
3355       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3356       g_error_free (error);
3357     }
3358   g_object_unref (message);
3359 }
3360
3361 /* ---------------------------------------------------------------------------------------------------- */
3362
3363 static gboolean
3364 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3365 {
3366   return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3367          g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3368          g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3369          (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3370           g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3371 }
3372
3373 /* ---------------------------------------------------------------------------------------------------- */
3374
3375 /**
3376  * g_dbus_connection_signal_subscribe:
3377  * @connection: a #GDBusConnection
3378  * @sender: (nullable): sender name to match on (unique or well-known name)
3379  *     or %NULL to listen from all senders
3380  * @interface_name: (nullable): D-Bus interface name to match on or %NULL to
3381  *     match on all interfaces
3382  * @member: (nullable): D-Bus signal name to match on or %NULL to match on
3383  *     all signals
3384  * @object_path: (nullable): object path to match on or %NULL to match on
3385  *     all object paths
3386  * @arg0: (nullable): contents of first string argument to match on or %NULL
3387  *     to match on all kinds of arguments
3388  * @flags: #GDBusSignalFlags describing how arg0 is used in subscribing to the
3389  *     signal
3390  * @callback: callback to invoke when there is a signal matching the requested data
3391  * @user_data: user data to pass to @callback
3392  * @user_data_free_func: (nullable): function to free @user_data with when
3393  *     subscription is removed or %NULL
3394  *
3395  * Subscribes to signals on @connection and invokes @callback with a whenever
3396  * the signal is received. Note that @callback will be invoked in the 
3397  * [thread-default main context][g-main-context-push-thread-default]
3398  * of the thread you are calling this method from.
3399  *
3400  * If @connection is not a message bus connection, @sender must be
3401  * %NULL.
3402  *
3403  * If @sender is a well-known name note that @callback is invoked with
3404  * the unique name for the owner of @sender, not the well-known name
3405  * as one would expect. This is because the message bus rewrites the
3406  * name. As such, to avoid certain race conditions, users should be
3407  * tracking the name owner of the well-known name and use that when
3408  * processing the received signal.
3409  *
3410  * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3411  * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3412  * interpreted as part of a namespace or path.  The first argument
3413  * of a signal is matched against that part as specified by D-Bus.
3414  *
3415  * If @user_data_free_func is non-%NULL, it will be called (in the
3416  * thread-default main context of the thread you are calling this
3417  * method from) at some point after @user_data is no longer
3418  * needed. (It is not guaranteed to be called synchronously when the
3419  * signal is unsubscribed from, and may be called after @connection
3420  * has been destroyed.)
3421  *
3422  * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3423  *
3424  * Since: 2.26
3425  */
3426 guint
3427 g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
3428                                     const gchar         *sender,
3429                                     const gchar         *interface_name,
3430                                     const gchar         *member,
3431                                     const gchar         *object_path,
3432                                     const gchar         *arg0,
3433                                     GDBusSignalFlags     flags,
3434                                     GDBusSignalCallback  callback,
3435                                     gpointer             user_data,
3436                                     GDestroyNotify       user_data_free_func)
3437 {
3438   gchar *rule;
3439   SignalData *signal_data;
3440   SignalSubscriber subscriber;
3441   GPtrArray *signal_data_array;
3442   const gchar *sender_unique_name;
3443
3444   /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3445    * an OOM condition. We might want to change that but that would involve making
3446    * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3447    * handle that. And there's really no sensible way of handling this short of retrying
3448    * to add the match rule... and then there's the little thing that, hey, maybe there's
3449    * a reason the bus in an OOM condition.
3450    *
3451    * Doable, but not really sure it's worth it...
3452    */
3453
3454   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3455   g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3456   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3457   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3458   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3459   g_return_val_if_fail (callback != NULL, 0);
3460   g_return_val_if_fail (check_initialized (connection), 0);
3461   g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3462   g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3463
3464   CONNECTION_LOCK (connection);
3465
3466   /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3467    * with a '-' character to prefix the rule (which will otherwise be
3468    * normal).
3469    *
3470    * This allows us to hash the rule and do our lifecycle tracking in
3471    * the usual way, but the '-' prevents the match rule from ever
3472    * actually being send to the bus (either for add or remove).
3473    */
3474   rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3475
3476   if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3477     sender_unique_name = sender;
3478   else
3479     sender_unique_name = "";
3480
3481   subscriber.callback = callback;
3482   subscriber.user_data = user_data;
3483   subscriber.user_data_free_func = user_data_free_func;
3484   subscriber.id = g_atomic_int_add (&_global_subscriber_id, 1); /* TODO: overflow etc. */
3485   subscriber.context = g_main_context_ref_thread_default ();
3486
3487   /* see if we've already have this rule */
3488   signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3489   if (signal_data != NULL)
3490     {
3491       g_array_append_val (signal_data->subscribers, subscriber);
3492       g_free (rule);
3493       goto out;
3494     }
3495
3496   signal_data = g_new0 (SignalData, 1);
3497   signal_data->rule                  = rule;
3498   signal_data->sender                = g_strdup (sender);
3499   signal_data->sender_unique_name    = g_strdup (sender_unique_name);
3500   signal_data->interface_name        = g_strdup (interface_name);
3501   signal_data->member                = g_strdup (member);
3502   signal_data->object_path           = g_strdup (object_path);
3503   signal_data->arg0                  = g_strdup (arg0);
3504   signal_data->flags                 = flags;
3505   signal_data->subscribers           = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3506   g_array_append_val (signal_data->subscribers, subscriber);
3507
3508   g_hash_table_insert (connection->map_rule_to_signal_data,
3509                        signal_data->rule,
3510                        signal_data);
3511
3512   /* Add the match rule to the bus...
3513    *
3514    * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3515    * always send such messages to us.
3516    */
3517   if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3518     {
3519       if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3520         add_match_rule (connection, signal_data->rule);
3521     }
3522
3523   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3524                                            signal_data->sender_unique_name);
3525   if (signal_data_array == NULL)
3526     {
3527       signal_data_array = g_ptr_array_new ();
3528       g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3529                            g_strdup (signal_data->sender_unique_name),
3530                            signal_data_array);
3531     }
3532   g_ptr_array_add (signal_data_array, signal_data);
3533
3534  out:
3535   g_hash_table_insert (connection->map_id_to_signal_data,
3536                        GUINT_TO_POINTER (subscriber.id),
3537                        signal_data);
3538
3539   CONNECTION_UNLOCK (connection);
3540
3541   return subscriber.id;
3542 }
3543
3544 /* ---------------------------------------------------------------------------------------------------- */
3545
3546 /* called in any thread */
3547 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3548 static void
3549 unsubscribe_id_internal (GDBusConnection *connection,
3550                          guint            subscription_id,
3551                          GArray          *out_removed_subscribers)
3552 {
3553   SignalData *signal_data;
3554   GPtrArray *signal_data_array;
3555   guint n;
3556
3557   signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3558                                      GUINT_TO_POINTER (subscription_id));
3559   if (signal_data == NULL)
3560     {
3561       /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3562       goto out;
3563     }
3564
3565   for (n = 0; n < signal_data->subscribers->len; n++)
3566     {
3567       SignalSubscriber *subscriber;
3568
3569       subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3570       if (subscriber->id != subscription_id)
3571         continue;
3572
3573       g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3574                                            GUINT_TO_POINTER (subscription_id)));
3575       g_array_append_val (out_removed_subscribers, *subscriber);
3576       g_array_remove_index (signal_data->subscribers, n);
3577
3578       if (signal_data->subscribers->len == 0)
3579         {
3580           g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3581
3582           signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3583                                                    signal_data->sender_unique_name);
3584           g_warn_if_fail (signal_data_array != NULL);
3585           g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3586
3587           if (signal_data_array->len == 0)
3588             {
3589               g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3590                                                    signal_data->sender_unique_name));
3591             }
3592
3593           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3594           if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3595               !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3596               !g_dbus_connection_is_closed (connection) &&
3597               !connection->finalizing)
3598             {
3599               /* The check for g_dbus_connection_is_closed() means that
3600                * sending the RemoveMatch message can't fail with
3601                * G_IO_ERROR_CLOSED, because we're holding the lock,
3602                * so on_worker_closed() can't happen between the check we just
3603                * did, and releasing the lock later.
3604                */
3605               remove_match_rule (connection, signal_data->rule);
3606             }
3607
3608           signal_data_free (signal_data);
3609         }
3610
3611       goto out;
3612     }
3613
3614   g_assert_not_reached ();
3615
3616  out:
3617   ;
3618 }
3619
3620 /**
3621  * g_dbus_connection_signal_unsubscribe:
3622  * @connection: a #GDBusConnection
3623  * @subscription_id: a subscription id obtained from
3624  *     g_dbus_connection_signal_subscribe()
3625  *
3626  * Unsubscribes from signals.
3627  *
3628  * Since: 2.26
3629  */
3630 void
3631 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3632                                       guint            subscription_id)
3633 {
3634   GArray *subscribers;
3635   guint n;
3636
3637   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3638   g_return_if_fail (check_initialized (connection));
3639
3640   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3641
3642   CONNECTION_LOCK (connection);
3643   unsubscribe_id_internal (connection,
3644                            subscription_id,
3645                            subscribers);
3646   CONNECTION_UNLOCK (connection);
3647
3648   /* invariant */
3649   g_assert (subscribers->len == 0 || subscribers->len == 1);
3650
3651   /* call GDestroyNotify without lock held */
3652   for (n = 0; n < subscribers->len; n++)
3653     {
3654       SignalSubscriber *subscriber;
3655       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3656       call_destroy_notify (subscriber->context,
3657                            subscriber->user_data_free_func,
3658                            subscriber->user_data);
3659       g_main_context_unref (subscriber->context);
3660     }
3661
3662   g_array_free (subscribers, TRUE);
3663 }
3664
3665 /* ---------------------------------------------------------------------------------------------------- */
3666
3667 typedef struct
3668 {
3669   guint                subscription_id;
3670   GDBusSignalCallback  callback;
3671   gpointer             user_data;
3672   GDBusMessage        *message;
3673   GDBusConnection     *connection;
3674   const gchar         *sender;
3675   const gchar         *path;
3676   const gchar         *interface;
3677   const gchar         *member;
3678 } SignalInstance;
3679
3680 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3681  * no locks held
3682  */
3683 static gboolean
3684 emit_signal_instance_in_idle_cb (gpointer data)
3685 {
3686   SignalInstance *signal_instance = data;
3687   GVariant *parameters;
3688   gboolean has_subscription;
3689
3690   parameters = g_dbus_message_get_body (signal_instance->message);
3691   if (parameters == NULL)
3692     {
3693       parameters = g_variant_new ("()");
3694       g_variant_ref_sink (parameters);
3695     }
3696   else
3697     {
3698       g_variant_ref_sink (parameters);
3699     }
3700
3701 #if 0
3702   g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3703            signal_instance->subscription_id,
3704            signal_instance->sender,
3705            signal_instance->path,
3706            signal_instance->interface,
3707            signal_instance->member,
3708            g_variant_print (parameters, TRUE));
3709 #endif
3710
3711   /* Careful here, don't do the callback if we no longer has the subscription */
3712   CONNECTION_LOCK (signal_instance->connection);
3713   has_subscription = FALSE;
3714   if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3715                            GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3716     has_subscription = TRUE;
3717   CONNECTION_UNLOCK (signal_instance->connection);
3718
3719   if (has_subscription)
3720     signal_instance->callback (signal_instance->connection,
3721                                signal_instance->sender,
3722                                signal_instance->path,
3723                                signal_instance->interface,
3724                                signal_instance->member,
3725                                parameters,
3726                                signal_instance->user_data);
3727
3728   g_variant_unref (parameters);
3729
3730   return FALSE;
3731 }
3732
3733 static void
3734 signal_instance_free (SignalInstance *signal_instance)
3735 {
3736   g_object_unref (signal_instance->message);
3737   g_object_unref (signal_instance->connection);
3738   g_free (signal_instance);
3739 }
3740
3741 static gboolean
3742 namespace_rule_matches (const gchar *namespace,
3743                         const gchar *name)
3744 {
3745   gint len_namespace;
3746   gint len_name;
3747
3748   len_namespace = strlen (namespace);
3749   len_name = strlen (name);
3750
3751   if (len_name < len_namespace)
3752     return FALSE;
3753
3754   if (memcmp (namespace, name, len_namespace) != 0)
3755     return FALSE;
3756
3757   return len_namespace == len_name || name[len_namespace] == '.';
3758 }
3759
3760 static gboolean
3761 path_rule_matches (const gchar *path_a,
3762                    const gchar *path_b)
3763 {
3764   gint len_a, len_b;
3765
3766   len_a = strlen (path_a);
3767   len_b = strlen (path_b);
3768
3769   if (len_a < len_b && (len_a == 0 || path_a[len_a - 1] != '/'))
3770     return FALSE;
3771
3772   if (len_b < len_a && (len_b == 0 || path_b[len_b - 1] != '/'))
3773     return FALSE;
3774
3775   return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3776 }
3777
3778 /* called in GDBusWorker thread WITH lock held */
3779 static void
3780 schedule_callbacks (GDBusConnection *connection,
3781                     GPtrArray       *signal_data_array,
3782                     GDBusMessage    *message,
3783                     const gchar     *sender)
3784 {
3785   guint n, m;
3786   const gchar *interface;
3787   const gchar *member;
3788   const gchar *path;
3789   const gchar *arg0;
3790
3791   interface = NULL;
3792   member = NULL;
3793   path = NULL;
3794   arg0 = NULL;
3795
3796   interface = g_dbus_message_get_interface (message);
3797   member = g_dbus_message_get_member (message);
3798   path = g_dbus_message_get_path (message);
3799   arg0 = g_dbus_message_get_arg0 (message);
3800
3801 #if 0
3802   g_print ("In schedule_callbacks:\n"
3803            "  sender    = '%s'\n"
3804            "  interface = '%s'\n"
3805            "  member    = '%s'\n"
3806            "  path      = '%s'\n"
3807            "  arg0      = '%s'\n",
3808            sender,
3809            interface,
3810            member,
3811            path,
3812            arg0);
3813 #endif
3814
3815   /* TODO: if this is slow, then we can change signal_data_array into
3816    *       map_object_path_to_signal_data_array or something.
3817    */
3818   for (n = 0; n < signal_data_array->len; n++)
3819     {
3820       SignalData *signal_data = signal_data_array->pdata[n];
3821
3822       if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3823         continue;
3824
3825       if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3826         continue;
3827
3828       if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3829         continue;
3830
3831       if (signal_data->arg0 != NULL)
3832         {
3833           if (arg0 == NULL)
3834             continue;
3835
3836           if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3837             {
3838               if (!namespace_rule_matches (signal_data->arg0, arg0))
3839                 continue;
3840             }
3841           else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3842             {
3843               if (!path_rule_matches (signal_data->arg0, arg0))
3844                 continue;
3845             }
3846           else if (!g_str_equal (signal_data->arg0, arg0))
3847             continue;
3848         }
3849
3850       for (m = 0; m < signal_data->subscribers->len; m++)
3851         {
3852           SignalSubscriber *subscriber;
3853           GSource *idle_source;
3854           SignalInstance *signal_instance;
3855
3856           subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3857
3858           signal_instance = g_new0 (SignalInstance, 1);
3859           signal_instance->subscription_id = subscriber->id;
3860           signal_instance->callback = subscriber->callback;
3861           signal_instance->user_data = subscriber->user_data;
3862           signal_instance->message = g_object_ref (message);
3863           signal_instance->connection = g_object_ref (connection);
3864           signal_instance->sender = sender;
3865           signal_instance->path = path;
3866           signal_instance->interface = interface;
3867           signal_instance->member = member;
3868
3869           idle_source = g_idle_source_new ();
3870           g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3871           g_source_set_callback (idle_source,
3872                                  emit_signal_instance_in_idle_cb,
3873                                  signal_instance,
3874                                  (GDestroyNotify) signal_instance_free);
3875           g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3876           g_source_attach (idle_source, subscriber->context);
3877           g_source_unref (idle_source);
3878         }
3879     }
3880 }
3881
3882 /* called in GDBusWorker thread with lock held */
3883 static void
3884 distribute_signals (GDBusConnection *connection,
3885                     GDBusMessage    *message)
3886 {
3887   GPtrArray *signal_data_array;
3888   const gchar *sender;
3889
3890   sender = g_dbus_message_get_sender (message);
3891
3892   if (G_UNLIKELY (_g_dbus_debug_signal ()))
3893     {
3894       _g_dbus_debug_print_lock ();
3895       g_print ("========================================================================\n"
3896                "GDBus-debug:Signal:\n"
3897                " <<<< RECEIVED SIGNAL %s.%s\n"
3898                "      on object %s\n"
3899                "      sent by name %s\n",
3900                g_dbus_message_get_interface (message),
3901                g_dbus_message_get_member (message),
3902                g_dbus_message_get_path (message),
3903                sender != NULL ? sender : "(none)");
3904       _g_dbus_debug_print_unlock ();
3905     }
3906
3907   /* collect subscribers that match on sender */
3908   if (sender != NULL)
3909     {
3910       signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3911       if (signal_data_array != NULL)
3912         schedule_callbacks (connection, signal_data_array, message, sender);
3913     }
3914
3915   /* collect subscribers not matching on sender */
3916   signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3917   if (signal_data_array != NULL)
3918     schedule_callbacks (connection, signal_data_array, message, sender);
3919 }
3920
3921 /* ---------------------------------------------------------------------------------------------------- */
3922
3923 /* only called from finalize(), removes all subscriptions */
3924 static void
3925 purge_all_signal_subscriptions (GDBusConnection *connection)
3926 {
3927   GHashTableIter iter;
3928   gpointer key;
3929   GArray *ids;
3930   GArray *subscribers;
3931   guint n;
3932
3933   ids = g_array_new (FALSE, FALSE, sizeof (guint));
3934   g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3935   while (g_hash_table_iter_next (&iter, &key, NULL))
3936     {
3937       guint subscription_id = GPOINTER_TO_UINT (key);
3938       g_array_append_val (ids, subscription_id);
3939     }
3940
3941   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3942   for (n = 0; n < ids->len; n++)
3943     {
3944       guint subscription_id = g_array_index (ids, guint, n);
3945       unsubscribe_id_internal (connection,
3946                                subscription_id,
3947                                subscribers);
3948     }
3949   g_array_free (ids, TRUE);
3950
3951   /* call GDestroyNotify without lock held */
3952   for (n = 0; n < subscribers->len; n++)
3953     {
3954       SignalSubscriber *subscriber;
3955       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3956       call_destroy_notify (subscriber->context,
3957                            subscriber->user_data_free_func,
3958                            subscriber->user_data);
3959       g_main_context_unref (subscriber->context);
3960     }
3961
3962   g_array_free (subscribers, TRUE);
3963 }
3964
3965 /* ---------------------------------------------------------------------------------------------------- */
3966
3967 static GDBusInterfaceVTable *
3968 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3969 {
3970   /* Don't waste memory by copying padding - remember to update this
3971    * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3972    */
3973   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3974 }
3975
3976 static void
3977 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3978 {
3979   g_free (vtable);
3980 }
3981
3982 /* ---------------------------------------------------------------------------------------------------- */
3983
3984 static GDBusSubtreeVTable *
3985 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3986 {
3987   /* Don't waste memory by copying padding - remember to update this
3988    * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3989    */
3990   return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3991 }
3992
3993 static void
3994 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3995 {
3996   g_free (vtable);
3997 }
3998
3999 /* ---------------------------------------------------------------------------------------------------- */
4000
4001 struct ExportedObject
4002 {
4003   gchar *object_path;
4004   GDBusConnection *connection;
4005
4006   /* maps gchar* -> ExportedInterface* */
4007   GHashTable *map_if_name_to_ei;
4008 };
4009
4010 /* only called with lock held */
4011 static void
4012 exported_object_free (ExportedObject *eo)
4013 {
4014   g_free (eo->object_path);
4015   g_hash_table_unref (eo->map_if_name_to_ei);
4016   g_free (eo);
4017 }
4018
4019 typedef struct
4020 {
4021   ExportedObject *eo;
4022
4023   guint                       id;
4024   gchar                      *interface_name;
4025   GDBusInterfaceVTable       *vtable;
4026   GDBusInterfaceInfo         *interface_info;
4027
4028   GMainContext               *context;
4029   gpointer                    user_data;
4030   GDestroyNotify              user_data_free_func;
4031 } ExportedInterface;
4032
4033 /* called with lock held */
4034 static void
4035 exported_interface_free (ExportedInterface *ei)
4036 {
4037   g_dbus_interface_info_cache_release (ei->interface_info);
4038   g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4039
4040   call_destroy_notify (ei->context,
4041                        ei->user_data_free_func,
4042                        ei->user_data);
4043
4044   g_main_context_unref (ei->context);
4045
4046   g_free (ei->interface_name);
4047   _g_dbus_interface_vtable_free (ei->vtable);
4048   g_free (ei);
4049 }
4050
4051 /* ---------------------------------------------------------------------------------------------------- */
4052
4053 /* Convenience function to check if @registration_id (if not zero) or
4054  * @subtree_registration_id (if not zero) has been unregistered. If
4055  * so, returns %TRUE.
4056  *
4057  * May be called by any thread. Caller must *not* hold lock.
4058  */
4059 static gboolean
4060 has_object_been_unregistered (GDBusConnection  *connection,
4061                               guint             registration_id,
4062                               guint             subtree_registration_id)
4063 {
4064   gboolean ret;
4065
4066   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4067
4068   ret = FALSE;
4069
4070   CONNECTION_LOCK (connection);
4071   if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4072                                                    GUINT_TO_POINTER (registration_id)) == NULL)
4073     {
4074       ret = TRUE;
4075     }
4076   else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4077                                                                 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4078     {
4079       ret = TRUE;
4080     }
4081   CONNECTION_UNLOCK (connection);
4082
4083   return ret;
4084 }
4085
4086 /* ---------------------------------------------------------------------------------------------------- */
4087
4088 typedef struct
4089 {
4090   GDBusConnection *connection;
4091   GDBusMessage *message;
4092   gpointer user_data;
4093   const gchar *property_name;
4094   const GDBusInterfaceVTable *vtable;
4095   GDBusInterfaceInfo *interface_info;
4096   const GDBusPropertyInfo *property_info;
4097   guint registration_id;
4098   guint subtree_registration_id;
4099 } PropertyData;
4100
4101 static void
4102 property_data_free (PropertyData *data)
4103 {
4104   g_object_unref (data->connection);
4105   g_object_unref (data->message);
4106   g_free (data);
4107 }
4108
4109 /* called in thread where object was registered - no locks held */
4110 static gboolean
4111 invoke_get_property_in_idle_cb (gpointer _data)
4112 {
4113   PropertyData *data = _data;
4114   GVariant *value;
4115   GError *error;
4116   GDBusMessage *reply;
4117
4118   if (has_object_been_unregistered (data->connection,
4119                                     data->registration_id,
4120                                     data->subtree_registration_id))
4121     {
4122       reply = g_dbus_message_new_method_error (data->message,
4123                                                "org.freedesktop.DBus.Error.UnknownMethod",
4124                                                _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4125                                                g_dbus_message_get_path (data->message));
4126       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4127       g_object_unref (reply);
4128       goto out;
4129     }
4130
4131   error = NULL;
4132   value = data->vtable->get_property (data->connection,
4133                                       g_dbus_message_get_sender (data->message),
4134                                       g_dbus_message_get_path (data->message),
4135                                       data->interface_info->name,
4136                                       data->property_name,
4137                                       &error,
4138                                       data->user_data);
4139
4140
4141   if (value != NULL)
4142     {
4143       g_assert_no_error (error);
4144
4145       g_variant_take_ref (value);
4146       reply = g_dbus_message_new_method_reply (data->message);
4147       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4148       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4149       g_variant_unref (value);
4150       g_object_unref (reply);
4151     }
4152   else
4153     {
4154       gchar *dbus_error_name;
4155       g_assert (error != NULL);
4156       dbus_error_name = g_dbus_error_encode_gerror (error);
4157       reply = g_dbus_message_new_method_error_literal (data->message,
4158                                                        dbus_error_name,
4159                                                        error->message);
4160       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4161       g_free (dbus_error_name);
4162       g_error_free (error);
4163       g_object_unref (reply);
4164     }
4165
4166  out:
4167   return FALSE;
4168 }
4169
4170 /* called in thread where object was registered - no locks held */
4171 static gboolean
4172 invoke_set_property_in_idle_cb (gpointer _data)
4173 {
4174   PropertyData *data = _data;
4175   GError *error;
4176   GDBusMessage *reply;
4177   GVariant *value;
4178
4179   error = NULL;
4180   value = NULL;
4181
4182   g_variant_get (g_dbus_message_get_body (data->message),
4183                  "(ssv)",
4184                  NULL,
4185                  NULL,
4186                  &value);
4187
4188   if (!data->vtable->set_property (data->connection,
4189                                    g_dbus_message_get_sender (data->message),
4190                                    g_dbus_message_get_path (data->message),
4191                                    data->interface_info->name,
4192                                    data->property_name,
4193                                    value,
4194                                    &error,
4195                                    data->user_data))
4196     {
4197       gchar *dbus_error_name;
4198       g_assert (error != NULL);
4199       dbus_error_name = g_dbus_error_encode_gerror (error);
4200       reply = g_dbus_message_new_method_error_literal (data->message,
4201                                                        dbus_error_name,
4202                                                        error->message);
4203       g_free (dbus_error_name);
4204       g_error_free (error);
4205     }
4206   else
4207     {
4208       reply = g_dbus_message_new_method_reply (data->message);
4209     }
4210
4211   g_assert (reply != NULL);
4212   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4213   g_object_unref (reply);
4214   g_variant_unref (value);
4215
4216   return FALSE;
4217 }
4218
4219 /* called in any thread with connection's lock held */
4220 static gboolean
4221 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
4222                                              GDBusMessage               *message,
4223                                              guint                       registration_id,
4224                                              guint                       subtree_registration_id,
4225                                              gboolean                    is_get,
4226                                              GDBusInterfaceInfo         *interface_info,
4227                                              const GDBusInterfaceVTable *vtable,
4228                                              GMainContext               *main_context,
4229                                              gpointer                    user_data)
4230 {
4231   gboolean handled;
4232   const char *interface_name;
4233   const char *property_name;
4234   const GDBusPropertyInfo *property_info;
4235   GSource *idle_source;
4236   PropertyData *property_data;
4237   GDBusMessage *reply;
4238
4239   handled = FALSE;
4240
4241   if (is_get)
4242     g_variant_get (g_dbus_message_get_body (message),
4243                    "(&s&s)",
4244                    &interface_name,
4245                    &property_name);
4246   else
4247     g_variant_get (g_dbus_message_get_body (message),
4248                    "(&s&sv)",
4249                    &interface_name,
4250                    &property_name,
4251                    NULL);
4252
4253   if (vtable == NULL)
4254     goto out;
4255
4256   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4257    */
4258   property_info = NULL;
4259
4260   /* TODO: the cost of this is O(n) - it might be worth caching the result */
4261   property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4262   if (property_info == NULL)
4263     {
4264       reply = g_dbus_message_new_method_error (message,
4265                                                "org.freedesktop.DBus.Error.InvalidArgs",
4266                                                _("No such property '%s'"),
4267                                                property_name);
4268       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4269       g_object_unref (reply);
4270       handled = TRUE;
4271       goto out;
4272     }
4273
4274   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4275     {
4276       reply = g_dbus_message_new_method_error (message,
4277                                                "org.freedesktop.DBus.Error.InvalidArgs",
4278                                                _("Property '%s' is not readable"),
4279                                                property_name);
4280       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4281       g_object_unref (reply);
4282       handled = TRUE;
4283       goto out;
4284     }
4285   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4286     {
4287       reply = g_dbus_message_new_method_error (message,
4288                                                "org.freedesktop.DBus.Error.InvalidArgs",
4289                                                _("Property '%s' is not writable"),
4290                                                property_name);
4291       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4292       g_object_unref (reply);
4293       handled = TRUE;
4294       goto out;
4295     }
4296
4297   if (!is_get)
4298     {
4299       GVariant *value;
4300
4301       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4302        * of the given value is wrong
4303        */
4304       g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4305       if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4306         {
4307           reply = g_dbus_message_new_method_error (message,
4308                                                    "org.freedesktop.DBus.Error.InvalidArgs",
4309                                                    _("Error setting property '%s': Expected type '%s' but got '%s'"),
4310                                                    property_name, property_info->signature,
4311                                                    g_variant_get_type_string (value));
4312           g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4313           g_variant_unref (value);
4314           g_object_unref (reply);
4315           handled = TRUE;
4316           goto out;
4317         }
4318
4319       g_variant_unref (value);
4320     }
4321
4322   /* If the vtable pointer for get_property() resp. set_property() is
4323    * NULL then dispatch the call via the method_call() handler.
4324    */
4325   if (is_get)
4326     {
4327       if (vtable->get_property == NULL)
4328         {
4329           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4330                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4331                                 vtable, main_context, user_data);
4332           handled = TRUE;
4333           goto out;
4334         }
4335     }
4336   else
4337     {
4338       if (vtable->set_property == NULL)
4339         {
4340           schedule_method_call (connection, message, registration_id, subtree_registration_id,
4341                                 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4342                                 vtable, main_context, user_data);
4343           handled = TRUE;
4344           goto out;
4345         }
4346     }
4347
4348   /* ok, got the property info - call user code in an idle handler */
4349   property_data = g_new0 (PropertyData, 1);
4350   property_data->connection = g_object_ref (connection);
4351   property_data->message = g_object_ref (message);
4352   property_data->user_data = user_data;
4353   property_data->property_name = property_name;
4354   property_data->vtable = vtable;
4355   property_data->interface_info = interface_info;
4356   property_data->property_info = property_info;
4357   property_data->registration_id = registration_id;
4358   property_data->subtree_registration_id = subtree_registration_id;
4359
4360   idle_source = g_idle_source_new ();
4361   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4362   g_source_set_callback (idle_source,
4363                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4364                          property_data,
4365                          (GDestroyNotify) property_data_free);
4366   if (is_get)
4367     g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4368   else
4369     g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4370   g_source_attach (idle_source, main_context);
4371   g_source_unref (idle_source);
4372
4373   handled = TRUE;
4374
4375  out:
4376   return handled;
4377 }
4378
4379 /* called in GDBusWorker thread with connection's lock held */
4380 static gboolean
4381 handle_getset_property (GDBusConnection *connection,
4382                         ExportedObject  *eo,
4383                         GDBusMessage    *message,
4384                         gboolean         is_get)
4385 {
4386   ExportedInterface *ei;
4387   gboolean handled;
4388   const char *interface_name;
4389   const char *property_name;
4390
4391   handled = FALSE;
4392
4393   if (is_get)
4394     g_variant_get (g_dbus_message_get_body (message),
4395                    "(&s&s)",
4396                    &interface_name,
4397                    &property_name);
4398   else
4399     g_variant_get (g_dbus_message_get_body (message),
4400                    "(&s&sv)",
4401                    &interface_name,
4402                    &property_name,
4403                    NULL);
4404
4405   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4406    * no such interface registered
4407    */
4408   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4409   if (ei == NULL)
4410     {
4411       GDBusMessage *reply;
4412       reply = g_dbus_message_new_method_error (message,
4413                                                "org.freedesktop.DBus.Error.InvalidArgs",
4414                                                _("No such interface '%s'"),
4415                                                interface_name);
4416       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4417       g_object_unref (reply);
4418       handled = TRUE;
4419       goto out;
4420     }
4421
4422   handled = validate_and_maybe_schedule_property_getset (eo->connection,
4423                                                          message,
4424                                                          ei->id,
4425                                                          0,
4426                                                          is_get,
4427                                                          ei->interface_info,
4428                                                          ei->vtable,
4429                                                          ei->context,
4430                                                          ei->user_data);
4431  out:
4432   return handled;
4433 }
4434
4435 /* ---------------------------------------------------------------------------------------------------- */
4436
4437 typedef struct
4438 {
4439   GDBusConnection *connection;
4440   GDBusMessage *message;
4441   gpointer user_data;
4442   const GDBusInterfaceVTable *vtable;
4443   GDBusInterfaceInfo *interface_info;
4444   guint registration_id;
4445   guint subtree_registration_id;
4446 } PropertyGetAllData;
4447
4448 static void
4449 property_get_all_data_free (PropertyData *data)
4450 {
4451   g_object_unref (data->connection);
4452   g_object_unref (data->message);
4453   g_free (data);
4454 }
4455
4456 /* called in thread where object was registered - no locks held */
4457 static gboolean
4458 invoke_get_all_properties_in_idle_cb (gpointer _data)
4459 {
4460   PropertyGetAllData *data = _data;
4461   GVariantBuilder builder;
4462   GDBusMessage *reply;
4463   guint n;
4464
4465   if (has_object_been_unregistered (data->connection,
4466                                     data->registration_id,
4467                                     data->subtree_registration_id))
4468     {
4469       reply = g_dbus_message_new_method_error (data->message,
4470                                                "org.freedesktop.DBus.Error.UnknownMethod",
4471                                                _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4472                                                g_dbus_message_get_path (data->message));
4473       g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4474       g_object_unref (reply);
4475       goto out;
4476     }
4477
4478   /* TODO: Right now we never fail this call - we just omit values if
4479    *       a get_property() call is failing.
4480    *
4481    *       We could fail the whole call if just a single get_property() call
4482    *       returns an error. We need clarification in the D-Bus spec about this.
4483    */
4484   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4485   g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4486   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4487     {
4488       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4489       GVariant *value;
4490
4491       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4492         continue;
4493
4494       value = data->vtable->get_property (data->connection,
4495                                           g_dbus_message_get_sender (data->message),
4496                                           g_dbus_message_get_path (data->message),
4497                                           data->interface_info->name,
4498                                           property_info->name,
4499                                           NULL,
4500                                           data->user_data);
4501
4502       if (value == NULL)
4503         continue;
4504
4505       g_variant_take_ref (value);
4506       g_variant_builder_add (&builder,
4507                              "{sv}",
4508                              property_info->name,
4509                              value);
4510       g_variant_unref (value);
4511     }
4512   g_variant_builder_close (&builder);
4513
4514   reply = g_dbus_message_new_method_reply (data->message);
4515   g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4516   g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4517   g_object_unref (reply);
4518
4519  out:
4520   return FALSE;
4521 }
4522
4523 static gboolean
4524 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4525 {
4526   gint i;
4527
4528   if (!interface_info->properties)
4529     return FALSE;
4530
4531   for (i = 0; interface_info->properties[i]; i++)
4532     if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4533       return TRUE;
4534
4535   return FALSE;
4536 }
4537
4538 /* called in any thread with connection's lock held */
4539 static gboolean
4540 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
4541                                               GDBusMessage               *message,
4542                                               guint                       registration_id,
4543                                               guint                       subtree_registration_id,
4544                                               GDBusInterfaceInfo         *interface_info,
4545                                               const GDBusInterfaceVTable *vtable,
4546                                               GMainContext               *main_context,
4547                                               gpointer                    user_data)
4548 {
4549   gboolean handled;
4550   GSource *idle_source;
4551   PropertyGetAllData *property_get_all_data;
4552
4553   handled = FALSE;
4554
4555   if (vtable == NULL)
4556     goto out;
4557
4558   /* If the vtable pointer for get_property() is NULL but we have a
4559    * non-zero number of readable properties, then dispatch the call via
4560    * the method_call() handler.
4561    */
4562   if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4563     {
4564       schedule_method_call (connection, message, registration_id, subtree_registration_id,
4565                             interface_info, NULL, NULL, g_dbus_message_get_body (message),
4566                             vtable, main_context, user_data);
4567       handled = TRUE;
4568       goto out;
4569     }
4570
4571   /* ok, got the property info - call user in an idle handler */
4572   property_get_all_data = g_new0 (PropertyGetAllData, 1);
4573   property_get_all_data->connection = g_object_ref (connection);
4574   property_get_all_data->message = g_object_ref (message);
4575   property_get_all_data->user_data = user_data;
4576   property_get_all_data->vtable = vtable;
4577   property_get_all_data->interface_info = interface_info;
4578   property_get_all_data->registration_id = registration_id;
4579   property_get_all_data->subtree_registration_id = subtree_registration_id;
4580
4581   idle_source = g_idle_source_new ();
4582   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4583   g_source_set_callback (idle_source,
4584                          invoke_get_all_properties_in_idle_cb,
4585                          property_get_all_data,
4586                          (GDestroyNotify) property_get_all_data_free);
4587   g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4588   g_source_attach (idle_source, main_context);
4589   g_source_unref (idle_source);
4590
4591   handled = TRUE;
4592
4593  out:
4594   return handled;
4595 }
4596
4597 /* called in GDBusWorker thread with connection's lock held */
4598 static gboolean
4599 handle_get_all_properties (GDBusConnection *connection,
4600                            ExportedObject  *eo,
4601                            GDBusMessage    *message)
4602 {
4603   ExportedInterface *ei;
4604   gboolean handled;
4605   const char *interface_name;
4606
4607   handled = FALSE;
4608
4609   g_variant_get (g_dbus_message_get_body (message),
4610                  "(&s)",
4611                  &interface_name);
4612
4613   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4614    * no such interface registered
4615    */
4616   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4617   if (ei == NULL)
4618     {
4619       GDBusMessage *reply;
4620       reply = g_dbus_message_new_method_error (message,
4621                                                "org.freedesktop.DBus.Error.InvalidArgs",
4622                                                _("No such interface '%s'"),
4623                                                interface_name);
4624       g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4625       g_object_unref (reply);
4626       handled = TRUE;
4627       goto out;
4628     }
4629
4630   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4631                                                           message,
4632                                                           ei->id,
4633                                                           0,
4634                                                           ei->interface_info,
4635                                                           ei->vtable,
4636                                                           ei->context,
4637                                                           ei->user_data);
4638  out:
4639   return handled;
4640 }
4641
4642 /* ---------------------------------------------------------------------------------------------------- */
4643
4644 static const gchar introspect_header[] =
4645   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4646   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4647   "<!-- GDBus " PACKAGE_VERSION " -->\n"
4648   "<node>\n";
4649
4650 static const gchar introspect_tail[] =
4651   "</node>\n";
4652
4653 static const gchar introspect_properties_interface[] =
4654   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
4655   "    <method name=\"Get\">\n"
4656   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4657   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4658   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4659   "    </method>\n"
4660   "    <method name=\"GetAll\">\n"
4661   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4662   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4663   "    </method>\n"
4664   "    <method name=\"Set\">\n"
4665   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4666   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4667   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4668   "    </method>\n"
4669   "    <signal name=\"PropertiesChanged\">\n"
4670   "      <arg type=\"s\" name=\"interface_name\"/>\n"
4671   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4672   "      <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4673   "    </signal>\n"
4674   "  </interface>\n";
4675
4676 static const gchar introspect_introspectable_interface[] =
4677   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4678   "    <method name=\"Introspect\">\n"
4679   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4680   "    </method>\n"
4681   "  </interface>\n"
4682   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
4683   "    <method name=\"Ping\"/>\n"
4684   "    <method name=\"GetMachineId\">\n"
4685   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4686   "    </method>\n"
4687   "  </interface>\n";
4688
4689 static void
4690 introspect_append_header (GString *s)
4691 {
4692   g_string_append (s, introspect_header);
4693 }
4694
4695 static void
4696 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4697 {
4698   if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4699     {
4700       const gchar *begin;
4701       const gchar *end;
4702       gchar *s;
4703
4704       begin = object_path + path_len;
4705       end = strchr (begin, '/');
4706       if (end != NULL)
4707         s = g_strndup (begin, end - begin);
4708       else
4709         s = g_strdup (begin);
4710
4711       if (!g_hash_table_contains (set, s))
4712         g_hash_table_add (set, s);
4713       else
4714         g_free (s);
4715     }
4716 }
4717
4718 /* TODO: we want a nicer public interface for this */
4719 /* called in any thread with connection's lock held */
4720 static gchar **
4721 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4722                                             const gchar     *path)
4723 {
4724   GPtrArray *p;
4725   gchar **ret;
4726   GHashTableIter hash_iter;
4727   const gchar *object_path;
4728   gsize path_len;
4729   GHashTable *set;
4730   GList *keys;
4731   GList *l;
4732
4733   CONNECTION_ENSURE_LOCK (connection);
4734
4735   path_len = strlen (path);
4736   if (path_len > 1)
4737     path_len++;
4738
4739   set = g_hash_table_new (g_str_hash, g_str_equal);
4740
4741   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4742   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4743     maybe_add_path (path, path_len, object_path, set);
4744
4745   g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4746   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4747     maybe_add_path (path, path_len, object_path, set);
4748
4749   p = g_ptr_array_new ();
4750   keys = g_hash_table_get_keys (set);
4751   for (l = keys; l != NULL; l = l->next)
4752     g_ptr_array_add (p, l->data);
4753   g_hash_table_unref (set);
4754   g_list_free (keys);
4755
4756   g_ptr_array_add (p, NULL);
4757   ret = (gchar **) g_ptr_array_free (p, FALSE);
4758   return ret;
4759 }
4760
4761 /* called in any thread with connection's lock not held */
4762 static gchar **
4763 g_dbus_connection_list_registered (GDBusConnection *connection,
4764                                    const gchar     *path)
4765 {
4766   gchar **ret;
4767   CONNECTION_LOCK (connection);
4768   ret = g_dbus_connection_list_registered_unlocked (connection, path);
4769   CONNECTION_UNLOCK (connection);
4770   return ret;
4771 }
4772
4773 /* called in GDBusWorker thread with connection's lock held */
4774 static gboolean
4775 handle_introspect (GDBusConnection *connection,
4776                    ExportedObject  *eo,
4777                    GDBusMessage    *message)
4778 {
4779   guint n;
4780   GString *s;
4781   GDBusMessage *reply;
4782   GHashTableIter hash_iter;
4783   ExportedInterface *ei;
4784   gchar **registered;
4785
4786   /* first the header with the standard interfaces */
4787   s = g_string_sized_new (sizeof (introspect_header) +
4788                           sizeof (introspect_properties_interface) +
4789                           sizeof (introspect_introspectable_interface) +
4790                           sizeof (introspect_tail));
4791   introspect_append_header (s);
4792   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4793                             "org.freedesktop.DBus.Properties"))
4794     g_string_append (s, introspect_properties_interface);
4795
4796   if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4797                             "org.freedesktop.DBus.Introspectable"))
4798     g_string_append (s, introspect_introspectable_interface);
4799
4800   /* then include the registered interfaces */
4801   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4802   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4803     g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4804
4805   /* finally include nodes registered below us */
4806   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4807   for (n = 0; registered != NULL && registered[n] != NULL; n++)
4808     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
4809   g_strfreev (registered);
4810   g_string_append (s, introspect_tail);
4811
4812   reply = g_dbus_message_new_method_reply (message);
4813   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4814   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4815   g_object_unref (reply);
4816   g_string_free (s, TRUE);
4817
4818   return TRUE;
4819 }
4820
4821 /* called in thread where object was registered - no locks held */
4822 static gboolean
4823 call_in_idle_cb (gpointer user_data)
4824 {
4825   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4826   GDBusInterfaceVTable *vtable;
4827   guint registration_id;
4828   guint subtree_registration_id;
4829
4830   registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4831   subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4832
4833   if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4834                                     registration_id,
4835                                     subtree_registration_id))
4836     {
4837       GDBusMessage *reply;
4838       reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4839                                                "org.freedesktop.DBus.Error.UnknownMethod",
4840                                                _("No such interface '%s' on object at path %s"),
4841                                                g_dbus_method_invocation_get_interface_name (invocation),
4842                                                g_dbus_method_invocation_get_object_path (invocation));
4843       g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4844       g_object_unref (reply);
4845       goto out;
4846     }
4847
4848   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4849   g_assert (vtable != NULL && vtable->method_call != NULL);
4850
4851   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4852                        g_dbus_method_invocation_get_sender (invocation),
4853                        g_dbus_method_invocation_get_object_path (invocation),
4854                        g_dbus_method_invocation_get_interface_name (invocation),
4855                        g_dbus_method_invocation_get_method_name (invocation),
4856                        g_dbus_method_invocation_get_parameters (invocation),
4857                        g_object_ref (invocation),
4858                        g_dbus_method_invocation_get_user_data (invocation));
4859
4860  out:
4861   return FALSE;
4862 }
4863
4864 /* called in GDBusWorker thread with connection's lock held */
4865 static void
4866 schedule_method_call (GDBusConnection            *connection,
4867                       GDBusMessage               *message,
4868                       guint                       registration_id,
4869                       guint                       subtree_registration_id,
4870                       const GDBusInterfaceInfo   *interface_info,
4871                       const GDBusMethodInfo      *method_info,
4872                       const GDBusPropertyInfo    *property_info,
4873                       GVariant                   *parameters,
4874                       const GDBusInterfaceVTable *vtable,
4875                       GMainContext               *main_context,
4876                       gpointer                    user_data)
4877 {
4878   GDBusMethodInvocation *invocation;
4879   GSource *idle_source;
4880
4881   invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4882                                               g_dbus_message_get_path (message),
4883                                               g_dbus_message_get_interface (message),
4884                                               g_dbus_message_get_member (message),
4885                                               method_info,
4886                                               property_info,
4887                                               connection,
4888                                               message,
4889                                               parameters,
4890                                               user_data);
4891
4892   /* TODO: would be nicer with a real MethodData like we already
4893    * have PropertyData and PropertyGetAllData... */
4894   g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4895   g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4896   g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4897
4898   idle_source = g_idle_source_new ();
4899   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4900   g_source_set_callback (idle_source,
4901                          call_in_idle_cb,
4902                          invocation,
4903                          g_object_unref);
4904   g_source_set_name (idle_source, "[gio, " __FILE__ "] call_in_idle_cb");
4905   g_source_attach (idle_source, main_context);
4906   g_source_unref (idle_source);
4907 }
4908
4909 /* called in GDBusWorker thread with connection's lock held */
4910 static gboolean
4911 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
4912                                          GDBusMessage               *message,
4913                                          guint                       registration_id,
4914                                          guint                       subtree_registration_id,
4915                                          GDBusInterfaceInfo         *interface_info,
4916                                          const GDBusInterfaceVTable *vtable,
4917                                          GMainContext               *main_context,
4918                                          gpointer                    user_data)
4919 {
4920   GDBusMethodInfo *method_info;
4921   GDBusMessage *reply;
4922   GVariant *parameters;
4923   gboolean handled;
4924   GVariantType *in_type;
4925
4926   handled = FALSE;
4927
4928   /* TODO: the cost of this is O(n) - it might be worth caching the result */
4929   method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4930
4931   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4932    * error to the caller
4933    */
4934   if (method_info == NULL)
4935     {
4936       reply = g_dbus_message_new_method_error (message,
4937                                                "org.freedesktop.DBus.Error.UnknownMethod",
4938                                                _("No such method '%s'"),
4939                                                g_dbus_message_get_member (message));
4940       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4941       g_object_unref (reply);
4942       handled = TRUE;
4943       goto out;
4944     }
4945
4946   parameters = g_dbus_message_get_body (message);
4947   if (parameters == NULL)
4948     {
4949       parameters = g_variant_new ("()");
4950       g_variant_ref_sink (parameters);
4951     }
4952   else
4953     {
4954       g_variant_ref (parameters);
4955     }
4956
4957   /* Check that the incoming args are of the right type - if they are not, return
4958    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4959    */
4960   in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4961   if (!g_variant_is_of_type (parameters, in_type))
4962     {
4963       gchar *type_string;
4964
4965       type_string = g_variant_type_dup_string (in_type);
4966
4967       reply = g_dbus_message_new_method_error (message,
4968                                                "org.freedesktop.DBus.Error.InvalidArgs",
4969                                                _("Type of message, '%s', does not match expected type '%s'"),
4970                                                g_variant_get_type_string (parameters),
4971                                                type_string);
4972       g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4973       g_variant_type_free (in_type);
4974       g_variant_unref (parameters);
4975       g_object_unref (reply);
4976       g_free (type_string);
4977       handled = TRUE;
4978       goto out;
4979     }
4980   g_variant_type_free (in_type);
4981
4982   /* schedule the call in idle */
4983   schedule_method_call (connection, message, registration_id, subtree_registration_id,
4984                         interface_info, method_info, NULL, parameters,
4985                         vtable, main_context, user_data);
4986   g_variant_unref (parameters);
4987   handled = TRUE;
4988
4989  out:
4990   return handled;
4991 }
4992
4993 /* ---------------------------------------------------------------------------------------------------- */
4994
4995 /* called in GDBusWorker thread with connection's lock held */
4996 static gboolean
4997 obj_message_func (GDBusConnection *connection,
4998                   ExportedObject  *eo,
4999                   GDBusMessage    *message)
5000 {
5001   const gchar *interface_name;
5002   const gchar *member;
5003   const gchar *signature;
5004   gboolean handled;
5005
5006   handled = FALSE;
5007
5008   interface_name = g_dbus_message_get_interface (message);
5009   member = g_dbus_message_get_member (message);
5010   signature = g_dbus_message_get_signature (message);
5011
5012   /* see if we have an interface for handling this call */
5013   if (interface_name != NULL)
5014     {
5015       ExportedInterface *ei;
5016       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5017       if (ei != NULL)
5018         {
5019           /* we do - invoke the handler in idle in the right thread */
5020
5021           /* handle no vtable or handler being present */
5022           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5023             goto out;
5024
5025           handled = validate_and_maybe_schedule_method_call (connection,
5026                                                              message,
5027                                                              ei->id,
5028                                                              0,
5029                                                              ei->interface_info,
5030                                                              ei->vtable,
5031                                                              ei->context,
5032                                                              ei->user_data);
5033           goto out;
5034         }
5035     }
5036
5037   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5038       g_strcmp0 (member, "Introspect") == 0 &&
5039       g_strcmp0 (signature, "") == 0)
5040     {
5041       handled = handle_introspect (connection, eo, message);
5042       goto out;
5043     }
5044   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5045            g_strcmp0 (member, "Get") == 0 &&
5046            g_strcmp0 (signature, "ss") == 0)
5047     {
5048       handled = handle_getset_property (connection, eo, message, TRUE);
5049       goto out;
5050     }
5051   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5052            g_strcmp0 (member, "Set") == 0 &&
5053            g_strcmp0 (signature, "ssv") == 0)
5054     {
5055       handled = handle_getset_property (connection, eo, message, FALSE);
5056       goto out;
5057     }
5058   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5059            g_strcmp0 (member, "GetAll") == 0 &&
5060            g_strcmp0 (signature, "s") == 0)
5061     {
5062       handled = handle_get_all_properties (connection, eo, message);
5063       goto out;
5064     }
5065
5066  out:
5067   return handled;
5068 }
5069
5070 /**
5071  * g_dbus_connection_register_object:
5072  * @connection: a #GDBusConnection
5073  * @object_path: the object path to register at
5074  * @interface_info: introspection data for the interface
5075  * @vtable: (nullable): a #GDBusInterfaceVTable to call into or %NULL
5076  * @user_data: (nullable): data to pass to functions in @vtable
5077  * @user_data_free_func: function to call when the object path is unregistered
5078  * @error: return location for error or %NULL
5079  *
5080  * Registers callbacks for exported objects at @object_path with the
5081  * D-Bus interface that is described in @interface_info.
5082  *
5083  * Calls to functions in @vtable (and @user_data_free_func) will happen
5084  * in the 
5085  * [thread-default main context][g-main-context-push-thread-default]
5086  * of the thread you are calling this method from.
5087  *
5088  * Note that all #GVariant values passed to functions in @vtable will match
5089  * the signature given in @interface_info - if a remote caller passes
5090  * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5091  * is returned to the remote caller.
5092  *
5093  * Additionally, if the remote caller attempts to invoke methods or
5094  * access properties not mentioned in @interface_info the
5095  * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5096  * `org.freedesktop.DBus.Error.InvalidArgs` errors
5097  * are returned to the caller.
5098  *
5099  * It is considered a programming error if the
5100  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5101  * #GVariant of incorrect type.
5102  *
5103  * If an existing callback is already registered at @object_path and
5104  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5105  *
5106  * GDBus automatically implements the standard D-Bus interfaces
5107  * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5108  * and org.freedesktop.Peer, so you don't have to implement those for the
5109  * objects you export. You can implement org.freedesktop.DBus.Properties
5110  * yourself, e.g. to handle getting and setting of properties asynchronously.
5111  *
5112  * Note that the reference count on @interface_info will be
5113  * incremented by 1 (unless allocated statically, e.g. if the
5114  * reference count is -1, see g_dbus_interface_info_ref()) for as long
5115  * as the object is exported. Also note that @vtable will be copied.
5116  *
5117  * See this [server][gdbus-server] for an example of how to use this method.
5118  *
5119  * Returns: 0 if @error is set, otherwise a registration id (never 0)
5120  *     that can be used with g_dbus_connection_unregister_object()
5121  *
5122  * Since: 2.26
5123  */
5124 guint
5125 g_dbus_connection_register_object (GDBusConnection             *connection,
5126                                    const gchar                 *object_path,
5127                                    GDBusInterfaceInfo          *interface_info,
5128                                    const GDBusInterfaceVTable  *vtable,
5129                                    gpointer                     user_data,
5130                                    GDestroyNotify               user_data_free_func,
5131                                    GError                     **error)
5132 {
5133   ExportedObject *eo;
5134   ExportedInterface *ei;
5135   guint ret;
5136
5137   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5138   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5139   g_return_val_if_fail (interface_info != NULL, 0);
5140   g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5141   g_return_val_if_fail (error == NULL || *error == NULL, 0);
5142   g_return_val_if_fail (check_initialized (connection), 0);
5143
5144   ret = 0;
5145
5146   CONNECTION_LOCK (connection);
5147
5148   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5149   if (eo == NULL)
5150     {
5151       eo = g_new0 (ExportedObject, 1);
5152       eo->object_path = g_strdup (object_path);
5153       eo->connection = connection;
5154       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5155                                                      g_str_equal,
5156                                                      NULL,
5157                                                      (GDestroyNotify) exported_interface_free);
5158       g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5159     }
5160
5161   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5162   if (ei != NULL)
5163     {
5164       g_set_error (error,
5165                    G_IO_ERROR,
5166                    G_IO_ERROR_EXISTS,
5167                    _("An object is already exported for the interface %s at %s"),
5168                    interface_info->name,
5169                    object_path);
5170       goto out;
5171     }
5172
5173   ei = g_new0 (ExportedInterface, 1);
5174   ei->id = g_atomic_int_add (&_global_registration_id, 1); /* TODO: overflow etc. */
5175   ei->eo = eo;
5176   ei->user_data = user_data;
5177   ei->user_data_free_func = user_data_free_func;
5178   ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5179   ei->interface_info = g_dbus_interface_info_ref (interface_info);
5180   g_dbus_interface_info_cache_build (ei->interface_info);
5181   ei->interface_name = g_strdup (interface_info->name);
5182   ei->context = g_main_context_ref_thread_default ();
5183
5184   g_hash_table_insert (eo->map_if_name_to_ei,
5185                        (gpointer) ei->interface_name,
5186                        ei);
5187   g_hash_table_insert (connection->map_id_to_ei,
5188                        GUINT_TO_POINTER (ei->id),
5189                        ei);
5190
5191   ret = ei->id;
5192
5193  out:
5194   CONNECTION_UNLOCK (connection);
5195
5196   return ret;
5197 }
5198
5199 /**
5200  * g_dbus_connection_unregister_object:
5201  * @connection: a #GDBusConnection
5202  * @registration_id: a registration id obtained from
5203  *     g_dbus_connection_register_object()
5204  *
5205  * Unregisters an object.
5206  *
5207  * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5208  *
5209  * Since: 2.26
5210  */
5211 gboolean
5212 g_dbus_connection_unregister_object (GDBusConnection *connection,
5213                                      guint            registration_id)
5214 {
5215   ExportedInterface *ei;
5216   ExportedObject *eo;
5217   gboolean ret;
5218
5219   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5220   g_return_val_if_fail (check_initialized (connection), FALSE);
5221
5222   ret = FALSE;
5223
5224   CONNECTION_LOCK (connection);
5225
5226   ei = g_hash_table_lookup (connection->map_id_to_ei,
5227                             GUINT_TO_POINTER (registration_id));
5228   if (ei == NULL)
5229     goto out;
5230
5231   eo = ei->eo;
5232
5233   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5234   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5235   /* unregister object path if we have no more exported interfaces */
5236   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5237     g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5238                                          eo->object_path));
5239
5240   ret = TRUE;
5241
5242  out:
5243   CONNECTION_UNLOCK (connection);
5244
5245   return ret;
5246 }
5247
5248 typedef struct {
5249   GClosure *method_call_closure;
5250   GClosure *get_property_closure;
5251   GClosure *set_property_closure;
5252 } RegisterObjectData;
5253
5254 static RegisterObjectData *
5255 register_object_data_new (GClosure *method_call_closure,
5256                           GClosure *get_property_closure,
5257                           GClosure *set_property_closure)
5258 {
5259   RegisterObjectData *data;
5260
5261   data = g_new0 (RegisterObjectData, 1);
5262
5263   if (method_call_closure != NULL)
5264     {
5265       data->method_call_closure = g_closure_ref (method_call_closure);
5266       g_closure_sink (method_call_closure);
5267       if (G_CLOSURE_NEEDS_MARSHAL (method_call_closure))
5268         g_closure_set_marshal (method_call_closure, g_cclosure_marshal_generic);
5269     }
5270
5271   if (get_property_closure != NULL)
5272     {
5273       data->get_property_closure = g_closure_ref (get_property_closure);
5274       g_closure_sink (get_property_closure);
5275       if (G_CLOSURE_NEEDS_MARSHAL (get_property_closure))
5276         g_closure_set_marshal (get_property_closure, g_cclosure_marshal_generic);
5277     }
5278
5279   if (set_property_closure != NULL)
5280     {
5281       data->set_property_closure = g_closure_ref (set_property_closure);
5282       g_closure_sink (set_property_closure);
5283       if (G_CLOSURE_NEEDS_MARSHAL (set_property_closure))
5284         g_closure_set_marshal (set_property_closure, g_cclosure_marshal_generic);
5285     }
5286
5287   return data;
5288 }
5289
5290 static void
5291 register_object_free_func (gpointer user_data)
5292 {
5293   RegisterObjectData *data = user_data;
5294
5295   g_clear_pointer (&data->method_call_closure, g_closure_unref);
5296   g_clear_pointer (&data->get_property_closure, g_closure_unref);
5297   g_clear_pointer (&data->set_property_closure, g_closure_unref);
5298
5299   g_free (data);
5300 }
5301
5302 static void
5303 register_with_closures_on_method_call (GDBusConnection       *connection,
5304                                        const gchar           *sender,
5305                                        const gchar           *object_path,
5306                                        const gchar           *interface_name,
5307                                        const gchar           *method_name,
5308                                        GVariant              *parameters,
5309                                        GDBusMethodInvocation *invocation,
5310                                        gpointer               user_data)
5311 {
5312   RegisterObjectData *data = user_data;
5313   GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5314
5315   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
5316   g_value_set_object (&params[0], connection);
5317
5318   g_value_init (&params[1], G_TYPE_STRING);
5319   g_value_set_string (&params[1], sender);
5320
5321   g_value_init (&params[2], G_TYPE_STRING);
5322   g_value_set_string (&params[2], object_path);
5323
5324   g_value_init (&params[3], G_TYPE_STRING);
5325   g_value_set_string (&params[3], interface_name);
5326
5327   g_value_init (&params[4], G_TYPE_STRING);
5328   g_value_set_string (&params[4], method_name);
5329
5330   g_value_init (&params[5], G_TYPE_VARIANT);
5331   g_value_set_variant (&params[5], parameters);
5332
5333   g_value_init (&params[6], G_TYPE_DBUS_METHOD_INVOCATION);
5334   g_value_set_object (&params[6], invocation);
5335
5336   g_closure_invoke (data->method_call_closure, NULL, G_N_ELEMENTS (params), params, NULL);
5337
5338   g_value_unset (params + 0);
5339   g_value_unset (params + 1);
5340   g_value_unset (params + 2);
5341   g_value_unset (params + 3);
5342   g_value_unset (params + 4);
5343   g_value_unset (params + 5);
5344   g_value_unset (params + 6);
5345 }
5346
5347 static GVariant *
5348 register_with_closures_on_get_property (GDBusConnection *connection,
5349                                         const gchar     *sender,
5350                                         const gchar     *object_path,
5351                                         const gchar     *interface_name,
5352                                         const gchar     *property_name,
5353                                         GError         **error,
5354                                         gpointer         user_data)
5355 {
5356   RegisterObjectData *data = user_data;
5357   GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5358   GValue result_value = G_VALUE_INIT;
5359   GVariant *result;
5360
5361   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
5362   g_value_set_object (&params[0], connection);
5363
5364   g_value_init (&params[1], G_TYPE_STRING);
5365   g_value_set_string (&params[1], sender);
5366
5367   g_value_init (&params[2], G_TYPE_STRING);
5368   g_value_set_string (&params[2], object_path);
5369
5370   g_value_init (&params[3], G_TYPE_STRING);
5371   g_value_set_string (&params[3], interface_name);
5372
5373   g_value_init (&params[4], G_TYPE_STRING);
5374   g_value_set_string (&params[4], property_name);
5375
5376   g_value_init (&result_value, G_TYPE_VARIANT);
5377
5378   g_closure_invoke (data->get_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5379
5380   result = g_value_get_variant (&result_value);
5381   if (result)
5382     g_variant_ref (result);
5383
5384   g_value_unset (params + 0);
5385   g_value_unset (params + 1);
5386   g_value_unset (params + 2);
5387   g_value_unset (params + 3);
5388   g_value_unset (params + 4);
5389   g_value_unset (&result_value);
5390
5391   if (!result)
5392     g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5393                  _("Unable to retrieve property %s.%s"),
5394                  interface_name, property_name);
5395
5396   return result;
5397 }
5398
5399 static gboolean
5400 register_with_closures_on_set_property (GDBusConnection *connection,
5401                                         const gchar     *sender,
5402                                         const gchar     *object_path,
5403                                         const gchar     *interface_name,
5404                                         const gchar     *property_name,
5405                                         GVariant        *value,
5406                                         GError         **error,
5407                                         gpointer         user_data)
5408 {
5409   RegisterObjectData *data = user_data;
5410   GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5411   GValue result_value = G_VALUE_INIT;
5412   gboolean result;
5413
5414   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
5415   g_value_set_object (&params[0], connection);
5416
5417   g_value_init (&params[1], G_TYPE_STRING);
5418   g_value_set_string (&params[1], sender);
5419
5420   g_value_init (&params[2], G_TYPE_STRING);
5421   g_value_set_string (&params[2], object_path);
5422
5423   g_value_init (&params[3], G_TYPE_STRING);
5424   g_value_set_string (&params[3], interface_name);
5425
5426   g_value_init (&params[4], G_TYPE_STRING);
5427   g_value_set_string (&params[4], property_name);
5428
5429   g_value_init (&params[5], G_TYPE_VARIANT);
5430   g_value_set_variant (&params[5], value);
5431
5432   g_value_init (&result_value, G_TYPE_BOOLEAN);
5433
5434   g_closure_invoke (data->set_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5435
5436   result = g_value_get_boolean (&result_value);
5437
5438   g_value_unset (params + 0);
5439   g_value_unset (params + 1);
5440   g_value_unset (params + 2);
5441   g_value_unset (params + 3);
5442   g_value_unset (params + 4);
5443   g_value_unset (params + 5);
5444   g_value_unset (&result_value);
5445
5446   if (!result)
5447     g_set_error (error,
5448                  G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5449                  _("Unable to set property %s.%s"),
5450                  interface_name, property_name);
5451
5452   return result;
5453 }
5454
5455 /**
5456  * g_dbus_connection_register_object_with_closures: (rename-to g_dbus_connection_register_object)
5457  * @connection: A #GDBusConnection.
5458  * @object_path: The object path to register at.
5459  * @interface_info: Introspection data for the interface.
5460  * @method_call_closure: (nullable): #GClosure for handling incoming method calls.
5461  * @get_property_closure: (nullable): #GClosure for getting a property.
5462  * @set_property_closure: (nullable): #GClosure for setting a property.
5463  * @error: Return location for error or %NULL.
5464  *
5465  * Version of g_dbus_connection_register_object() using closures instead of a
5466  * #GDBusInterfaceVTable for easier binding in other languages.
5467  *
5468  * Returns: 0 if @error is set, otherwise a registration id (never 0)
5469  * that can be used with g_dbus_connection_unregister_object() .
5470  *
5471  * Since: 2.46
5472  */
5473 guint
5474 g_dbus_connection_register_object_with_closures (GDBusConnection     *connection,
5475                                                  const gchar         *object_path,
5476                                                  GDBusInterfaceInfo  *interface_info,
5477                                                  GClosure            *method_call_closure,
5478                                                  GClosure            *get_property_closure,
5479                                                  GClosure            *set_property_closure,
5480                                                  GError             **error)
5481 {
5482   RegisterObjectData *data;
5483   GDBusInterfaceVTable vtable =
5484     {
5485       method_call_closure != NULL  ? register_with_closures_on_method_call  : NULL,
5486       get_property_closure != NULL ? register_with_closures_on_get_property : NULL,
5487       set_property_closure != NULL ? register_with_closures_on_set_property : NULL
5488     };
5489
5490   data = register_object_data_new (method_call_closure, get_property_closure, set_property_closure);
5491
5492   return g_dbus_connection_register_object (connection,
5493                                             object_path,
5494                                             interface_info,
5495                                             &vtable,
5496                                             data,
5497                                             register_object_free_func,
5498                                             error);
5499 }
5500
5501 /* ---------------------------------------------------------------------------------------------------- */
5502
5503 /**
5504  * g_dbus_connection_emit_signal:
5505  * @connection: a #GDBusConnection
5506  * @destination_bus_name: (nullable): the unique bus name for the destination
5507  *     for the signal or %NULL to emit to all listeners
5508  * @object_path: path of remote object
5509  * @interface_name: D-Bus interface to emit a signal on
5510  * @signal_name: the name of the signal to emit
5511  * @parameters: (nullable): a #GVariant tuple with parameters for the signal
5512  *              or %NULL if not passing parameters
5513  * @error: Return location for error or %NULL
5514  *
5515  * Emits a signal.
5516  *
5517  * If the parameters GVariant is floating, it is consumed.
5518  *
5519  * This can only fail if @parameters is not compatible with the D-Bus protocol
5520  * (%G_IO_ERROR_INVALID_ARGUMENT), or if @connection has been closed
5521  * (%G_IO_ERROR_CLOSED).
5522  *
5523  * Returns: %TRUE unless @error is set
5524  *
5525  * Since: 2.26
5526  */
5527 gboolean
5528 g_dbus_connection_emit_signal (GDBusConnection  *connection,
5529                                const gchar      *destination_bus_name,
5530                                const gchar      *object_path,
5531                                const gchar      *interface_name,
5532                                const gchar      *signal_name,
5533                                GVariant         *parameters,
5534                                GError          **error)
5535 {
5536   GDBusMessage *message;
5537   gboolean ret;
5538
5539   message = NULL;
5540   ret = FALSE;
5541
5542   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5543   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5544   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5545   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5546   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5547   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5548   g_return_val_if_fail (check_initialized (connection), FALSE);
5549
5550   if (G_UNLIKELY (_g_dbus_debug_emission ()))
5551     {
5552       _g_dbus_debug_print_lock ();
5553       g_print ("========================================================================\n"
5554                "GDBus-debug:Emission:\n"
5555                " >>>> SIGNAL EMISSION %s.%s()\n"
5556                "      on object %s\n"
5557                "      destination %s\n",
5558                interface_name, signal_name,
5559                object_path,
5560                destination_bus_name != NULL ? destination_bus_name : "(none)");
5561       _g_dbus_debug_print_unlock ();
5562     }
5563
5564   message = g_dbus_message_new_signal (object_path,
5565                                        interface_name,
5566                                        signal_name);
5567
5568   if (destination_bus_name != NULL)
5569     g_dbus_message_set_header (message,
5570                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5571                                g_variant_new_string (destination_bus_name));
5572
5573   if (parameters != NULL)
5574     g_dbus_message_set_body (message, parameters);
5575
5576   ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5577   g_object_unref (message);
5578
5579   return ret;
5580 }
5581
5582 static void
5583 add_call_flags (GDBusMessage           *message,
5584                          GDBusCallFlags  flags)
5585 {
5586   GDBusMessageFlags msg_flags = 0;
5587
5588   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5589     msg_flags |= G_DBUS_MESSAGE_FLAGS_NO_AUTO_START;
5590   if (flags & G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
5591     msg_flags |= G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION;
5592   if (msg_flags)
5593     g_dbus_message_set_flags (message, msg_flags);
5594 }
5595
5596 static GVariant *
5597 decode_method_reply (GDBusMessage        *reply,
5598                      const gchar         *method_name,
5599                      const GVariantType  *reply_type,
5600                      GUnixFDList        **out_fd_list,
5601                      GError             **error)
5602 {
5603   GVariant *result;
5604
5605   result = NULL;
5606   switch (g_dbus_message_get_message_type (reply))
5607     {
5608     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5609       result = g_dbus_message_get_body (reply);
5610       if (result == NULL)
5611         {
5612           result = g_variant_new ("()");
5613           g_variant_ref_sink (result);
5614         }
5615       else
5616         {
5617           g_variant_ref (result);
5618         }
5619
5620       if (!g_variant_is_of_type (result, reply_type))
5621         {
5622           gchar *type_string = g_variant_type_dup_string (reply_type);
5623
5624           g_set_error (error,
5625                        G_IO_ERROR,
5626                        G_IO_ERROR_INVALID_ARGUMENT,
5627                        _("Method '%s' returned type '%s', but expected '%s'"),
5628                        method_name, g_variant_get_type_string (result), type_string);
5629
5630           g_variant_unref (result);
5631           g_free (type_string);
5632           result = NULL;
5633         }
5634
5635 #ifdef G_OS_UNIX
5636       if (result != NULL)
5637         {
5638           if (out_fd_list != NULL)
5639             {
5640               *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5641               if (*out_fd_list != NULL)
5642                 g_object_ref (*out_fd_list);
5643             }
5644         }
5645 #endif
5646       break;
5647
5648     case G_DBUS_MESSAGE_TYPE_ERROR:
5649       g_dbus_message_to_gerror (reply, error);
5650       break;
5651
5652     default:
5653       g_assert_not_reached ();
5654       break;
5655     }
5656
5657   return result;
5658 }
5659
5660
5661 typedef struct
5662 {
5663   GVariantType *reply_type;
5664   gchar *method_name; /* for error message */
5665
5666   GUnixFDList *fd_list;
5667 } CallState;
5668
5669 static void
5670 call_state_free (CallState *state)
5671 {
5672   g_variant_type_free (state->reply_type);
5673   g_free (state->method_name);
5674
5675   if (state->fd_list != NULL)
5676     g_object_unref (state->fd_list);
5677   g_slice_free (CallState, state);
5678 }
5679
5680 /* called in any thread, with the connection's lock not held */
5681 static void
5682 g_dbus_connection_call_done (GObject      *source,
5683                              GAsyncResult *result,
5684                              gpointer      user_data)
5685 {
5686   GDBusConnection *connection = G_DBUS_CONNECTION (source);
5687   GTask *task = user_data;
5688   CallState *state = g_task_get_task_data (task);
5689   GError *error = NULL;
5690   GDBusMessage *reply;
5691   GVariant *value = NULL;
5692
5693   reply = g_dbus_connection_send_message_with_reply_finish (connection,
5694                                                             result,
5695                                                             &error);
5696
5697   if (G_UNLIKELY (_g_dbus_debug_call ()))
5698     {
5699       _g_dbus_debug_print_lock ();
5700       g_print ("========================================================================\n"
5701                "GDBus-debug:Call:\n"
5702                " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5703                "      ",
5704                state->method_name,
5705                g_dbus_message_get_reply_serial (reply));
5706       if (reply != NULL)
5707         {
5708           g_print ("SUCCESS\n");
5709         }
5710       else
5711         {
5712           g_print ("FAILED: %s\n",
5713                    error->message);
5714         }
5715       _g_dbus_debug_print_unlock ();
5716     }
5717
5718   if (reply != NULL)
5719     value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5720
5721   if (error != NULL)
5722     g_task_return_error (task, error);
5723   else
5724     g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5725
5726   g_clear_object (&reply);
5727   g_object_unref (task);
5728 }
5729
5730 /* called in any thread, with the connection's lock not held */
5731 static void
5732 g_dbus_connection_call_internal (GDBusConnection        *connection,
5733                                  const gchar            *bus_name,
5734                                  const gchar            *object_path,
5735                                  const gchar            *interface_name,
5736                                  const gchar            *method_name,
5737                                  GVariant               *parameters,
5738                                  const GVariantType     *reply_type,
5739                                  GDBusCallFlags          flags,
5740                                  gint                    timeout_msec,
5741                                  GUnixFDList            *fd_list,
5742                                  GCancellable           *cancellable,
5743                                  GAsyncReadyCallback     callback,
5744                                  gpointer                user_data)
5745 {
5746   GDBusMessage *message;
5747   guint32 serial;
5748
5749   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5750   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5751   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5752   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5753   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5754   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5755   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5756   g_return_if_fail (check_initialized (connection));
5757 #ifdef G_OS_UNIX
5758   g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5759 #else
5760   g_return_if_fail (fd_list == NULL);
5761 #endif
5762
5763   message = g_dbus_message_new_method_call (bus_name,
5764                                             object_path,
5765                                             interface_name,
5766                                             method_name);
5767   add_call_flags (message, flags);
5768   if (parameters != NULL)
5769     g_dbus_message_set_body (message, parameters);
5770
5771 #ifdef G_OS_UNIX
5772   if (fd_list != NULL)
5773     g_dbus_message_set_unix_fd_list (message, fd_list);
5774 #endif
5775
5776   /* If the user has no callback then we can just send the message with
5777    * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5778    * the logic for processing the reply.  If the service sends the reply
5779    * anyway then it will just be ignored.
5780    */
5781   if (callback != NULL)
5782     {
5783       CallState *state;
5784       GTask *task;
5785
5786       state = g_slice_new0 (CallState);
5787       state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5788
5789       if (reply_type == NULL)
5790         reply_type = G_VARIANT_TYPE_ANY;
5791
5792       state->reply_type = g_variant_type_copy (reply_type);
5793
5794       task = g_task_new (connection, cancellable, callback, user_data);
5795       g_task_set_source_tag (task, g_dbus_connection_call_internal);
5796       g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5797
5798       g_dbus_connection_send_message_with_reply (connection,
5799                                                  message,
5800                                                  G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5801                                                  timeout_msec,
5802                                                  &serial,
5803                                                  cancellable,
5804                                                  g_dbus_connection_call_done,
5805                                                  task);
5806     }
5807   else
5808     {
5809       GDBusMessageFlags flags;
5810
5811       flags = g_dbus_message_get_flags (message);
5812       flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5813       g_dbus_message_set_flags (message, flags);
5814
5815       g_dbus_connection_send_message (connection,
5816                                       message,
5817                                       G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5818                                       &serial, NULL);
5819     }
5820
5821   if (G_UNLIKELY (_g_dbus_debug_call ()))
5822     {
5823       _g_dbus_debug_print_lock ();
5824       g_print ("========================================================================\n"
5825                "GDBus-debug:Call:\n"
5826                " >>>> ASYNC %s.%s()\n"
5827                "      on object %s\n"
5828                "      owned by name %s (serial %d)\n",
5829                interface_name,
5830                method_name,
5831                object_path,
5832                bus_name != NULL ? bus_name : "(none)",
5833                serial);
5834       _g_dbus_debug_print_unlock ();
5835     }
5836
5837   if (message != NULL)
5838     g_object_unref (message);
5839 }
5840
5841 /* called in any thread, with the connection's lock not held */
5842 static GVariant *
5843 g_dbus_connection_call_finish_internal (GDBusConnection  *connection,
5844                                         GUnixFDList     **out_fd_list,
5845                                         GAsyncResult     *res,
5846                                         GError          **error)
5847 {
5848   GTask *task;
5849   CallState *state;
5850   GVariant *ret;
5851
5852   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5853   g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5854   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5855
5856   task = G_TASK (res);
5857   state = g_task_get_task_data (task);
5858
5859   ret = g_task_propagate_pointer (task, error);
5860   if (!ret)
5861     return NULL;
5862
5863   if (out_fd_list != NULL)
5864     *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5865   return ret;
5866 }
5867
5868 /* called in any user thread, with the connection's lock not held */
5869 static GVariant *
5870 g_dbus_connection_call_sync_internal (GDBusConnection         *connection,
5871                                       const gchar             *bus_name,
5872                                       const gchar             *object_path,
5873                                       const gchar             *interface_name,
5874                                       const gchar             *method_name,
5875                                       GVariant                *parameters,
5876                                       const GVariantType      *reply_type,
5877                                       GDBusCallFlags           flags,
5878                                       gint                     timeout_msec,
5879                                       GUnixFDList             *fd_list,
5880                                       GUnixFDList            **out_fd_list,
5881                                       GCancellable            *cancellable,
5882                                       GError                 **error)
5883 {
5884   GDBusMessage *message;
5885   GDBusMessage *reply;
5886   GVariant *result;
5887   GError *local_error;
5888   GDBusSendMessageFlags send_flags;
5889
5890   message = NULL;
5891   reply = NULL;
5892   result = NULL;
5893
5894   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5895   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5896   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5897   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5898   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5899   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5900   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5901 #ifdef G_OS_UNIX
5902   g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5903 #else
5904   g_return_val_if_fail (fd_list == NULL, NULL);
5905 #endif
5906   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5907
5908   if (!(flags & CALL_FLAGS_INITIALIZING))
5909     g_return_val_if_fail (check_initialized (connection), FALSE);
5910
5911   if (reply_type == NULL)
5912     reply_type = G_VARIANT_TYPE_ANY;
5913
5914   message = g_dbus_message_new_method_call (bus_name,
5915                                             object_path,
5916                                             interface_name,
5917                                             method_name);
5918   add_call_flags (message, flags);
5919   if (parameters != NULL)
5920     g_dbus_message_set_body (message, parameters);
5921
5922 #ifdef G_OS_UNIX
5923   if (fd_list != NULL)
5924     g_dbus_message_set_unix_fd_list (message, fd_list);
5925 #endif
5926
5927   if (G_UNLIKELY (_g_dbus_debug_call ()))
5928     {
5929       _g_dbus_debug_print_lock ();
5930       g_print ("========================================================================\n"
5931                "GDBus-debug:Call:\n"
5932                " >>>> SYNC %s.%s()\n"
5933                "      on object %s\n"
5934                "      owned by name %s\n",
5935                interface_name,
5936                method_name,
5937                object_path,
5938                bus_name != NULL ? bus_name : "(none)");
5939       _g_dbus_debug_print_unlock ();
5940     }
5941
5942   local_error = NULL;
5943
5944   send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5945
5946   /* translate from one flavour of flags to another... */
5947   if (flags & CALL_FLAGS_INITIALIZING)
5948     send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5949
5950   reply = g_dbus_connection_send_message_with_reply_sync (connection,
5951                                                           message,
5952                                                           send_flags,
5953                                                           timeout_msec,
5954                                                           NULL, /* volatile guint32 *out_serial */
5955                                                           cancellable,
5956                                                           &local_error);
5957
5958   if (G_UNLIKELY (_g_dbus_debug_call ()))
5959     {
5960       _g_dbus_debug_print_lock ();
5961       g_print ("========================================================================\n"
5962                "GDBus-debug:Call:\n"
5963                " <<<< SYNC COMPLETE %s.%s()\n"
5964                "      ",
5965                interface_name,
5966                method_name);
5967       if (reply != NULL)
5968         {
5969           g_print ("SUCCESS\n");
5970         }
5971       else
5972         {
5973           g_print ("FAILED: %s\n",
5974                    local_error->message);
5975         }
5976       _g_dbus_debug_print_unlock ();
5977     }
5978
5979   if (reply == NULL)
5980     {
5981       if (error != NULL)
5982         *error = local_error;
5983       else
5984         g_error_free (local_error);
5985       goto out;
5986     }
5987
5988   result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5989
5990  out:
5991   if (message != NULL)
5992     g_object_unref (message);
5993   if (reply != NULL)
5994     g_object_unref (reply);
5995
5996   return result;
5997 }
5998
5999 /* ---------------------------------------------------------------------------------------------------- */
6000
6001 /**
6002  * g_dbus_connection_call:
6003  * @connection: a #GDBusConnection
6004  * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6005  *     @connection is not a message bus connection
6006  * @object_path: path of remote object
6007  * @interface_name: D-Bus interface to invoke method on
6008  * @method_name: the name of the method to invoke
6009  * @parameters: (nullable): a #GVariant tuple with parameters for the method
6010  *     or %NULL if not passing parameters
6011  * @reply_type: (nullable): the expected type of the reply (which will be a
6012  *     tuple), or %NULL
6013  * @flags: flags from the #GDBusCallFlags enumeration
6014  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6015  *     timeout or %G_MAXINT for no timeout
6016  * @cancellable: (nullable): a #GCancellable or %NULL
6017  * @callback: (nullable): a #GAsyncReadyCallback to call when the request
6018  *     is satisfied or %NULL if you don't care about the result of the
6019  *     method invocation
6020  * @user_data: the data to pass to @callback
6021  *
6022  * Asynchronously invokes the @method_name method on the
6023  * @interface_name D-Bus interface on the remote object at
6024  * @object_path owned by @bus_name.
6025  *
6026  * If @connection is closed then the operation will fail with
6027  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6028  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6029  * not compatible with the D-Bus protocol, the operation fails with
6030  * %G_IO_ERROR_INVALID_ARGUMENT.
6031  *
6032  * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6033  * error will be raised if it does not match.  Said another way, if you give a @reply_type
6034  * then any non-%NULL return value will be of this type. Unless it’s
6035  * %G_VARIANT_TYPE_UNIT, the @reply_type will be a tuple containing one or more
6036  * values.
6037  *
6038  * If the @parameters #GVariant is floating, it is consumed. This allows
6039  * convenient 'inline' use of g_variant_new(), e.g.:
6040  * |[<!-- language="C" -->
6041  *  g_dbus_connection_call (connection,
6042  *                          "org.freedesktop.StringThings",
6043  *                          "/org/freedesktop/StringThings",
6044  *                          "org.freedesktop.StringThings",
6045  *                          "TwoStrings",
6046  *                          g_variant_new ("(ss)",
6047  *                                         "Thing One",
6048  *                                         "Thing Two"),
6049  *                          NULL,
6050  *                          G_DBUS_CALL_FLAGS_NONE,
6051  *                          -1,
6052  *                          NULL,
6053  *                          (GAsyncReadyCallback) two_strings_done,
6054  *                          NULL);
6055  * ]|
6056  *
6057  * This is an asynchronous method. When the operation is finished,
6058  * @callback will be invoked in the
6059  * [thread-default main context][g-main-context-push-thread-default]
6060  * of the thread you are calling this method from. You can then call
6061  * g_dbus_connection_call_finish() to get the result of the operation.
6062  * See g_dbus_connection_call_sync() for the synchronous version of this
6063  * function.
6064  *
6065  * If @callback is %NULL then the D-Bus method call message will be sent with
6066  * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6067  *
6068  * Since: 2.26
6069  */
6070 void
6071 g_dbus_connection_call (GDBusConnection     *connection,
6072                         const gchar         *bus_name,
6073                         const gchar         *object_path,
6074                         const gchar         *interface_name,
6075                         const gchar         *method_name,
6076                         GVariant            *parameters,
6077                         const GVariantType  *reply_type,
6078                         GDBusCallFlags       flags,
6079                         gint                 timeout_msec,
6080                         GCancellable        *cancellable,
6081                         GAsyncReadyCallback  callback,
6082                         gpointer             user_data)
6083 {
6084   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);
6085 }
6086
6087 /**
6088  * g_dbus_connection_call_finish:
6089  * @connection: a #GDBusConnection
6090  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6091  * @error: return location for error or %NULL
6092  *
6093  * Finishes an operation started with g_dbus_connection_call().
6094  *
6095  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6096  *     return values. Free with g_variant_unref().
6097  *
6098  * Since: 2.26
6099  */
6100 GVariant *
6101 g_dbus_connection_call_finish (GDBusConnection  *connection,
6102                                GAsyncResult     *res,
6103                                GError          **error)
6104 {
6105   return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6106 }
6107
6108 /**
6109  * g_dbus_connection_call_sync:
6110  * @connection: a #GDBusConnection
6111  * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6112  *     @connection is not a message bus connection
6113  * @object_path: path of remote object
6114  * @interface_name: D-Bus interface to invoke method on
6115  * @method_name: the name of the method to invoke
6116  * @parameters: (nullable): a #GVariant tuple with parameters for the method
6117  *     or %NULL if not passing parameters
6118  * @reply_type: (nullable): the expected type of the reply, or %NULL
6119  * @flags: flags from the #GDBusCallFlags enumeration
6120  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6121  *     timeout or %G_MAXINT for no timeout
6122  * @cancellable: (nullable): a #GCancellable or %NULL
6123  * @error: return location for error or %NULL
6124  *
6125  * Synchronously invokes the @method_name method on the
6126  * @interface_name D-Bus interface on the remote object at
6127  * @object_path owned by @bus_name.
6128  *
6129  * If @connection is closed then the operation will fail with
6130  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6131  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6132  * contains a value not compatible with the D-Bus protocol, the operation
6133  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6134  *
6135  * If @reply_type is non-%NULL then the reply will be checked for having
6136  * this type and an error will be raised if it does not match.  Said
6137  * another way, if you give a @reply_type then any non-%NULL return
6138  * value will be of this type.
6139  *
6140  * If the @parameters #GVariant is floating, it is consumed.
6141  * This allows convenient 'inline' use of g_variant_new(), e.g.:
6142  * |[<!-- language="C" -->
6143  *  g_dbus_connection_call_sync (connection,
6144  *                               "org.freedesktop.StringThings",
6145  *                               "/org/freedesktop/StringThings",
6146  *                               "org.freedesktop.StringThings",
6147  *                               "TwoStrings",
6148  *                               g_variant_new ("(ss)",
6149  *                                              "Thing One",
6150  *                                              "Thing Two"),
6151  *                               NULL,
6152  *                               G_DBUS_CALL_FLAGS_NONE,
6153  *                               -1,
6154  *                               NULL,
6155  *                               &error);
6156  * ]|
6157  *
6158  * The calling thread is blocked until a reply is received. See
6159  * g_dbus_connection_call() for the asynchronous version of
6160  * this method.
6161  *
6162  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6163  *     return values. Free with g_variant_unref().
6164  *
6165  * Since: 2.26
6166  */
6167 GVariant *
6168 g_dbus_connection_call_sync (GDBusConnection     *connection,
6169                              const gchar         *bus_name,
6170                              const gchar         *object_path,
6171                              const gchar         *interface_name,
6172                              const gchar         *method_name,
6173                              GVariant            *parameters,
6174                              const GVariantType  *reply_type,
6175                              GDBusCallFlags       flags,
6176                              gint                 timeout_msec,
6177                              GCancellable        *cancellable,
6178                              GError             **error)
6179 {
6180   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);
6181 }
6182
6183 /* ---------------------------------------------------------------------------------------------------- */
6184
6185 #ifdef G_OS_UNIX
6186
6187 /**
6188  * g_dbus_connection_call_with_unix_fd_list:
6189  * @connection: a #GDBusConnection
6190  * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6191  *     @connection is not a message bus connection
6192  * @object_path: path of remote object
6193  * @interface_name: D-Bus interface to invoke method on
6194  * @method_name: the name of the method to invoke
6195  * @parameters: (nullable): a #GVariant tuple with parameters for the method
6196  *     or %NULL if not passing parameters
6197  * @reply_type: (nullable): the expected type of the reply, or %NULL
6198  * @flags: flags from the #GDBusCallFlags enumeration
6199  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6200  *     timeout or %G_MAXINT for no timeout
6201  * @fd_list: (nullable): a #GUnixFDList or %NULL
6202  * @cancellable: (nullable): a #GCancellable or %NULL
6203  * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
6204  *     satisfied or %NULL if you don't * care about the result of the
6205  *     method invocation
6206  * @user_data: The data to pass to @callback.
6207  *
6208  * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6209  *
6210  * This method is only available on UNIX.
6211  *
6212  * Since: 2.30
6213  */
6214 void
6215 g_dbus_connection_call_with_unix_fd_list (GDBusConnection     *connection,
6216                                           const gchar         *bus_name,
6217                                           const gchar         *object_path,
6218                                           const gchar         *interface_name,
6219                                           const gchar         *method_name,
6220                                           GVariant            *parameters,
6221                                           const GVariantType  *reply_type,
6222                                           GDBusCallFlags       flags,
6223                                           gint                 timeout_msec,
6224                                           GUnixFDList         *fd_list,
6225                                           GCancellable        *cancellable,
6226                                           GAsyncReadyCallback  callback,
6227                                           gpointer             user_data)
6228 {
6229   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);
6230 }
6231
6232 /**
6233  * g_dbus_connection_call_with_unix_fd_list_finish:
6234  * @connection: a #GDBusConnection
6235  * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6236  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6237  *     g_dbus_connection_call_with_unix_fd_list()
6238  * @error: return location for error or %NULL
6239  *
6240  * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6241  *
6242  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6243  *     return values. Free with g_variant_unref().
6244  *
6245  * Since: 2.30
6246  */
6247 GVariant *
6248 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection  *connection,
6249                                                  GUnixFDList     **out_fd_list,
6250                                                  GAsyncResult     *res,
6251                                                  GError          **error)
6252 {
6253   return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6254 }
6255
6256 /**
6257  * g_dbus_connection_call_with_unix_fd_list_sync:
6258  * @connection: a #GDBusConnection
6259  * @bus_name: (nullable): a unique or well-known bus name or %NULL
6260  *     if @connection is not a message bus connection
6261  * @object_path: path of remote object
6262  * @interface_name: D-Bus interface to invoke method on
6263  * @method_name: the name of the method to invoke
6264  * @parameters: (nullable): a #GVariant tuple with parameters for
6265  *     the method or %NULL if not passing parameters
6266  * @reply_type: (nullable): the expected type of the reply, or %NULL
6267  * @flags: flags from the #GDBusCallFlags enumeration
6268  * @timeout_msec: the timeout in milliseconds, -1 to use the default
6269  *     timeout or %G_MAXINT for no timeout
6270  * @fd_list: (nullable): a #GUnixFDList or %NULL
6271  * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6272  * @cancellable: (nullable): a #GCancellable or %NULL
6273  * @error: return location for error or %NULL
6274  *
6275  * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6276  *
6277  * This method is only available on UNIX.
6278  *
6279  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6280  *     return values. Free with g_variant_unref().
6281  *
6282  * Since: 2.30
6283  */
6284 GVariant *
6285 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection     *connection,
6286                                                const gchar         *bus_name,
6287                                                const gchar         *object_path,
6288                                                const gchar         *interface_name,
6289                                                const gchar         *method_name,
6290                                                GVariant            *parameters,
6291                                                const GVariantType  *reply_type,
6292                                                GDBusCallFlags       flags,
6293                                                gint                 timeout_msec,
6294                                                GUnixFDList         *fd_list,
6295                                                GUnixFDList        **out_fd_list,
6296                                                GCancellable        *cancellable,
6297                                                GError             **error)
6298 {
6299   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);
6300 }
6301
6302 #endif /* G_OS_UNIX */
6303
6304 /* ---------------------------------------------------------------------------------------------------- */
6305
6306 struct ExportedSubtree
6307 {
6308   guint                     id;
6309   gchar                    *object_path;
6310   GDBusConnection          *connection;
6311   GDBusSubtreeVTable       *vtable;
6312   GDBusSubtreeFlags         flags;
6313
6314   GMainContext             *context;
6315   gpointer                  user_data;
6316   GDestroyNotify            user_data_free_func;
6317 };
6318
6319 static void
6320 exported_subtree_free (ExportedSubtree *es)
6321 {
6322   call_destroy_notify (es->context,
6323                        es->user_data_free_func,
6324                        es->user_data);
6325
6326   g_main_context_unref (es->context);
6327
6328   _g_dbus_subtree_vtable_free (es->vtable);
6329   g_free (es->object_path);
6330   g_free (es);
6331 }
6332
6333 /* called without lock held in the thread where the caller registered
6334  * the subtree
6335  */
6336 static gboolean
6337 handle_subtree_introspect (GDBusConnection *connection,
6338                            ExportedSubtree *es,
6339                            GDBusMessage    *message)
6340 {
6341   GString *s;
6342   gboolean handled;
6343   GDBusMessage *reply;
6344   gchar **children;
6345   gboolean is_root;
6346   const gchar *sender;
6347   const gchar *requested_object_path;
6348   const gchar *requested_node;
6349   GDBusInterfaceInfo **interfaces;
6350   guint n;
6351   gchar **subnode_paths;
6352   gboolean has_properties_interface;
6353   gboolean has_introspectable_interface;
6354
6355   handled = FALSE;
6356
6357   requested_object_path = g_dbus_message_get_path (message);
6358   sender = g_dbus_message_get_sender (message);
6359   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6360
6361   s = g_string_new (NULL);
6362   introspect_append_header (s);
6363
6364   /* Strictly we don't need the children in dynamic mode, but we avoid the
6365    * conditionals to preserve code clarity
6366    */
6367   children = es->vtable->enumerate (es->connection,
6368                                     sender,
6369                                     es->object_path,
6370                                     es->user_data);
6371
6372   if (!is_root)
6373     {
6374       requested_node = strrchr (requested_object_path, '/') + 1;
6375
6376       /* Assert existence of object if we are not dynamic */
6377       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6378           !_g_strv_has_string ((const gchar * const *) children, requested_node))
6379         goto out;
6380     }
6381   else
6382     {
6383       requested_node = NULL;
6384     }
6385
6386   interfaces = es->vtable->introspect (es->connection,
6387                                        sender,
6388                                        es->object_path,
6389                                        requested_node,
6390                                        es->user_data);
6391   if (interfaces != NULL)
6392     {
6393       has_properties_interface = FALSE;
6394       has_introspectable_interface = FALSE;
6395
6396       for (n = 0; interfaces[n] != NULL; n++)
6397         {
6398           if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6399             has_properties_interface = TRUE;
6400           else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6401             has_introspectable_interface = TRUE;
6402         }
6403       if (!has_properties_interface)
6404         g_string_append (s, introspect_properties_interface);
6405       if (!has_introspectable_interface)
6406         g_string_append (s, introspect_introspectable_interface);
6407
6408       for (n = 0; interfaces[n] != NULL; n++)
6409         {
6410           g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6411           g_dbus_interface_info_unref (interfaces[n]);
6412         }
6413       g_free (interfaces);
6414     }
6415
6416   /* then include <node> entries from the Subtree for the root */
6417   if (is_root)
6418     {
6419       for (n = 0; children != NULL && children[n] != NULL; n++)
6420         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
6421     }
6422
6423   /* finally include nodes registered below us */
6424   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6425   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6426     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
6427   g_strfreev (subnode_paths);
6428
6429   g_string_append (s, "</node>\n");
6430
6431   reply = g_dbus_message_new_method_reply (message);
6432   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6433   g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6434   g_object_unref (reply);
6435
6436   handled = TRUE;
6437
6438  out:
6439   g_string_free (s, TRUE);
6440   g_strfreev (children);
6441   return handled;
6442 }
6443
6444 /* called without lock held in the thread where the caller registered
6445  * the subtree
6446  */
6447 static gboolean
6448 handle_subtree_method_invocation (GDBusConnection *connection,
6449                                   ExportedSubtree *es,
6450                                   GDBusMessage    *message)
6451 {
6452   gboolean handled;
6453   const gchar *sender;
6454   const gchar *interface_name;
6455   const gchar *member;
6456   const gchar *signature;
6457   const gchar *requested_object_path;
6458   const gchar *requested_node;
6459   gboolean is_root;
6460   GDBusInterfaceInfo *interface_info;
6461   const GDBusInterfaceVTable *interface_vtable;
6462   gpointer interface_user_data;
6463   guint n;
6464   GDBusInterfaceInfo **interfaces;
6465   gboolean is_property_get;
6466   gboolean is_property_set;
6467   gboolean is_property_get_all;
6468
6469   handled = FALSE;
6470   interfaces = NULL;
6471
6472   requested_object_path = g_dbus_message_get_path (message);
6473   sender = g_dbus_message_get_sender (message);
6474   interface_name = g_dbus_message_get_interface (message);
6475   member = g_dbus_message_get_member (message);
6476   signature = g_dbus_message_get_signature (message);
6477   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6478
6479   is_property_get = FALSE;
6480   is_property_set = FALSE;
6481   is_property_get_all = FALSE;
6482   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6483     {
6484       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6485         is_property_get = TRUE;
6486       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6487         is_property_set = TRUE;
6488       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6489         is_property_get_all = TRUE;
6490     }
6491
6492   if (!is_root)
6493     {
6494       requested_node = strrchr (requested_object_path, '/') + 1;
6495
6496       if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6497         {
6498           /* We don't want to dispatch to unenumerated
6499            * nodes, so ensure that the child exists.
6500            */
6501           gchar **children;
6502           gboolean exists;
6503
6504           children = es->vtable->enumerate (es->connection,
6505                                             sender,
6506                                             es->object_path,
6507                                             es->user_data);
6508
6509           exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6510           g_strfreev (children);
6511
6512           if (!exists)
6513             goto out;
6514         }
6515     }
6516   else
6517     {
6518       requested_node = NULL;
6519     }
6520
6521   /* get introspection data for the node */
6522   interfaces = es->vtable->introspect (es->connection,
6523                                        sender,
6524                                        requested_object_path,
6525                                        requested_node,
6526                                        es->user_data);
6527
6528   if (interfaces == NULL)
6529     goto out;
6530
6531   interface_info = NULL;
6532   for (n = 0; interfaces[n] != NULL; n++)
6533     {
6534       if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6535         interface_info = interfaces[n];
6536     }
6537
6538   /* dispatch the call if the user wants to handle it */
6539   if (interface_info != NULL)
6540     {
6541       /* figure out where to dispatch the method call */
6542       interface_user_data = NULL;
6543       interface_vtable = es->vtable->dispatch (es->connection,
6544                                                sender,
6545                                                es->object_path,
6546                                                interface_name,
6547                                                requested_node,
6548                                                &interface_user_data,
6549                                                es->user_data);
6550       if (interface_vtable == NULL)
6551         goto out;
6552
6553       CONNECTION_LOCK (connection);
6554       handled = validate_and_maybe_schedule_method_call (es->connection,
6555                                                          message,
6556                                                          0,
6557                                                          es->id,
6558                                                          interface_info,
6559                                                          interface_vtable,
6560                                                          es->context,
6561                                                          interface_user_data);
6562       CONNECTION_UNLOCK (connection);
6563     }
6564   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6565   else if (is_property_get || is_property_set || is_property_get_all)
6566     {
6567       if (is_property_get)
6568         g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6569       else if (is_property_set)
6570         g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6571       else if (is_property_get_all)
6572         g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6573       else
6574         g_assert_not_reached ();
6575
6576       /* see if the object supports this interface at all */
6577       for (n = 0; interfaces[n] != NULL; n++)
6578         {
6579           if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6580             interface_info = interfaces[n];
6581         }
6582
6583       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6584        * claims it won't support the interface
6585        */
6586       if (interface_info == NULL)
6587         {
6588           GDBusMessage *reply;
6589           reply = g_dbus_message_new_method_error (message,
6590                                                    "org.freedesktop.DBus.Error.InvalidArgs",
6591                                                    _("No such interface '%s'"),
6592                                                    interface_name);
6593           g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6594           g_object_unref (reply);
6595           handled = TRUE;
6596           goto out;
6597         }
6598
6599       /* figure out where to dispatch the property get/set/getall calls */
6600       interface_user_data = NULL;
6601       interface_vtable = es->vtable->dispatch (es->connection,
6602                                                sender,
6603                                                es->object_path,
6604                                                interface_name,
6605                                                requested_node,
6606                                                &interface_user_data,
6607                                                es->user_data);
6608       if (interface_vtable == NULL)
6609         {
6610           g_warning ("The subtree introspection function indicates that '%s' "
6611                      "is a valid interface name, but calling the dispatch "
6612                      "function on that interface gave us NULL", interface_name);
6613           goto out;
6614         }
6615
6616       if (is_property_get || is_property_set)
6617         {
6618           CONNECTION_LOCK (connection);
6619           handled = validate_and_maybe_schedule_property_getset (es->connection,
6620                                                                  message,
6621                                                                  0,
6622                                                                  es->id,
6623                                                                  is_property_get,
6624                                                                  interface_info,
6625                                                                  interface_vtable,
6626                                                                  es->context,
6627                                                                  interface_user_data);
6628           CONNECTION_UNLOCK (connection);
6629         }
6630       else if (is_property_get_all)
6631         {
6632           CONNECTION_LOCK (connection);
6633           handled = validate_and_maybe_schedule_property_get_all (es->connection,
6634                                                                   message,
6635                                                                   0,
6636                                                                   es->id,
6637                                                                   interface_info,
6638                                                                   interface_vtable,
6639                                                                   es->context,
6640                                                                   interface_user_data);
6641           CONNECTION_UNLOCK (connection);
6642         }
6643     }
6644
6645  out:
6646   if (interfaces != NULL)
6647     {
6648       for (n = 0; interfaces[n] != NULL; n++)
6649         g_dbus_interface_info_unref (interfaces[n]);
6650       g_free (interfaces);
6651     }
6652
6653   return handled;
6654 }
6655
6656 typedef struct
6657 {
6658   GDBusMessage *message;
6659   ExportedSubtree *es;
6660 } SubtreeDeferredData;
6661
6662 static void
6663 subtree_deferred_data_free (SubtreeDeferredData *data)
6664 {
6665   g_object_unref (data->message);
6666   g_free (data);
6667 }
6668
6669 /* called without lock held in the thread where the caller registered the subtree */
6670 static gboolean
6671 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6672 {
6673   SubtreeDeferredData *data = _data;
6674   gboolean handled;
6675
6676   handled = FALSE;
6677
6678   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6679       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6680       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6681     handled = handle_subtree_introspect (data->es->connection,
6682                                          data->es,
6683                                          data->message);
6684   else
6685     handled = handle_subtree_method_invocation (data->es->connection,
6686                                                 data->es,
6687                                                 data->message);
6688
6689   if (!handled)
6690     {
6691       CONNECTION_LOCK (data->es->connection);
6692       handled = handle_generic_unlocked (data->es->connection, data->message);
6693       CONNECTION_UNLOCK (data->es->connection);
6694     }
6695
6696   /* if we couldn't handle the request, just bail with the UnknownMethod error */
6697   if (!handled)
6698     {
6699       GDBusMessage *reply;
6700       reply = g_dbus_message_new_method_error (data->message,
6701                                                "org.freedesktop.DBus.Error.UnknownMethod",
6702                                                _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6703                                                g_dbus_message_get_member (data->message),
6704                                                g_dbus_message_get_interface (data->message),
6705                                                g_dbus_message_get_signature (data->message));
6706       g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6707       g_object_unref (reply);
6708     }
6709
6710   return FALSE;
6711 }
6712
6713 /* called in GDBusWorker thread with connection's lock held */
6714 static gboolean
6715 subtree_message_func (GDBusConnection *connection,
6716                       ExportedSubtree *es,
6717                       GDBusMessage    *message)
6718 {
6719   GSource *idle_source;
6720   SubtreeDeferredData *data;
6721
6722   data = g_new0 (SubtreeDeferredData, 1);
6723   data->message = g_object_ref (message);
6724   data->es = es;
6725
6726   /* defer this call to an idle handler in the right thread */
6727   idle_source = g_idle_source_new ();
6728   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6729   g_source_set_callback (idle_source,
6730                          process_subtree_vtable_message_in_idle_cb,
6731                          data,
6732                          (GDestroyNotify) subtree_deferred_data_free);
6733   g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6734   g_source_attach (idle_source, es->context);
6735   g_source_unref (idle_source);
6736
6737   /* since we own the entire subtree, handlers for objects not in the subtree have been
6738    * tried already by libdbus-1 - so we just need to ensure that we're always going
6739    * to reply to the message
6740    */
6741   return TRUE;
6742 }
6743
6744 /**
6745  * g_dbus_connection_register_subtree:
6746  * @connection: a #GDBusConnection
6747  * @object_path: the object path to register the subtree at
6748  * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6749  *     dispatch nodes in the subtree
6750  * @flags: flags used to fine tune the behavior of the subtree
6751  * @user_data: data to pass to functions in @vtable
6752  * @user_data_free_func: function to call when the subtree is unregistered
6753  * @error: return location for error or %NULL
6754  *
6755  * Registers a whole subtree of dynamic objects.
6756  *
6757  * The @enumerate and @introspection functions in @vtable are used to
6758  * convey, to remote callers, what nodes exist in the subtree rooted
6759  * by @object_path.
6760  *
6761  * When handling remote calls into any node in the subtree, first the
6762  * @enumerate function is used to check if the node exists. If the node exists
6763  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6764  * the @introspection function is used to check if the node supports the
6765  * requested method. If so, the @dispatch function is used to determine
6766  * where to dispatch the call. The collected #GDBusInterfaceVTable and
6767  * #gpointer will be used to call into the interface vtable for processing
6768  * the request.
6769  *
6770  * All calls into user-provided code will be invoked in the
6771  * [thread-default main context][g-main-context-push-thread-default]
6772  * of the thread you are calling this method from.
6773  *
6774  * If an existing subtree is already registered at @object_path or
6775  * then @error is set to #G_IO_ERROR_EXISTS.
6776  *
6777  * Note that it is valid to register regular objects (using
6778  * g_dbus_connection_register_object()) in a subtree registered with
6779  * g_dbus_connection_register_subtree() - if so, the subtree handler
6780  * is tried as the last resort. One way to think about a subtree
6781  * handler is to consider it a fallback handler for object paths not
6782  * registered via g_dbus_connection_register_object() or other bindings.
6783  *
6784  * Note that @vtable will be copied so you cannot change it after
6785  * registration.
6786  *
6787  * See this [server][gdbus-subtree-server] for an example of how to use
6788  * this method.
6789  *
6790  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6791  * that can be used with g_dbus_connection_unregister_subtree() .
6792  *
6793  * Since: 2.26
6794  */
6795 guint
6796 g_dbus_connection_register_subtree (GDBusConnection           *connection,
6797                                     const gchar               *object_path,
6798                                     const GDBusSubtreeVTable  *vtable,
6799                                     GDBusSubtreeFlags          flags,
6800                                     gpointer                   user_data,
6801                                     GDestroyNotify             user_data_free_func,
6802                                     GError                   **error)
6803 {
6804   guint ret;
6805   ExportedSubtree *es;
6806
6807   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6808   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6809   g_return_val_if_fail (vtable != NULL, 0);
6810   g_return_val_if_fail (error == NULL || *error == NULL, 0);
6811   g_return_val_if_fail (check_initialized (connection), 0);
6812
6813   ret = 0;
6814
6815   CONNECTION_LOCK (connection);
6816
6817   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6818   if (es != NULL)
6819     {
6820       g_set_error (error,
6821                    G_IO_ERROR,
6822                    G_IO_ERROR_EXISTS,
6823                    _("A subtree is already exported for %s"),
6824                    object_path);
6825       goto out;
6826     }
6827
6828   es = g_new0 (ExportedSubtree, 1);
6829   es->object_path = g_strdup (object_path);
6830   es->connection = connection;
6831
6832   es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6833   es->flags = flags;
6834   es->id = g_atomic_int_add (&_global_subtree_registration_id, 1); /* TODO: overflow etc. */
6835   es->user_data = user_data;
6836   es->user_data_free_func = user_data_free_func;
6837   es->context = g_main_context_ref_thread_default ();
6838
6839   g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6840   g_hash_table_insert (connection->map_id_to_es,
6841                        GUINT_TO_POINTER (es->id),
6842                        es);
6843
6844   ret = es->id;
6845
6846  out:
6847   CONNECTION_UNLOCK (connection);
6848
6849   return ret;
6850 }
6851
6852 /* ---------------------------------------------------------------------------------------------------- */
6853
6854 /**
6855  * g_dbus_connection_unregister_subtree:
6856  * @connection: a #GDBusConnection
6857  * @registration_id: a subtree registration id obtained from
6858  *     g_dbus_connection_register_subtree()
6859  *
6860  * Unregisters a subtree.
6861  *
6862  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6863  *
6864  * Since: 2.26
6865  */
6866 gboolean
6867 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6868                                       guint            registration_id)
6869 {
6870   ExportedSubtree *es;
6871   gboolean ret;
6872
6873   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6874   g_return_val_if_fail (check_initialized (connection), FALSE);
6875
6876   ret = FALSE;
6877
6878   CONNECTION_LOCK (connection);
6879
6880   es = g_hash_table_lookup (connection->map_id_to_es,
6881                             GUINT_TO_POINTER (registration_id));
6882   if (es == NULL)
6883     goto out;
6884
6885   g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6886   g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6887
6888   ret = TRUE;
6889
6890  out:
6891   CONNECTION_UNLOCK (connection);
6892
6893   return ret;
6894 }
6895
6896 /* ---------------------------------------------------------------------------------------------------- */
6897
6898 /* may be called in any thread, with connection's lock held */
6899 static void
6900 handle_generic_ping_unlocked (GDBusConnection *connection,
6901                               const gchar     *object_path,
6902                               GDBusMessage    *message)
6903 {
6904   GDBusMessage *reply;
6905   reply = g_dbus_message_new_method_reply (message);
6906   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6907   g_object_unref (reply);
6908 }
6909
6910 /* may be called in any thread, with connection's lock held */
6911 static void
6912 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6913                                         const gchar     *object_path,
6914                                         GDBusMessage    *message)
6915 {
6916   GDBusMessage *reply;
6917
6918   reply = NULL;
6919   if (connection->machine_id == NULL)
6920     {
6921       GError *error;
6922
6923       error = NULL;
6924       connection->machine_id = _g_dbus_get_machine_id (&error);
6925       if (connection->machine_id == NULL)
6926         {
6927           reply = g_dbus_message_new_method_error_literal (message,
6928                                                            "org.freedesktop.DBus.Error.Failed",
6929                                                            error->message);
6930           g_error_free (error);
6931         }
6932     }
6933
6934   if (reply == NULL)
6935     {
6936       reply = g_dbus_message_new_method_reply (message);
6937       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6938     }
6939   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6940   g_object_unref (reply);
6941 }
6942
6943 /* may be called in any thread, with connection's lock held */
6944 static void
6945 handle_generic_introspect_unlocked (GDBusConnection *connection,
6946                                     const gchar     *object_path,
6947                                     GDBusMessage    *message)
6948 {
6949   guint n;
6950   GString *s;
6951   gchar **registered;
6952   GDBusMessage *reply;
6953
6954   /* first the header */
6955   s = g_string_new (NULL);
6956   introspect_append_header (s);
6957
6958   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6959   for (n = 0; registered != NULL && registered[n] != NULL; n++)
6960       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
6961   g_strfreev (registered);
6962   g_string_append (s, "</node>\n");
6963
6964   reply = g_dbus_message_new_method_reply (message);
6965   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6966   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6967   g_object_unref (reply);
6968   g_string_free (s, TRUE);
6969 }
6970
6971 /* may be called in any thread, with connection's lock held */
6972 static gboolean
6973 handle_generic_unlocked (GDBusConnection *connection,
6974                          GDBusMessage    *message)
6975 {
6976   gboolean handled;
6977   const gchar *interface_name;
6978   const gchar *member;
6979   const gchar *signature;
6980   const gchar *path;
6981
6982   CONNECTION_ENSURE_LOCK (connection);
6983
6984   handled = FALSE;
6985
6986   interface_name = g_dbus_message_get_interface (message);
6987   member = g_dbus_message_get_member (message);
6988   signature = g_dbus_message_get_signature (message);
6989   path = g_dbus_message_get_path (message);
6990
6991   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6992       g_strcmp0 (member, "Introspect") == 0 &&
6993       g_strcmp0 (signature, "") == 0)
6994     {
6995       handle_generic_introspect_unlocked (connection, path, message);
6996       handled = TRUE;
6997     }
6998   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6999            g_strcmp0 (member, "Ping") == 0 &&
7000            g_strcmp0 (signature, "") == 0)
7001     {
7002       handle_generic_ping_unlocked (connection, path, message);
7003       handled = TRUE;
7004     }
7005   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7006            g_strcmp0 (member, "GetMachineId") == 0 &&
7007            g_strcmp0 (signature, "") == 0)
7008     {
7009       handle_generic_get_machine_id_unlocked (connection, path, message);
7010       handled = TRUE;
7011     }
7012
7013   return handled;
7014 }
7015
7016 /* ---------------------------------------------------------------------------------------------------- */
7017
7018 /* called in GDBusWorker thread with connection's lock held */
7019 static void
7020 distribute_method_call (GDBusConnection *connection,
7021                         GDBusMessage    *message)
7022 {
7023   GDBusMessage *reply;
7024   ExportedObject *eo;
7025   ExportedSubtree *es;
7026   const gchar *object_path;
7027   const gchar *interface_name;
7028   const gchar *member;
7029   const gchar *path;
7030   gchar *subtree_path;
7031   gchar *needle;
7032
7033   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7034
7035   interface_name = g_dbus_message_get_interface (message);
7036   member = g_dbus_message_get_member (message);
7037   path = g_dbus_message_get_path (message);
7038   subtree_path = g_strdup (path);
7039   needle = strrchr (subtree_path, '/');
7040   if (needle != NULL && needle != subtree_path)
7041     {
7042       *needle = '\0';
7043     }
7044   else
7045     {
7046       g_free (subtree_path);
7047       subtree_path = NULL;
7048     }
7049
7050
7051   if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7052     {
7053       _g_dbus_debug_print_lock ();
7054       g_print ("========================================================================\n"
7055                "GDBus-debug:Incoming:\n"
7056                " <<<< METHOD INVOCATION %s.%s()\n"
7057                "      on object %s\n"
7058                "      invoked by name %s\n"
7059                "      serial %d\n",
7060                interface_name, member,
7061                path,
7062                g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7063                g_dbus_message_get_serial (message));
7064       _g_dbus_debug_print_unlock ();
7065     }
7066
7067   object_path = g_dbus_message_get_path (message);
7068   g_assert (object_path != NULL);
7069
7070   eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7071   if (eo != NULL)
7072     {
7073       if (obj_message_func (connection, eo, message))
7074         goto out;
7075     }
7076
7077   es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7078   if (es != NULL)
7079     {
7080       if (subtree_message_func (connection, es, message))
7081         goto out;
7082     }
7083
7084   if (subtree_path != NULL)
7085     {
7086       es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7087       if (es != NULL)
7088         {
7089           if (subtree_message_func (connection, es, message))
7090             goto out;
7091         }
7092     }
7093
7094   if (handle_generic_unlocked (connection, message))
7095     goto out;
7096
7097   /* if we end up here, the message has not been not handled - so return an error saying this */
7098   reply = g_dbus_message_new_method_error (message,
7099                                            "org.freedesktop.DBus.Error.UnknownMethod",
7100                                            _("No such interface '%s' on object at path %s"),
7101                                            interface_name,
7102                                            object_path);
7103   g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7104   g_object_unref (reply);
7105
7106  out:
7107   g_free (subtree_path);
7108 }
7109
7110 /* ---------------------------------------------------------------------------------------------------- */
7111
7112 /* Called in any user thread, with the message_bus_lock held. */
7113 static GWeakRef *
7114 message_bus_get_singleton (GBusType   bus_type,
7115                            GError   **error)
7116 {
7117   GWeakRef *ret;
7118   const gchar *starter_bus;
7119
7120   ret = NULL;
7121
7122   switch (bus_type)
7123     {
7124     case G_BUS_TYPE_SESSION:
7125       ret = &the_session_bus;
7126       break;
7127
7128     case G_BUS_TYPE_SYSTEM:
7129       ret = &the_system_bus;
7130       break;
7131
7132     case G_BUS_TYPE_STARTER:
7133       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7134       if (g_strcmp0 (starter_bus, "session") == 0)
7135         {
7136           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7137           goto out;
7138         }
7139       else if (g_strcmp0 (starter_bus, "system") == 0)
7140         {
7141           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7142           goto out;
7143         }
7144       else
7145         {
7146           if (starter_bus != NULL)
7147             {
7148               g_set_error (error,
7149                            G_IO_ERROR,
7150                            G_IO_ERROR_INVALID_ARGUMENT,
7151                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7152                              " - unknown value '%s'"),
7153                            starter_bus);
7154             }
7155           else
7156             {
7157               g_set_error_literal (error,
7158                                    G_IO_ERROR,
7159                                    G_IO_ERROR_INVALID_ARGUMENT,
7160                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7161                                      "variable is not set"));
7162             }
7163         }
7164       break;
7165
7166     default:
7167       g_assert_not_reached ();
7168       break;
7169     }
7170
7171  out:
7172   return ret;
7173 }
7174
7175 /* Called in any user thread, without holding locks. */
7176 static GDBusConnection *
7177 get_uninitialized_connection (GBusType       bus_type,
7178                               GCancellable  *cancellable,
7179                               GError       **error)
7180 {
7181   GWeakRef *singleton;
7182   GDBusConnection *ret;
7183
7184   ret = NULL;
7185
7186   G_LOCK (message_bus_lock);
7187   singleton = message_bus_get_singleton (bus_type, error);
7188   if (singleton == NULL)
7189     goto out;
7190
7191   ret = g_weak_ref_get (singleton);
7192
7193   if (ret == NULL)
7194     {
7195       gchar *address;
7196       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7197       if (address == NULL)
7198         goto out;
7199       ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7200                           "address", address,
7201                           "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7202                                    G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7203                           "exit-on-close", TRUE,
7204                           NULL);
7205
7206       g_weak_ref_set (singleton, ret);
7207       g_free (address);
7208     }
7209
7210   g_assert (ret != NULL);
7211
7212  out:
7213   G_UNLOCK (message_bus_lock);
7214   return ret;
7215 }
7216
7217 /* May be called from any thread. Must not hold message_bus_lock. */
7218 GDBusConnection *
7219 _g_bus_get_singleton_if_exists (GBusType bus_type)
7220 {
7221   GWeakRef *singleton;
7222   GDBusConnection *ret = NULL;
7223
7224   G_LOCK (message_bus_lock);
7225   singleton = message_bus_get_singleton (bus_type, NULL);
7226   if (singleton == NULL)
7227     goto out;
7228
7229   ret = g_weak_ref_get (singleton);
7230
7231  out:
7232   G_UNLOCK (message_bus_lock);
7233   return ret;
7234 }
7235
7236 /* May be called from any thread. Must not hold message_bus_lock. */
7237 void
7238 _g_bus_forget_singleton (GBusType bus_type)
7239 {
7240   GWeakRef *singleton;
7241
7242   G_LOCK (message_bus_lock);
7243
7244   singleton = message_bus_get_singleton (bus_type, NULL);
7245
7246   if (singleton != NULL)
7247     g_weak_ref_set (singleton, NULL);
7248
7249   G_UNLOCK (message_bus_lock);
7250 }
7251
7252 /**
7253  * g_bus_get_sync:
7254  * @bus_type: a #GBusType
7255  * @cancellable: (nullable): a #GCancellable or %NULL
7256  * @error: return location for error or %NULL
7257  *
7258  * Synchronously connects to the message bus specified by @bus_type.
7259  * Note that the returned object may shared with other callers,
7260  * e.g. if two separate parts of a process calls this function with
7261  * the same @bus_type, they will share the same object.
7262  *
7263  * This is a synchronous failable function. See g_bus_get() and
7264  * g_bus_get_finish() for the asynchronous version.
7265  *
7266  * The returned object is a singleton, that is, shared with other
7267  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7268  * event that you need a private message bus connection, use
7269  * g_dbus_address_get_for_bus_sync() and
7270  * g_dbus_connection_new_for_address().
7271  *
7272  * Note that the returned #GDBusConnection object will (usually) have
7273  * the #GDBusConnection:exit-on-close property set to %TRUE.
7274  *
7275  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7276  *     Free with g_object_unref().
7277  *
7278  * Since: 2.26
7279  */
7280 GDBusConnection *
7281 g_bus_get_sync (GBusType       bus_type,
7282                 GCancellable  *cancellable,
7283                 GError       **error)
7284 {
7285   GDBusConnection *connection;
7286
7287   _g_dbus_initialize ();
7288
7289   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7290
7291   connection = get_uninitialized_connection (bus_type, cancellable, error);
7292   if (connection == NULL)
7293     goto out;
7294
7295   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7296     {
7297       g_object_unref (connection);
7298       connection = NULL;
7299     }
7300
7301  out:
7302   return connection;
7303 }
7304
7305 static void
7306 bus_get_async_initable_cb (GObject      *source_object,
7307                            GAsyncResult *res,
7308                            gpointer      user_data)
7309 {
7310   GTask *task = user_data;
7311   GError *error = NULL;
7312
7313   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7314                                      res,
7315                                      &error))
7316     {
7317       g_assert (error != NULL);
7318       g_task_return_error (task, error);
7319       g_object_unref (source_object);
7320     }
7321   else
7322     {
7323       g_task_return_pointer (task, source_object, g_object_unref);
7324     }
7325   g_object_unref (task);
7326 }
7327
7328 /**
7329  * g_bus_get:
7330  * @bus_type: a #GBusType
7331  * @cancellable: (nullable): a #GCancellable or %NULL
7332  * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7333  * @user_data: the data to pass to @callback
7334  *
7335  * Asynchronously connects to the message bus specified by @bus_type.
7336  *
7337  * When the operation is finished, @callback will be invoked. You can
7338  * then call g_bus_get_finish() to get the result of the operation.
7339  *
7340  * This is a asynchronous failable function. See g_bus_get_sync() for
7341  * the synchronous version.
7342  *
7343  * Since: 2.26
7344  */
7345 void
7346 g_bus_get (GBusType             bus_type,
7347            GCancellable        *cancellable,
7348            GAsyncReadyCallback  callback,
7349            gpointer             user_data)
7350 {
7351   GDBusConnection *connection;
7352   GTask *task;
7353   GError *error = NULL;
7354
7355   _g_dbus_initialize ();
7356
7357   task = g_task_new (NULL, cancellable, callback, user_data);
7358   g_task_set_source_tag (task, g_bus_get);
7359
7360   connection = get_uninitialized_connection (bus_type, cancellable, &error);
7361   if (connection == NULL)
7362     {
7363       g_assert (error != NULL);
7364       g_task_return_error (task, error);
7365       g_object_unref (task);
7366     }
7367   else
7368     {
7369       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7370                                    G_PRIORITY_DEFAULT,
7371                                    cancellable,
7372                                    bus_get_async_initable_cb,
7373                                    task);
7374     }
7375 }
7376
7377 /**
7378  * g_bus_get_finish:
7379  * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7380  *     to g_bus_get()
7381  * @error: return location for error or %NULL
7382  *
7383  * Finishes an operation started with g_bus_get().
7384  *
7385  * The returned object is a singleton, that is, shared with other
7386  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7387  * event that you need a private message bus connection, use
7388  * g_dbus_address_get_for_bus_sync() and
7389  * g_dbus_connection_new_for_address().
7390  *
7391  * Note that the returned #GDBusConnection object will (usually) have
7392  * the #GDBusConnection:exit-on-close property set to %TRUE.
7393  *
7394  * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7395  *     Free with g_object_unref().
7396  *
7397  * Since: 2.26
7398  */
7399 GDBusConnection *
7400 g_bus_get_finish (GAsyncResult  *res,
7401                   GError       **error)
7402 {
7403   g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7404   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7405
7406   return g_task_propagate_pointer (G_TASK (res), error);
7407 }
7408
7409 /* ---------------------------------------------------------------------------------------------------- */