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