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