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