Use stack-allocated GVariantBuilders
[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  * - Validate all data (e.g. UTF-8) and check all the required D-Bus headers
27  *   are present and forbidden ones aren't
28  *   - When writing: g_dbus_message_to_blob()
29  *   - When reading: g_dbus_message_new_from_blob()
30  *
31  * - would be nice to expose GDBusAuthMechanism and an extension point
32  *
33  * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
34  *   the mechanism VFuncs need to be able to set an error.
35  *
36  * - Need to document other mechanisms/sources for determining the D-Bus
37  *   address of a well-known bus.
38  *
39  *   - e.g. on Win32 we need code like from here
40  *
41  *     http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
42  *
43  *     that was never copied over here because it originally was copy-paste
44  *     from the GPLv2 / AFL 2.1 libdbus sources.
45  *
46  *   - on OS X we need to look in launchd for the address
47  *
48  *     https://bugs.freedesktop.org/show_bug.cgi?id=14259
49  *
50  *   - on X11 we need to look in a X11 property on the X server
51  *     - (we can also just use dbus-launch(1) from the D-Bus
52  *        distribution)
53  *
54  *   - (ideally) this requires D-Bus spec work because none of
55  *     this has never really been specced out properly (excect
56  *     the X11 bits)
57  *
58  * - Related to the above, we also need to be able to launch a message bus
59  *   instance.... Since we don't want to write our own bus daemon we should
60  *   launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
61  *
62  * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
63  *   to specify where the nonce is stored. This will allow people to use
64  *   G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
65  *   to easily acheive secure RPC via nonce-tcp.
66  *
67  * - need to expose an extension point for resolving D-Bus address and
68  *   turning them into GIOStream objects. This will allow us to implement
69  *   e.g. X11 D-Bus transports without dlopen()'ing or linking against
70  *   libX11 from libgio.
71  *   - see g_dbus_address_connect() in gdbusaddress.c
72  *
73  * - would be cute to use kernel-specific APIs to resolve fds for
74  *   debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
75  *
76  *     fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
77  *
78  *   maybe we can show more information about what fd 21 really is.
79  *   Ryan suggests looking in /proc/self/fd for clues / symlinks!
80  *   Initial experiments on Linux 2.6 suggests that the symlink looks
81  *   like this:
82  *
83  *    3 -> /proc/18068/fd
84  *
85  *   e.g. not of much use.
86  *
87  *  - GDBus High-Level docs
88  *    - Proxy: properties, signals...
89  *    - Connection: IOStream based, ::close, connection setup steps
90  *                  mainloop integration, threading
91  *    - Differences from libdbus (extend "Migrating from")
92  *      - the message handling thread
93  *      - Using GVariant instead of GValue
94  *    - Explain why the high-level API is a good thing and what
95  *      kind of pitfalls it avoids
96  *      - Export objects before claiming names
97  *    - Talk about auto-starting services (cf. GBusNameWatcherFlags)
98  */
99
100 #include "config.h"
101
102 #include <stdlib.h>
103 #include <string.h>
104 #include <sys/types.h>
105 #ifdef HAVE_UNISTD_H
106 #include <unistd.h>
107 #endif
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 "gio-marshal.h"
121 #include "ginitable.h"
122 #include "gasyncinitable.h"
123 #include "giostream.h"
124 #include "gasyncresult.h"
125 #include "gsimpleasyncresult.h"
126
127 #ifdef G_OS_UNIX
128 #include "gunixconnection.h"
129 #include "gunixfdmessage.h"
130 #endif
131
132 #include "glibintl.h"
133 #include "gioalias.h"
134
135 /**
136  * SECTION:gdbusconnection
137  * @short_description: D-Bus Connections
138  * @include: gio/gio.h
139  *
140  * The #GDBusConnection type is used for D-Bus connections to remote
141  * peers such as a message buses. It is a low-level API that offers a
142  * lot of flexibility. For instance, it lets you establish a connection
143  * over any transport that can by represented as an #GIOStream.
144  *
145  * This class is rarely used directly in D-Bus clients. If you are writing
146  * an D-Bus client, it is often easier to use the g_bus_own_name(),
147  * g_bus_watch_name() or g_bus_watch_proxy() APIs.
148  *
149  * <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>
150  *
151  * <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>
152  *
153  * <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>
154  *
155  * <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>
156  */
157
158 /* ---------------------------------------------------------------------------------------------------- */
159
160 G_LOCK_DEFINE_STATIC (message_bus_lock);
161
162 static GDBusConnection *the_session_bus = NULL;
163 static GDBusConnection *the_system_bus = NULL;
164
165 /* ---------------------------------------------------------------------------------------------------- */
166
167 static gboolean
168 _g_strv_has_string (const gchar* const *haystack,
169                     const gchar        *needle)
170 {
171   guint n;
172
173   for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
174     {
175       if (g_strcmp0 (haystack[n], needle) == 0)
176         return TRUE;
177     }
178   return FALSE;
179 }
180
181 /* ---------------------------------------------------------------------------------------------------- */
182
183 #ifdef G_OS_WIN32
184 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
185 #else
186 // TODO: for some reason this doesn't work on Windows
187 #define CONNECTION_ENSURE_LOCK(obj) do {                                \
188     if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock)))                \
189       {                                                                 \
190         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
191                              "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
192       }                                                                 \
193   } while (FALSE)
194 #endif
195
196 #define CONNECTION_LOCK(obj) do {                                       \
197     g_mutex_lock ((obj)->priv->lock);                                   \
198   } while (FALSE)
199
200 #define CONNECTION_UNLOCK(obj) do {                                     \
201     g_mutex_unlock ((obj)->priv->lock);                                 \
202   } while (FALSE)
203
204 struct _GDBusConnectionPrivate
205 {
206   /* ------------------------------------------------------------------------ */
207   /* -- General object state ------------------------------------------------ */
208   /* ------------------------------------------------------------------------ */
209
210   /* object-wide lock */
211   GMutex *lock;
212
213   /* A lock used in the init() method of the GInitable interface - see comments
214    * in initable_init() for why a separate lock is needed
215    */
216   GMutex *init_lock;
217
218   /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
219    * someone calls org.freedesktop.DBus.GetMachineId()
220    */
221   gchar *machine_id;
222
223   /* The underlying stream used for communication */
224   GIOStream *stream;
225
226   /* The object used for authentication (if any) */
227   GDBusAuth *auth;
228
229   /* Set to TRUE if the connection has been closed */
230   gboolean closed;
231
232   /* Last serial used */
233   guint32 last_serial;
234
235   /* The object used to send/receive message */
236   GDBusWorker *worker;
237
238   /* If connected to a message bus, this contains the unique name assigned to
239    * us by the bus (e.g. ":1.42")
240    */
241   gchar *bus_unique_name;
242
243   /* The GUID returned by the other side if we authenticed as a client or
244    * the GUID to use if authenticating as a server
245    */
246   gchar *guid;
247
248   /* set to TRUE exactly when initable_init() has finished running */
249   gboolean is_initialized;
250
251   /* If the connection could not be established during initable_init(), this GError will set */
252   GError *initialization_error;
253
254   /* The result of g_main_context_get_thread_default() when the object
255    * was created (the GObject _init() function) - this is used for delivery
256    * of the :closed GObject signal.
257    */
258   GMainContext *main_context_at_construction;
259
260   /* construct properties */
261   gchar *address;
262   GDBusConnectionFlags flags;
263
264   /* Map used for managing method replies */
265   GHashTable *map_method_serial_to_send_message_data;  /* guint32 -> SendMessageData* */
266
267   /* Maps used for managing signal subscription */
268   GHashTable *map_rule_to_signal_data;          /* gchar* -> SignalData */
269   GHashTable *map_id_to_signal_data;            /* guint  -> SignalData */
270   GHashTable *map_sender_to_signal_data_array;  /* gchar* -> GPtrArray* of SignalData */
271
272   /* Maps used for managing exported objects and subtrees */
273   GHashTable *map_object_path_to_eo;  /* gchar* -> ExportedObject* */
274   GHashTable *map_id_to_ei;           /* guint  -> ExportedInterface* */
275   GHashTable *map_object_path_to_es;  /* gchar* -> ExportedSubtree* */
276   GHashTable *map_id_to_es;           /* guint  -> ExportedSubtree* */
277
278   /* Structure used for message filters */
279   GPtrArray *filters;
280
281   /* Whether to exit on close */
282   gboolean exit_on_close;
283
284   /* Capabilities negotiated during authentication */
285   GDBusCapabilityFlags capabilities;
286
287   GDBusAuthObserver *authentication_observer;
288   GCredentials *crendentials;
289 };
290
291 typedef struct ExportedObject ExportedObject;
292 static void exported_object_free (ExportedObject *eo);
293
294 typedef struct ExportedSubtree ExportedSubtree;
295 static void exported_subtree_free (ExportedSubtree *es);
296
297 enum
298 {
299   CLOSED_SIGNAL,
300   LAST_SIGNAL,
301 };
302
303 enum
304 {
305   PROP_0,
306   PROP_STREAM,
307   PROP_ADDRESS,
308   PROP_FLAGS,
309   PROP_GUID,
310   PROP_UNIQUE_NAME,
311   PROP_CLOSED,
312   PROP_EXIT_ON_CLOSE,
313   PROP_CAPABILITY_FLAGS,
314   PROP_AUTHENTICATION_OBSERVER,
315 };
316
317 static void distribute_signals (GDBusConnection  *connection,
318                                 GDBusMessage     *message);
319
320 static void distribute_method_call (GDBusConnection  *connection,
321                                     GDBusMessage     *message);
322
323 static gboolean handle_generic_unlocked (GDBusConnection *connection,
324                                          GDBusMessage    *message);
325
326
327 static void purge_all_signal_subscriptions (GDBusConnection *connection);
328 static void purge_all_filters (GDBusConnection *connection);
329
330 #define _G_ENSURE_LOCK(name) do {                                       \
331     if (G_UNLIKELY (G_TRYLOCK(name)))                                   \
332       {                                                                 \
333         g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
334                              "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
335       }                                                                 \
336   } while (FALSE)                                                       \
337
338 static guint signals[LAST_SIGNAL] = { 0 };
339
340 static void initable_iface_init       (GInitableIface      *initable_iface);
341 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
342
343 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
344                          G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
345                          G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
346                          );
347
348 static void
349 g_dbus_connection_dispose (GObject *object)
350 {
351   GDBusConnection *connection = G_DBUS_CONNECTION (object);
352
353   G_LOCK (message_bus_lock);
354   //g_debug ("disposing %p", connection);
355   if (connection == the_session_bus)
356     {
357       the_session_bus = NULL;
358     }
359   else if (connection == the_system_bus)
360     {
361       the_system_bus = NULL;
362     }
363   if (connection->priv->worker != NULL)
364     {
365       _g_dbus_worker_stop (connection->priv->worker);
366       connection->priv->worker = NULL;
367     }
368   G_UNLOCK (message_bus_lock);
369
370   if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
371     G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
372 }
373
374 static void
375 g_dbus_connection_finalize (GObject *object)
376 {
377   GDBusConnection *connection = G_DBUS_CONNECTION (object);
378
379   if (connection->priv->authentication_observer != NULL)
380     g_object_unref (connection->priv->authentication_observer);
381
382   if (connection->priv->auth != NULL)
383     g_object_unref (connection->priv->auth);
384
385   //g_debug ("finalizing %p", connection);
386   if (connection->priv->stream != NULL)
387     {
388       /* We don't really care if closing the stream succeeds or not */
389       g_io_stream_close_async (connection->priv->stream,
390                                G_PRIORITY_DEFAULT,
391                                NULL,  /* GCancellable */
392                                NULL,  /* GAsyncReadyCallback */
393                                NULL); /* userdata */
394       g_object_unref (connection->priv->stream);
395       connection->priv->stream = NULL;
396     }
397
398   g_free (connection->priv->address);
399
400   g_free (connection->priv->guid);
401   g_free (connection->priv->bus_unique_name);
402
403   if (connection->priv->initialization_error != NULL)
404     g_error_free (connection->priv->initialization_error);
405
406   g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
407
408   purge_all_signal_subscriptions (connection);
409   g_hash_table_unref (connection->priv->map_rule_to_signal_data);
410   g_hash_table_unref (connection->priv->map_id_to_signal_data);
411   g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
412
413   g_hash_table_unref (connection->priv->map_id_to_ei);
414   g_hash_table_unref (connection->priv->map_object_path_to_eo);
415   g_hash_table_unref (connection->priv->map_id_to_es);
416   g_hash_table_unref (connection->priv->map_object_path_to_es);
417
418   purge_all_filters (connection);
419   g_ptr_array_unref (connection->priv->filters);
420
421   if (connection->priv->main_context_at_construction != NULL)
422     g_main_context_unref (connection->priv->main_context_at_construction);
423
424   g_free (connection->priv->machine_id);
425
426   g_mutex_free (connection->priv->init_lock);
427   g_mutex_free (connection->priv->lock);
428
429   G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
430 }
431
432 static void
433 g_dbus_connection_get_property (GObject    *object,
434                                 guint       prop_id,
435                                 GValue     *value,
436                                 GParamSpec *pspec)
437 {
438   GDBusConnection *connection = G_DBUS_CONNECTION (object);
439
440   switch (prop_id)
441     {
442     case PROP_STREAM:
443       g_value_set_object (value, g_dbus_connection_get_stream (connection));
444       break;
445
446     case PROP_GUID:
447       g_value_set_string (value, g_dbus_connection_get_guid (connection));
448       break;
449
450     case PROP_UNIQUE_NAME:
451       g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
452       break;
453
454     case PROP_CLOSED:
455       g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
456       break;
457
458     case PROP_EXIT_ON_CLOSE:
459       g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
460       break;
461
462     case PROP_CAPABILITY_FLAGS:
463       g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
464       break;
465
466     default:
467       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
468       break;
469     }
470 }
471
472 static void
473 g_dbus_connection_set_property (GObject      *object,
474                                 guint         prop_id,
475                                 const GValue *value,
476                                 GParamSpec   *pspec)
477 {
478   GDBusConnection *connection = G_DBUS_CONNECTION (object);
479
480   switch (prop_id)
481     {
482     case PROP_STREAM:
483       connection->priv->stream = g_value_dup_object (value);
484       break;
485
486     case PROP_GUID:
487       connection->priv->guid = g_value_dup_string (value);
488       break;
489
490     case PROP_ADDRESS:
491       connection->priv->address = g_value_dup_string (value);
492       break;
493
494     case PROP_FLAGS:
495       connection->priv->flags = g_value_get_flags (value);
496       break;
497
498     case PROP_EXIT_ON_CLOSE:
499       g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
500       break;
501
502     case PROP_AUTHENTICATION_OBSERVER:
503       connection->priv->authentication_observer = g_value_dup_object (value);
504       break;
505
506     default:
507       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
508       break;
509     }
510 }
511
512 static void
513 g_dbus_connection_real_closed (GDBusConnection *connection,
514                                gboolean         remote_peer_vanished,
515                                GError          *error)
516 {
517   if (remote_peer_vanished && connection->priv->exit_on_close)
518     {
519       g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
520       raise (SIGTERM);
521     }
522 }
523
524 static void
525 g_dbus_connection_class_init (GDBusConnectionClass *klass)
526 {
527   GObjectClass *gobject_class;
528
529   g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
530
531   gobject_class = G_OBJECT_CLASS (klass);
532
533   gobject_class->finalize     = g_dbus_connection_finalize;
534   gobject_class->dispose      = g_dbus_connection_dispose;
535   gobject_class->set_property = g_dbus_connection_set_property;
536   gobject_class->get_property = g_dbus_connection_get_property;
537
538   klass->closed = g_dbus_connection_real_closed;
539
540   /**
541    * GDBusConnection:stream:
542    *
543    * The underlying #GIOStream used for I/O.
544    *
545    * Since: 2.26
546    */
547   g_object_class_install_property (gobject_class,
548                                    PROP_STREAM,
549                                    g_param_spec_object ("stream",
550                                                         P_("IO Stream"),
551                                                         P_("The underlying streams used for I/O"),
552                                                         G_TYPE_IO_STREAM,
553                                                         G_PARAM_READABLE |
554                                                         G_PARAM_WRITABLE |
555                                                         G_PARAM_CONSTRUCT_ONLY |
556                                                         G_PARAM_STATIC_NAME |
557                                                         G_PARAM_STATIC_BLURB |
558                                                         G_PARAM_STATIC_NICK));
559
560   /**
561    * GDBusConnection:address:
562    *
563    * A D-Bus address specifying potential endpoints that can be used
564    * when establishing the connection.
565    *
566    * Since: 2.26
567    */
568   g_object_class_install_property (gobject_class,
569                                    PROP_ADDRESS,
570                                    g_param_spec_string ("address",
571                                                         P_("Address"),
572                                                         P_("D-Bus address specifying potential socket endpoints"),
573                                                         NULL,
574                                                         G_PARAM_WRITABLE |
575                                                         G_PARAM_CONSTRUCT_ONLY |
576                                                         G_PARAM_STATIC_NAME |
577                                                         G_PARAM_STATIC_BLURB |
578                                                         G_PARAM_STATIC_NICK));
579
580   /**
581    * GDBusConnection:flags:
582    *
583    * Flags from the #GDBusConnectionFlags enumeration.
584    *
585    * Since: 2.26
586    */
587   g_object_class_install_property (gobject_class,
588                                    PROP_FLAGS,
589                                    g_param_spec_flags ("flags",
590                                                        P_("Flags"),
591                                                        P_("Flags"),
592                                                        G_TYPE_DBUS_CONNECTION_FLAGS,
593                                                        G_DBUS_CONNECTION_FLAGS_NONE,
594                                                        G_PARAM_WRITABLE |
595                                                        G_PARAM_CONSTRUCT_ONLY |
596                                                        G_PARAM_STATIC_NAME |
597                                                        G_PARAM_STATIC_BLURB |
598                                                        G_PARAM_STATIC_NICK));
599
600   /**
601    * GDBusConnection:guid:
602    *
603    * The GUID of the peer performing the role of server when
604    * authenticating.
605    *
606    * If you are constructing a #GDBusConnection and pass
607    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
608    * #GDBusConnection:flags property then you MUST also set this
609    * property to a valid guid.
610    *
611    * If you are constructing a #GDBusConnection and pass
612    * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
613    * #GDBusConnection:flags property you will be able to read the GUID
614    * of the other peer here after the connection has been successfully
615    * initialized.
616    *
617    * Since: 2.26
618    */
619   g_object_class_install_property (gobject_class,
620                                    PROP_GUID,
621                                    g_param_spec_string ("guid",
622                                                         P_("GUID"),
623                                                         P_("GUID of the server peer"),
624                                                         NULL,
625                                                         G_PARAM_READABLE |
626                                                         G_PARAM_WRITABLE |
627                                                         G_PARAM_CONSTRUCT_ONLY |
628                                                         G_PARAM_STATIC_NAME |
629                                                         G_PARAM_STATIC_BLURB |
630                                                         G_PARAM_STATIC_NICK));
631
632   /**
633    * GDBusConnection:unique-name:
634    *
635    * The unique name as assigned by the message bus or %NULL if the
636    * connection is not open or not a message bus connection.
637    *
638    * Since: 2.26
639    */
640   g_object_class_install_property (gobject_class,
641                                    PROP_UNIQUE_NAME,
642                                    g_param_spec_string ("unique-name",
643                                                         P_("unique-name"),
644                                                         P_("Unique name of bus connection"),
645                                                         NULL,
646                                                         G_PARAM_READABLE |
647                                                         G_PARAM_STATIC_NAME |
648                                                         G_PARAM_STATIC_BLURB |
649                                                         G_PARAM_STATIC_NICK));
650
651   /**
652    * GDBusConnection:closed:
653    *
654    * A boolean specifying whether the connection has been closed.
655    *
656    * Since: 2.26
657    */
658   g_object_class_install_property (gobject_class,
659                                    PROP_CLOSED,
660                                    g_param_spec_boolean ("closed",
661                                                          P_("Closed"),
662                                                          P_("Whether the connection is closed"),
663                                                          FALSE,
664                                                          G_PARAM_READABLE |
665                                                          G_PARAM_STATIC_NAME |
666                                                          G_PARAM_STATIC_BLURB |
667                                                          G_PARAM_STATIC_NICK));
668
669   /**
670    * GDBusConnection:exit-on-close:
671    *
672    * A boolean specifying whether the process will be terminated (by
673    * calling <literal>raise(SIGTERM)</literal>) if the connection
674    * is closed by the remote peer.
675    *
676    * Since: 2.26
677    */
678   g_object_class_install_property (gobject_class,
679                                    PROP_EXIT_ON_CLOSE,
680                                    g_param_spec_boolean ("exit-on-close",
681                                                          P_("Exit on close"),
682                                                          P_("Whether the process is terminated when the connection is closed"),
683                                                          FALSE,
684                                                          G_PARAM_READABLE |
685                                                          G_PARAM_WRITABLE |
686                                                          G_PARAM_STATIC_NAME |
687                                                          G_PARAM_STATIC_BLURB |
688                                                          G_PARAM_STATIC_NICK));
689
690   /**
691    * GDBusConnection:capabilities:
692    *
693    * Flags from the #GDBusCapabilityFlags enumeration
694    * representing connection features negotiated with the other peer.
695    *
696    * Since: 2.26
697    */
698   g_object_class_install_property (gobject_class,
699                                    PROP_CAPABILITY_FLAGS,
700                                    g_param_spec_flags ("capabilities",
701                                                        P_("Capabilities"),
702                                                        P_("Capabilities"),
703                                                        G_TYPE_DBUS_CAPABILITY_FLAGS,
704                                                        G_DBUS_CAPABILITY_FLAGS_NONE,
705                                                        G_PARAM_READABLE |
706                                                        G_PARAM_STATIC_NAME |
707                                                        G_PARAM_STATIC_BLURB |
708                                                        G_PARAM_STATIC_NICK));
709
710   /**
711    * GDBusConnection:authentication-observer:
712    *
713    * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
714    *
715    * Since: 2.26
716    */
717   g_object_class_install_property (gobject_class,
718                                    PROP_AUTHENTICATION_OBSERVER,
719                                    g_param_spec_object ("authentication-observer",
720                                                         P_("Authentication Observer"),
721                                                         P_("Object used to assist in the authentication process"),
722                                                         G_TYPE_DBUS_AUTH_OBSERVER,
723                                                         G_PARAM_WRITABLE |
724                                                         G_PARAM_CONSTRUCT_ONLY |
725                                                         G_PARAM_STATIC_NAME |
726                                                         G_PARAM_STATIC_BLURB |
727                                                         G_PARAM_STATIC_NICK));
728
729   /**
730    * GDBusConnection::closed:
731    * @connection: The #GDBusConnection emitting the signal.
732    * @remote_peer_vanished: %TRUE if @connection is closed because the
733    * remote peer closed its end of the connection.
734    * @error: A #GError with more details about the event or %NULL.
735    *
736    * Emitted when the connection is closed.
737    *
738    * The cause of this event can be
739    * <itemizedlist>
740    * <listitem><para>
741    *    If g_dbus_connection_close() is called. In this case
742    *    @remote_peer_vanished is set to %FALSE and @error is %NULL.
743    * </para></listitem>
744    * <listitem><para>
745    *    If the remote peer closes the connection. In this case
746    *    @remote_peer_vanished is set to %TRUE and @error is set.
747    * </para></listitem>
748    * <listitem><para>
749    *    If the remote peer sends invalid or malformed data. In this
750    *    case @remote_peer_vanished is set to %FALSE and @error
751    *    is set.
752    * </para></listitem>
753    * </itemizedlist>
754    *
755    * Upon receiving this signal, you should give up your reference to
756    * @connection. You are guaranteed that this signal is emitted only
757    * once.
758    *
759    * Since: 2.26
760    */
761   signals[CLOSED_SIGNAL] = g_signal_new ("closed",
762                                          G_TYPE_DBUS_CONNECTION,
763                                          G_SIGNAL_RUN_LAST,
764                                          G_STRUCT_OFFSET (GDBusConnectionClass, closed),
765                                          NULL,
766                                          NULL,
767                                          _gio_marshal_VOID__BOOLEAN_BOXED,
768                                          G_TYPE_NONE,
769                                          2,
770                                          G_TYPE_BOOLEAN,
771                                          G_TYPE_ERROR);
772 }
773
774 static void
775 g_dbus_connection_init (GDBusConnection *connection)
776 {
777   connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
778
779   connection->priv->lock = g_mutex_new ();
780   connection->priv->init_lock = g_mutex_new ();
781
782   connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
783
784   connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
785                                                                 g_str_equal);
786   connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
787                                                               g_direct_equal);
788   connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
789                                                                              g_str_equal,
790                                                                              g_free,
791                                                                              NULL);
792
793   connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
794                                                                    g_str_equal,
795                                                                    NULL,
796                                                                    (GDestroyNotify) exported_object_free);
797
798   connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
799                                                      g_direct_equal);
800
801   connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
802                                                                    g_str_equal,
803                                                                    NULL,
804                                                                    (GDestroyNotify) exported_subtree_free);
805
806   connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
807                                                      g_direct_equal);
808
809   connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
810   if (connection->priv->main_context_at_construction != NULL)
811     g_main_context_ref (connection->priv->main_context_at_construction);
812
813   connection->priv->filters = g_ptr_array_new ();
814 }
815
816 /**
817  * g_dbus_connection_get_stream:
818  * @connection: a #GDBusConnection
819  *
820  * Gets the underlying stream used for IO.
821  *
822  * Returns: the stream used for IO
823  *
824  * Since: 2.26
825  */
826 GIOStream *
827 g_dbus_connection_get_stream (GDBusConnection *connection)
828 {
829   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
830   return connection->priv->stream;
831 }
832
833
834 /**
835  * g_dbus_connection_is_closed:
836  * @connection: A #GDBusConnection.
837  *
838  * Gets whether @connection is closed.
839  *
840  * Returns: %TRUE if the connection is closed, %FALSE otherwise.
841  *
842  * Since: 2.26
843  */
844 gboolean
845 g_dbus_connection_is_closed (GDBusConnection *connection)
846 {
847   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
848   return connection->priv->closed;
849 }
850
851 /**
852  * g_dbus_connection_get_capabilities:
853  * @connection: A #GDBusConnection.
854  *
855  * Gets the capabilities negotiated with the remote peer
856  *
857  * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
858  *
859  * Since: 2.26
860  */
861 GDBusCapabilityFlags
862 g_dbus_connection_get_capabilities (GDBusConnection *connection)
863 {
864   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
865   return connection->priv->capabilities;
866 }
867
868
869 /* ---------------------------------------------------------------------------------------------------- */
870
871 typedef struct
872 {
873   GDBusConnection *connection;
874   GError *error;
875   gboolean remote_peer_vanished;
876 } EmitClosedData;
877
878 static void
879 emit_closed_data_free (EmitClosedData *data)
880 {
881   g_object_unref (data->connection);
882   if (data->error != NULL)
883     g_error_free (data->error);
884   g_free (data);
885 }
886
887 static gboolean
888 emit_closed_in_idle (gpointer user_data)
889 {
890   EmitClosedData *data = user_data;
891   gboolean result;
892
893   g_object_notify (G_OBJECT (data->connection), "closed");
894   g_signal_emit (data->connection,
895                  signals[CLOSED_SIGNAL],
896                  0,
897                  data->remote_peer_vanished,
898                  data->error,
899                  &result);
900   return FALSE;
901 }
902
903 /* Can be called from any thread, must hold lock */
904 static void
905 set_closed_unlocked (GDBusConnection *connection,
906                      gboolean         remote_peer_vanished,
907                      GError          *error)
908 {
909   GSource *idle_source;
910   EmitClosedData *data;
911
912   CONNECTION_ENSURE_LOCK (connection);
913
914   g_assert (!connection->priv->closed);
915
916   connection->priv->closed = TRUE;
917
918   data = g_new0 (EmitClosedData, 1);
919   data->connection = g_object_ref (connection);
920   data->remote_peer_vanished = remote_peer_vanished;
921   data->error = error != NULL ? g_error_copy (error) : NULL;
922
923   idle_source = g_idle_source_new ();
924   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
925   g_source_set_callback (idle_source,
926                          emit_closed_in_idle,
927                          data,
928                          (GDestroyNotify) emit_closed_data_free);
929   g_source_attach (idle_source, connection->priv->main_context_at_construction);
930   g_source_unref (idle_source);
931 }
932
933 /* ---------------------------------------------------------------------------------------------------- */
934
935 /**
936  * g_dbus_connection_close:
937  * @connection: A #GDBusConnection.
938  *
939  * Closes @connection. Note that this never causes the process to
940  * exit (this might only happen if the other end of a shared message
941  * bus connection disconnects).
942  *
943  * If @connection is already closed, this method does nothing.
944  *
945  * Since: 2.26
946  */
947 void
948 g_dbus_connection_close (GDBusConnection *connection)
949 {
950   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
951
952   CONNECTION_LOCK (connection);
953   if (!connection->priv->closed)
954     {
955       GError *error = NULL;
956
957       /* TODO: do this async */
958       //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
959       if (!g_io_stream_close (connection->priv->stream, NULL, &error))
960         {
961           g_warning ("Error closing stream: %s", error->message);
962           g_error_free (error);
963         }
964
965       set_closed_unlocked (connection, FALSE, NULL);
966     }
967   CONNECTION_UNLOCK (connection);
968 }
969
970 /* ---------------------------------------------------------------------------------------------------- */
971
972 static gboolean
973 g_dbus_connection_send_message_unlocked (GDBusConnection   *connection,
974                                          GDBusMessage      *message,
975                                          volatile guint32  *out_serial,
976                                          GError           **error)
977 {
978   guchar *blob;
979   gsize blob_size;
980   guint32 serial_to_use;
981   gboolean ret;
982
983   CONNECTION_ENSURE_LOCK (connection);
984
985   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
986   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
987
988   /* TODO: check all necessary headers are present */
989
990   ret = FALSE;
991   blob = NULL;
992
993   if (out_serial != NULL)
994     *out_serial = 0;
995
996   if (connection->priv->closed)
997     {
998       g_set_error_literal (error,
999                            G_IO_ERROR,
1000                            G_IO_ERROR_CLOSED,
1001                            _("The connection is closed"));
1002       goto out;
1003     }
1004
1005   blob = g_dbus_message_to_blob (message,
1006                                  &blob_size,
1007                                  connection->priv->capabilities,
1008                                  error);
1009   if (blob == NULL)
1010     goto out;
1011
1012   serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
1013
1014   switch (blob[0])
1015     {
1016     case 'l':
1017       ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1018       break;
1019     case 'B':
1020       ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1021       break;
1022     default:
1023       g_assert_not_reached ();
1024       break;
1025     }
1026
1027 #if 0
1028   g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1029               blob_size, serial_to_use, connection);
1030   g_printerr ("----\n");
1031   hexdump (blob, blob_size);
1032   g_printerr ("----\n");
1033 #endif
1034
1035   /* TODO: use connection->priv->auth to encode the blob */
1036
1037   if (out_serial != NULL)
1038     *out_serial = serial_to_use;
1039
1040   g_dbus_message_set_serial (message, serial_to_use);
1041
1042   _g_dbus_worker_send_message (connection->priv->worker,
1043                                message,
1044                                (gchar*) blob,
1045                                blob_size);
1046   blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1047
1048   ret = TRUE;
1049
1050  out:
1051   g_free (blob);
1052
1053   return ret;
1054 }
1055
1056 /**
1057  * g_dbus_connection_send_message:
1058  * @connection: A #GDBusConnection.
1059  * @message: A #GDBusMessage
1060  * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1061  * @error: Return location for error or %NULL.
1062  *
1063  * Asynchronously sends @message to the peer represented by @connection.
1064  *
1065  * If @out_serial is not %NULL, then the serial number assigned to
1066  * @message by @connection will be written to this location prior to
1067  * submitting the message to the underlying transport.
1068  *
1069  * If @connection is closed then the operation will fail with
1070  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1071  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1072  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1073  *
1074  * See <xref linkend="gdbus-server"/> and <xref
1075  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1076  * low-level API to send and receive UNIX file descriptors.
1077  *
1078  * Returns: %TRUE if the message was well-formed and queued for
1079  * transmission, %FALSE if @error is set.
1080  *
1081  * Since: 2.26
1082  */
1083 gboolean
1084 g_dbus_connection_send_message (GDBusConnection   *connection,
1085                                 GDBusMessage      *message,
1086                                 volatile guint32  *out_serial,
1087                                 GError           **error)
1088 {
1089   gboolean ret;
1090
1091   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1092   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1093   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1094
1095   CONNECTION_LOCK (connection);
1096   ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1097   CONNECTION_UNLOCK (connection);
1098   return ret;
1099 }
1100
1101 /* ---------------------------------------------------------------------------------------------------- */
1102
1103 typedef struct
1104 {
1105   volatile gint ref_count;
1106   GDBusConnection *connection;
1107   guint32 serial;
1108   GSimpleAsyncResult *simple;
1109
1110   GMainContext *main_context;
1111
1112   GCancellable *cancellable;
1113
1114   gulong cancellable_handler_id;
1115
1116   GSource *timeout_source;
1117
1118   gboolean delivered;
1119 } SendMessageData;
1120
1121 static SendMessageData *
1122 send_message_data_ref (SendMessageData *data)
1123 {
1124   g_atomic_int_inc (&data->ref_count);
1125   return data;
1126 }
1127
1128 static void
1129 send_message_data_unref (SendMessageData *data)
1130 {
1131   if (g_atomic_int_dec_and_test (&data->ref_count))
1132     {
1133       g_assert (data->timeout_source == NULL);
1134       g_assert (data->simple == NULL);
1135       g_assert (data->cancellable_handler_id == 0);
1136       g_object_unref (data->connection);
1137       if (data->cancellable != NULL)
1138         g_object_unref (data->cancellable);
1139       if (data->main_context != NULL)
1140         g_main_context_unref (data->main_context);
1141       g_free (data);
1142     }
1143 }
1144
1145 /* ---------------------------------------------------------------------------------------------------- */
1146
1147 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1148 static void
1149 send_message_with_reply_deliver (SendMessageData *data)
1150 {
1151   CONNECTION_ENSURE_LOCK (data->connection);
1152
1153   g_assert (!data->delivered);
1154
1155   data->delivered = TRUE;
1156
1157   g_simple_async_result_complete_in_idle (data->simple);
1158   g_object_unref (data->simple);
1159   data->simple = NULL;
1160
1161   if (data->timeout_source != NULL)
1162     {
1163       g_source_destroy (data->timeout_source);
1164       data->timeout_source = NULL;
1165     }
1166   if (data->cancellable_handler_id > 0)
1167     {
1168       g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1169       data->cancellable_handler_id = 0;
1170     }
1171
1172   g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1173                                        GUINT_TO_POINTER (data->serial)));
1174
1175   send_message_data_unref (data);
1176 }
1177
1178 /* ---------------------------------------------------------------------------------------------------- */
1179
1180 /* must hold lock */
1181 static void
1182 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1183                                           GDBusMessage    *reply)
1184 {
1185   if (data->delivered)
1186     goto out;
1187
1188   g_simple_async_result_set_op_res_gpointer (data->simple,
1189                                              g_object_ref (reply),
1190                                              g_object_unref);
1191
1192   send_message_with_reply_deliver (data);
1193
1194  out:
1195   ;
1196 }
1197
1198 /* ---------------------------------------------------------------------------------------------------- */
1199
1200 static gboolean
1201 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1202 {
1203   SendMessageData *data = user_data;
1204
1205   CONNECTION_LOCK (data->connection);
1206   if (data->delivered)
1207     goto out;
1208
1209   g_simple_async_result_set_error (data->simple,
1210                                    G_IO_ERROR,
1211                                    G_IO_ERROR_CANCELLED,
1212                                    _("Operation was cancelled"));
1213
1214   send_message_with_reply_deliver (data);
1215
1216  out:
1217   CONNECTION_UNLOCK (data->connection);
1218   return FALSE;
1219 }
1220
1221 /* Can be called from any thread with or without lock held */
1222 static void
1223 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1224                                       gpointer      user_data)
1225 {
1226   SendMessageData *data = user_data;
1227   GSource *idle_source;
1228
1229   /* postpone cancellation to idle handler since we may be called directly
1230    * via g_cancellable_connect() (e.g. holding lock)
1231    */
1232   idle_source = g_idle_source_new ();
1233   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1234   g_source_set_callback (idle_source,
1235                          send_message_with_reply_cancelled_idle_cb,
1236                          send_message_data_ref (data),
1237                          (GDestroyNotify) send_message_data_unref);
1238   g_source_attach (idle_source, data->main_context);
1239   g_source_unref (idle_source);
1240 }
1241
1242 /* ---------------------------------------------------------------------------------------------------- */
1243
1244 static gboolean
1245 send_message_with_reply_timeout_cb (gpointer user_data)
1246 {
1247   SendMessageData *data = user_data;
1248
1249   CONNECTION_LOCK (data->connection);
1250   if (data->delivered)
1251     goto out;
1252
1253   g_simple_async_result_set_error (data->simple,
1254                                    G_IO_ERROR,
1255                                    G_IO_ERROR_TIMED_OUT,
1256                                    _("Timeout was reached"));
1257
1258   send_message_with_reply_deliver (data);
1259
1260  out:
1261   CONNECTION_UNLOCK (data->connection);
1262
1263   return FALSE;
1264 }
1265
1266 /* ---------------------------------------------------------------------------------------------------- */
1267
1268 static void
1269 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection     *connection,
1270                                                     GDBusMessage        *message,
1271                                                     gint                 timeout_msec,
1272                                                     volatile guint32    *out_serial,
1273                                                     GCancellable        *cancellable,
1274                                                     GAsyncReadyCallback  callback,
1275                                                     gpointer             user_data)
1276 {
1277   GSimpleAsyncResult *simple;
1278   SendMessageData *data;
1279   GError *error;
1280   volatile guint32 serial;
1281
1282   data = NULL;
1283
1284   if (out_serial == NULL)
1285     out_serial = &serial;
1286
1287   if (timeout_msec == -1)
1288     timeout_msec = 25 * 1000;
1289
1290   simple = g_simple_async_result_new (G_OBJECT (connection),
1291                                       callback,
1292                                       user_data,
1293                                       g_dbus_connection_send_message_with_reply);
1294
1295   if (g_cancellable_is_cancelled (cancellable))
1296     {
1297       g_simple_async_result_set_error (simple,
1298                                        G_IO_ERROR,
1299                                        G_IO_ERROR_CANCELLED,
1300                                        _("Operation was cancelled"));
1301       g_simple_async_result_complete_in_idle (simple);
1302       g_object_unref (simple);
1303       goto out;
1304     }
1305
1306   if (connection->priv->closed)
1307     {
1308       g_simple_async_result_set_error (simple,
1309                                        G_IO_ERROR,
1310                                        G_IO_ERROR_CLOSED,
1311                                        _("The connection is closed"));
1312       g_simple_async_result_complete_in_idle (simple);
1313       g_object_unref (simple);
1314       goto out;
1315     }
1316
1317   error = NULL;
1318   if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1319     {
1320       g_simple_async_result_set_from_error (simple, error);
1321       g_simple_async_result_complete_in_idle (simple);
1322       g_object_unref (simple);
1323       goto out;
1324     }
1325
1326   data = g_new0 (SendMessageData, 1);
1327   data->ref_count = 1;
1328   data->connection = g_object_ref (connection);
1329   data->simple = simple;
1330   data->serial = *out_serial;
1331   data->main_context = g_main_context_get_thread_default ();
1332   if (data->main_context != NULL)
1333     g_main_context_ref (data->main_context);
1334
1335   if (cancellable != NULL)
1336     {
1337       data->cancellable = g_object_ref (cancellable);
1338       data->cancellable_handler_id = g_cancellable_connect (cancellable,
1339                                                             G_CALLBACK (send_message_with_reply_cancelled_cb),
1340                                                             send_message_data_ref (data),
1341                                                             (GDestroyNotify) send_message_data_unref);
1342       g_object_set_data_full (G_OBJECT (simple),
1343                               "cancellable",
1344                               g_object_ref (cancellable),
1345                               (GDestroyNotify) g_object_unref);
1346     }
1347
1348   data->timeout_source = g_timeout_source_new (timeout_msec);
1349   g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1350   g_source_set_callback (data->timeout_source,
1351                          send_message_with_reply_timeout_cb,
1352                          send_message_data_ref (data),
1353                          (GDestroyNotify) send_message_data_unref);
1354   g_source_attach (data->timeout_source, data->main_context);
1355   g_source_unref (data->timeout_source);
1356
1357   g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1358                        GUINT_TO_POINTER (*out_serial),
1359                        data);
1360
1361  out:
1362   ;
1363 }
1364
1365 /**
1366  * g_dbus_connection_send_message_with_reply:
1367  * @connection: A #GDBusConnection.
1368  * @message: A #GDBusMessage.
1369  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1370  * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1371  * @cancellable: A #GCancellable or %NULL.
1372  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1373  * care about the result.
1374  * @user_data: The data to pass to @callback.
1375  *
1376  * Asynchronously sends @message to the peer represented by @connection.
1377  *
1378  * If @out_serial is not %NULL, then the serial number assigned to
1379  * @message by @connection will be written to this location prior to
1380  * submitting the message to the underlying transport.
1381  *
1382  * If @connection is closed then the operation will fail with
1383  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1384  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1385  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1386  *
1387  * This is an asynchronous method. When the operation is finished, @callback will be invoked
1388  * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1389  * of the thread you are calling this method from. You can then call
1390  * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1391  * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1392  *
1393  * See <xref linkend="gdbus-server"/> and <xref
1394  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1395  * low-level API to send and receive UNIX file descriptors.
1396  *
1397  * Since: 2.26
1398  */
1399 void
1400 g_dbus_connection_send_message_with_reply (GDBusConnection     *connection,
1401                                            GDBusMessage        *message,
1402                                            gint                 timeout_msec,
1403                                            volatile guint32    *out_serial,
1404                                            GCancellable        *cancellable,
1405                                            GAsyncReadyCallback  callback,
1406                                            gpointer             user_data)
1407 {
1408   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1409   g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1410   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1411
1412   CONNECTION_LOCK (connection);
1413   g_dbus_connection_send_message_with_reply_unlocked (connection,
1414                                                       message,
1415                                                       timeout_msec,
1416                                                       out_serial,
1417                                                       cancellable,
1418                                                       callback,
1419                                                       user_data);
1420   CONNECTION_UNLOCK (connection);
1421 }
1422
1423 /**
1424  * g_dbus_connection_send_message_with_reply_finish:
1425  * @connection: a #GDBusConnection
1426  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1427  * @error: Return location for error or %NULL.
1428  *
1429  * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1430  *
1431  * Note that @error is only set if a local in-process error
1432  * occured. That is to say that the returned #GDBusMessage object may
1433  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1434  * g_dbus_message_to_gerror() to transcode this to a #GError.
1435  *
1436  * See <xref linkend="gdbus-server"/> and <xref
1437  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1438  * low-level API to send and receive UNIX file descriptors.
1439  *
1440  * Returns: A #GDBusMessage or %NULL if @error is set.
1441  *
1442  * Since: 2.26
1443  */
1444 GDBusMessage *
1445 g_dbus_connection_send_message_with_reply_finish (GDBusConnection  *connection,
1446                                                   GAsyncResult     *res,
1447                                                   GError          **error)
1448 {
1449   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1450   GDBusMessage *reply;
1451   GCancellable *cancellable;
1452
1453   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1454   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1455
1456   reply = NULL;
1457
1458   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1459
1460   if (g_simple_async_result_propagate_error (simple, error))
1461     goto out;
1462
1463   reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1464   cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1465   if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1466     {
1467       g_object_unref (reply);
1468       reply = NULL;
1469       g_set_error_literal (error,
1470                            G_IO_ERROR,
1471                            G_IO_ERROR_CANCELLED,
1472                            _("Operation was cancelled"));
1473     }
1474  out:
1475   return reply;
1476 }
1477
1478 /* ---------------------------------------------------------------------------------------------------- */
1479
1480 typedef struct
1481 {
1482   GAsyncResult *res;
1483   GMainContext *context;
1484   GMainLoop *loop;
1485 } SendMessageSyncData;
1486
1487 static void
1488 send_message_with_reply_sync_cb (GDBusConnection *connection,
1489                                  GAsyncResult    *res,
1490                                  gpointer         user_data)
1491 {
1492   SendMessageSyncData *data = user_data;
1493   data->res = g_object_ref (res);
1494   g_main_loop_quit (data->loop);
1495 }
1496
1497 /**
1498  * g_dbus_connection_send_message_with_reply_sync:
1499  * @connection: A #GDBusConnection.
1500  * @message: A #GDBusMessage.
1501  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1502  * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1503  * @cancellable: A #GCancellable or %NULL.
1504  * @error: Return location for error or %NULL.
1505  *
1506  * Synchronously sends @message to the peer represented by @connection
1507  * and blocks the calling thread until a reply is received or the
1508  * timeout is reached. See g_dbus_connection_send_message_with_reply()
1509  * for the asynchronous version of this method.
1510  *
1511  * If @out_serial is not %NULL, then the serial number assigned to
1512  * @message by @connection will be written to this location prior to
1513  * submitting the message to the underlying transport.
1514  *
1515  * If @connection is closed then the operation will fail with
1516  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1517  * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1518  * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1519  *
1520  * Note that @error is only set if a local in-process error
1521  * occured. That is to say that the returned #GDBusMessage object may
1522  * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1523  * g_dbus_message_to_gerror() to transcode this to a #GError.
1524  *
1525  * See <xref linkend="gdbus-server"/> and <xref
1526  * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1527  * low-level API to send and receive UNIX file descriptors.
1528  *
1529  * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1530  *
1531  * Since: 2.26
1532  */
1533 GDBusMessage *
1534 g_dbus_connection_send_message_with_reply_sync (GDBusConnection   *connection,
1535                                                 GDBusMessage      *message,
1536                                                 gint               timeout_msec,
1537                                                 volatile guint32  *out_serial,
1538                                                 GCancellable      *cancellable,
1539                                                 GError           **error)
1540 {
1541   SendMessageSyncData *data;
1542   GDBusMessage *reply;
1543
1544   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1545   g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1546   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1547   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1548
1549   data = g_new0 (SendMessageSyncData, 1);
1550   data->context = g_main_context_new ();
1551   data->loop = g_main_loop_new (data->context, FALSE);
1552
1553   g_main_context_push_thread_default (data->context);
1554
1555   g_dbus_connection_send_message_with_reply (connection,
1556                                              message,
1557                                              timeout_msec,
1558                                              out_serial,
1559                                              cancellable,
1560                                              (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1561                                              data);
1562   g_main_loop_run (data->loop);
1563   reply = g_dbus_connection_send_message_with_reply_finish (connection,
1564                                                             data->res,
1565                                                             error);
1566
1567   g_main_context_pop_thread_default (data->context);
1568
1569   g_main_context_unref (data->context);
1570   g_main_loop_unref (data->loop);
1571   g_object_unref (data->res);
1572   g_free (data);
1573
1574   return reply;
1575 }
1576
1577 /* ---------------------------------------------------------------------------------------------------- */
1578
1579 typedef struct
1580 {
1581   GDBusMessageFilterFunction func;
1582   gpointer user_data;
1583 } FilterCallback;
1584
1585 typedef struct
1586 {
1587   guint                       id;
1588   GDBusMessageFilterFunction  filter_function;
1589   gpointer                    user_data;
1590   GDestroyNotify              user_data_free_func;
1591 } FilterData;
1592
1593 /* Called in worker's thread - we must not block */
1594 static void
1595 on_worker_message_received (GDBusWorker  *worker,
1596                             GDBusMessage *message,
1597                             gpointer      user_data)
1598 {
1599   GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1600   FilterCallback *filters;
1601   gboolean consumed_by_filter;
1602   guint num_filters;
1603   guint n;
1604
1605   //g_debug ("in on_worker_message_received");
1606
1607   g_object_ref (connection);
1608
1609   /* First collect the set of callback functions */
1610   CONNECTION_LOCK (connection);
1611   num_filters = connection->priv->filters->len;
1612   filters = g_new0 (FilterCallback, num_filters);
1613   for (n = 0; n < num_filters; n++)
1614     {
1615       FilterData *data = connection->priv->filters->pdata[n];
1616       filters[n].func = data->filter_function;
1617       filters[n].user_data = data->user_data;
1618     }
1619   CONNECTION_UNLOCK (connection);
1620
1621   /* the call the filters in order (without holding the lock) */
1622   consumed_by_filter = FALSE;
1623   for (n = 0; n < num_filters; n++)
1624     {
1625       consumed_by_filter = filters[n].func (connection,
1626                                             message,
1627                                             filters[n].user_data);
1628       if (consumed_by_filter)
1629         break;
1630     }
1631
1632   /* Standard dispatch unless the filter ate the message */
1633   if (!consumed_by_filter)
1634     {
1635       GDBusMessageType message_type;
1636
1637       message_type = g_dbus_message_get_message_type (message);
1638       if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1639         {
1640           guint32 reply_serial;
1641           SendMessageData *send_message_data;
1642
1643           reply_serial = g_dbus_message_get_reply_serial (message);
1644           CONNECTION_LOCK (connection);
1645           send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1646                                                    GUINT_TO_POINTER (reply_serial));
1647           if (send_message_data != NULL)
1648             {
1649               //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1650               send_message_data_deliver_reply_unlocked (send_message_data, message);
1651             }
1652           else
1653             {
1654               //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1655             }
1656           CONNECTION_UNLOCK (connection);
1657         }
1658       else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1659         {
1660           CONNECTION_LOCK (connection);
1661           distribute_signals (connection, message);
1662           CONNECTION_UNLOCK (connection);
1663         }
1664       else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1665         {
1666           CONNECTION_LOCK (connection);
1667           distribute_method_call (connection, message);
1668           CONNECTION_UNLOCK (connection);
1669         }
1670     }
1671
1672   g_object_unref (connection);
1673   g_free (filters);
1674 }
1675
1676 /* Called in worker's thread - we must not block */
1677 static void
1678 on_worker_closed (GDBusWorker *worker,
1679                   gboolean     remote_peer_vanished,
1680                   GError      *error,
1681                   gpointer     user_data)
1682 {
1683   GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1684
1685   //g_debug ("in on_worker_closed: %s", error->message);
1686
1687   CONNECTION_LOCK (connection);
1688   if (!connection->priv->closed)
1689     set_closed_unlocked (connection, remote_peer_vanished, error);
1690   CONNECTION_UNLOCK (connection);
1691 }
1692
1693 /* ---------------------------------------------------------------------------------------------------- */
1694
1695 /* Determines the biggest set of capabilities we can support on this connection */
1696 static GDBusCapabilityFlags
1697 get_offered_capabilities_max (GDBusConnection *connection)
1698 {
1699       GDBusCapabilityFlags ret;
1700       ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1701 #ifdef G_OS_UNIX
1702       if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1703         ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1704 #endif
1705       return ret;
1706 }
1707
1708 static gboolean
1709 initable_init (GInitable     *initable,
1710                GCancellable  *cancellable,
1711                GError       **error)
1712 {
1713   GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1714   gboolean ret;
1715
1716   /* This method needs to be idempotent to work with the singleton
1717    * pattern. See the docs for g_initable_init(). We implement this by
1718    * locking.
1719    *
1720    * Unfortunately we can't use the main lock since the on_worker_*()
1721    * callbacks above needs the lock during initialization (for message
1722    * bus connections we do a synchronous Hello() call on the bus).
1723    */
1724   g_mutex_lock (connection->priv->init_lock);
1725
1726   ret = FALSE;
1727
1728   if (connection->priv->is_initialized)
1729     {
1730       if (connection->priv->stream != NULL)
1731         ret = TRUE;
1732       else
1733         g_assert (connection->priv->initialization_error != NULL);
1734       goto out;
1735     }
1736   g_assert (connection->priv->initialization_error == NULL);
1737
1738   /* The user can pass multiple (but mutally exclusive) construct
1739    * properties:
1740    *
1741    *  - stream (of type GIOStream)
1742    *  - address (of type gchar*)
1743    *
1744    * At the end of the day we end up with a non-NULL GIOStream
1745    * object in connection->priv->stream.
1746    */
1747   if (connection->priv->address != NULL)
1748     {
1749       g_assert (connection->priv->stream == NULL);
1750
1751       if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1752           (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1753         {
1754           g_set_error_literal (error,
1755                                G_IO_ERROR,
1756                                G_IO_ERROR_INVALID_ARGUMENT,
1757                                _("Unsupported flags encountered when constructing a client-side connection"));
1758           goto out;
1759         }
1760
1761       connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1762                                                                  NULL, /* TODO: out_guid */
1763                                                                  cancellable,
1764                                                                  &connection->priv->initialization_error);
1765       if (connection->priv->stream == NULL)
1766         goto out;
1767     }
1768   else if (connection->priv->stream != NULL)
1769     {
1770       /* nothing to do */
1771     }
1772   else
1773     {
1774       g_assert_not_reached ();
1775     }
1776
1777   /* Authenticate the connection */
1778   if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1779     {
1780       g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1781       g_assert (connection->priv->guid != NULL);
1782       connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1783       if (!_g_dbus_auth_run_server (connection->priv->auth,
1784                                     connection->priv->authentication_observer,
1785                                     connection->priv->guid,
1786                                     (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1787                                     get_offered_capabilities_max (connection),
1788                                     &connection->priv->capabilities,
1789                                     &connection->priv->crendentials,
1790                                     cancellable,
1791                                     &connection->priv->initialization_error))
1792         goto out;
1793     }
1794   else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1795     {
1796       g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1797       g_assert (connection->priv->guid == NULL);
1798       connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1799       connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1800                                                         get_offered_capabilities_max (connection),
1801                                                         &connection->priv->capabilities,
1802                                                         cancellable,
1803                                                         &connection->priv->initialization_error);
1804       if (connection->priv->guid == NULL)
1805         goto out;
1806     }
1807
1808   if (connection->priv->authentication_observer != NULL)
1809     {
1810       g_object_unref (connection->priv->authentication_observer);
1811       connection->priv->authentication_observer = NULL;
1812     }
1813
1814   //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1815
1816   //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1817
1818 #ifdef G_OS_UNIX
1819   /* Hack used until
1820    *
1821    *  https://bugzilla.gnome.org/show_bug.cgi?id=616458
1822    *
1823    * has been resolved
1824    */
1825   if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1826     {
1827       g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1828     }
1829 #endif
1830
1831   connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1832                                                  connection->priv->capabilities,
1833                                                  on_worker_message_received,
1834                                                  on_worker_closed,
1835                                                  connection);
1836
1837   /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1838   if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1839     {
1840       GVariant *hello_result;
1841
1842       hello_result = g_dbus_connection_call_sync (connection,
1843                                                   "org.freedesktop.DBus", /* name */
1844                                                   "/org/freedesktop/DBus", /* path */
1845                                                   "org.freedesktop.DBus", /* interface */
1846                                                   "Hello",
1847                                                   NULL, /* parameters */
1848                                                   G_DBUS_CALL_FLAGS_NONE,
1849                                                   -1,
1850                                                   NULL, /* TODO: cancellable */
1851                                                   &connection->priv->initialization_error);
1852       if (hello_result == NULL)
1853         goto out;
1854
1855       g_variant_get (hello_result, "(s)", &connection->priv->bus_unique_name);
1856       g_variant_unref (hello_result);
1857       //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1858     }
1859
1860   connection->priv->is_initialized = TRUE;
1861
1862   ret = TRUE;
1863  out:
1864   if (!ret)
1865     {
1866       g_assert (connection->priv->initialization_error != NULL);
1867       g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1868     }
1869
1870   g_mutex_unlock (connection->priv->init_lock);
1871
1872   return ret;
1873 }
1874
1875 static void
1876 initable_iface_init (GInitableIface *initable_iface)
1877 {
1878   initable_iface->init = initable_init;
1879 }
1880
1881 /* ---------------------------------------------------------------------------------------------------- */
1882
1883 static void
1884 async_init_thread (GSimpleAsyncResult *res,
1885                    GObject            *object,
1886                    GCancellable       *cancellable)
1887 {
1888   GError *error = NULL;
1889
1890   if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1891     {
1892       g_simple_async_result_set_from_error (res, error);
1893       g_error_free (error);
1894     }
1895 }
1896
1897 static void
1898 async_initable_init_async (GAsyncInitable      *initable,
1899                            gint                 io_priority,
1900                            GCancellable        *cancellable,
1901                            GAsyncReadyCallback  callback,
1902                            gpointer             user_data)
1903 {
1904   GSimpleAsyncResult *res;
1905
1906   g_return_if_fail (G_IS_INITABLE (initable));
1907
1908   res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1909                                    async_initable_init_async);
1910   g_simple_async_result_run_in_thread (res, async_init_thread,
1911                                        io_priority, cancellable);
1912   g_object_unref (res);
1913 }
1914
1915 static gboolean
1916 async_initable_init_finish (GAsyncInitable  *initable,
1917                             GAsyncResult    *res,
1918                             GError         **error)
1919 {
1920   return TRUE; /* Errors handled by base impl */
1921 }
1922
1923 static void
1924 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1925 {
1926   /* We basically just want to use GIO's default implementation - though that one is
1927    * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1928    */
1929   async_initable_iface->init_async = async_initable_init_async;
1930   async_initable_iface->init_finish = async_initable_init_finish;
1931 }
1932
1933 /* ---------------------------------------------------------------------------------------------------- */
1934
1935 /**
1936  * g_dbus_connection_new:
1937  * @stream: A #GIOStream.
1938  * @guid: The GUID to use if a authenticating as a server or %NULL.
1939  * @flags: Flags describing how to make the connection.
1940  * @observer: A #GDBusAuthObserver or %NULL.
1941  * @cancellable: A #GCancellable or %NULL.
1942  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1943  * @user_data: The data to pass to @callback.
1944  *
1945  * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1946  * with the end represented by @stream.
1947  *
1948  * If @observer is not %NULL it may be used to control the
1949  * authentication process.
1950  *
1951  * When the operation is finished, @callback will be invoked. You can
1952  * then call g_dbus_connection_new_finish() to get the result of the
1953  * operation.
1954  *
1955  * This is a asynchronous failable constructor. See
1956  * g_dbus_connection_new_sync() for the synchronous
1957  * version.
1958  *
1959  * Since: 2.26
1960  */
1961 void
1962 g_dbus_connection_new (GIOStream            *stream,
1963                        const gchar          *guid,
1964                        GDBusConnectionFlags  flags,
1965                        GDBusAuthObserver    *observer,
1966                        GCancellable         *cancellable,
1967                        GAsyncReadyCallback   callback,
1968                        gpointer              user_data)
1969 {
1970   g_return_if_fail (G_IS_IO_STREAM (stream));
1971   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1972                               G_PRIORITY_DEFAULT,
1973                               cancellable,
1974                               callback,
1975                               user_data,
1976                               "stream", stream,
1977                               "guid", guid,
1978                               "flags", flags,
1979                               "authentication-observer", observer,
1980                               NULL);
1981 }
1982
1983 /**
1984  * g_dbus_connection_new_finish:
1985  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1986  * @error: Return location for error or %NULL.
1987  *
1988  * Finishes an operation started with g_dbus_connection_new().
1989  *
1990  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1991  *
1992  * Since: 2.26
1993  */
1994 GDBusConnection *
1995 g_dbus_connection_new_finish (GAsyncResult  *res,
1996                               GError       **error)
1997 {
1998   GObject *object;
1999   GObject *source_object;
2000
2001   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2002   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2003
2004   source_object = g_async_result_get_source_object (res);
2005   g_assert (source_object != NULL);
2006   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2007                                         res,
2008                                         error);
2009   g_object_unref (source_object);
2010   if (object != NULL)
2011     return G_DBUS_CONNECTION (object);
2012   else
2013     return NULL;
2014 }
2015
2016 /**
2017  * g_dbus_connection_new_sync:
2018  * @stream: A #GIOStream.
2019  * @guid: The GUID to use if a authenticating as a server or %NULL.
2020  * @flags: Flags describing how to make the connection.
2021  * @observer: A #GDBusAuthObserver or %NULL.
2022  * @cancellable: A #GCancellable or %NULL.
2023  * @error: Return location for error or %NULL.
2024  *
2025  * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2026  * with the end represented by @stream.
2027  *
2028  * If @observer is not %NULL it may be used to control the
2029  * authentication process.
2030  *
2031  * This is a synchronous failable constructor. See
2032  * g_dbus_connection_new() for the asynchronous version.
2033  *
2034  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2035  *
2036  * Since: 2.26
2037  */
2038 GDBusConnection *
2039 g_dbus_connection_new_sync (GIOStream             *stream,
2040                             const gchar           *guid,
2041                             GDBusConnectionFlags   flags,
2042                             GDBusAuthObserver     *observer,
2043                             GCancellable          *cancellable,
2044                             GError               **error)
2045 {
2046   g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2047   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2048   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2049                          cancellable,
2050                          error,
2051                          "stream", stream,
2052                          "guid", guid,
2053                          "flags", flags,
2054                          "authentication-observer", observer,
2055                          NULL);
2056 }
2057
2058 /* ---------------------------------------------------------------------------------------------------- */
2059
2060 /**
2061  * g_dbus_connection_new_for_address:
2062  * @address: A D-Bus address.
2063  * @flags: Flags describing how to make the connection.
2064  * @observer: A #GDBusAuthObserver or %NULL.
2065  * @cancellable: A #GCancellable or %NULL.
2066  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2067  * @user_data: The data to pass to @callback.
2068  *
2069  * Asynchronously connects and sets up a D-Bus client connection for
2070  * exchanging D-Bus messages with an endpoint specified by @address
2071  * which must be in the D-Bus address format.
2072  *
2073  * This constructor can only be used to initiate client-side
2074  * connections - use g_dbus_connection_new() if you need to act as the
2075  * server. In particular, @flags cannot contain the
2076  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2077  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2078  *
2079  * When the operation is finished, @callback will be invoked. You can
2080  * then call g_dbus_connection_new_finish() to get the result of the
2081  * operation.
2082  *
2083  * If @observer is not %NULL it may be used to control the
2084  * authentication process.
2085  *
2086  * This is a asynchronous failable constructor. See
2087  * g_dbus_connection_new_for_address_sync() for the synchronous
2088  * version.
2089  *
2090  * Since: 2.26
2091  */
2092 void
2093 g_dbus_connection_new_for_address (const gchar          *address,
2094                                    GDBusConnectionFlags  flags,
2095                                    GDBusAuthObserver    *observer,
2096                                    GCancellable         *cancellable,
2097                                    GAsyncReadyCallback   callback,
2098                                    gpointer              user_data)
2099 {
2100   g_return_if_fail (address != NULL);
2101   g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2102                               G_PRIORITY_DEFAULT,
2103                               cancellable,
2104                               callback,
2105                               user_data,
2106                               "address", address,
2107                               "flags", flags,
2108                               "authentication-observer", observer,
2109                               NULL);
2110 }
2111
2112 /**
2113  * g_dbus_connection_new_for_address_finish:
2114  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2115  * @error: Return location for error or %NULL.
2116  *
2117  * Finishes an operation started with g_dbus_connection_new_for_address().
2118  *
2119  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2120  *
2121  * Since: 2.26
2122  */
2123 GDBusConnection *
2124 g_dbus_connection_new_for_address_finish (GAsyncResult  *res,
2125                                           GError       **error)
2126 {
2127   GObject *object;
2128   GObject *source_object;
2129
2130   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2131   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2132
2133   source_object = g_async_result_get_source_object (res);
2134   g_assert (source_object != NULL);
2135   object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2136                                         res,
2137                                         error);
2138   g_object_unref (source_object);
2139   if (object != NULL)
2140     return G_DBUS_CONNECTION (object);
2141   else
2142     return NULL;
2143 }
2144
2145 /**
2146  * g_dbus_connection_new_for_address_sync:
2147  * @address: A D-Bus address.
2148  * @flags: Flags describing how to make the connection.
2149  * @observer: A #GDBusAuthObserver or %NULL.
2150  * @cancellable: A #GCancellable or %NULL.
2151  * @error: Return location for error or %NULL.
2152  *
2153  * Synchronously connects and sets up a D-Bus client connection for
2154  * exchanging D-Bus messages with an endpoint specified by @address
2155  * which must be in the D-Bus address format.
2156  *
2157  * This constructor can only be used to initiate client-side
2158  * connections - use g_dbus_connection_new_sync() if you need to act
2159  * as the server. In particular, @flags cannot contain the
2160  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2161  * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2162  *
2163  * This is a synchronous failable constructor. See
2164  * g_dbus_connection_new_for_address() for the asynchronous version.
2165  *
2166  * If @observer is not %NULL it may be used to control the
2167  * authentication process.
2168  *
2169  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2170  *
2171  * Since: 2.26
2172  */
2173 GDBusConnection *
2174 g_dbus_connection_new_for_address_sync (const gchar           *address,
2175                                         GDBusConnectionFlags   flags,
2176                                         GDBusAuthObserver     *observer,
2177                                         GCancellable          *cancellable,
2178                                         GError               **error)
2179 {
2180   g_return_val_if_fail (address != NULL, NULL);
2181   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2182   return g_initable_new (G_TYPE_DBUS_CONNECTION,
2183                          cancellable,
2184                          error,
2185                          "address", address,
2186                          "flags", flags,
2187                          "authentication-observer", observer,
2188                          NULL);
2189 }
2190
2191 /* ---------------------------------------------------------------------------------------------------- */
2192
2193 /**
2194  * g_dbus_connection_set_exit_on_close:
2195  * @connection: A #GDBusConnection.
2196  * @exit_on_close: Whether the process should be terminated
2197  * when @connection is closed by the remote peer.
2198  *
2199  * Sets whether the process should be terminated when @connection is
2200  * closed by the remote peer. See #GDBusConnection:exit-on-close for
2201  * more details.
2202  *
2203  * Since: 2.26
2204  */
2205 void
2206 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2207                                      gboolean         exit_on_close)
2208 {
2209   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2210   connection->priv->exit_on_close = exit_on_close;
2211 }
2212
2213 /**
2214  * g_dbus_connection_get_exit_on_close:
2215  * @connection: A #GDBusConnection.
2216  *
2217  * Gets whether the process is terminated when @connection is
2218  * closed by the remote peer. See
2219  * #GDBusConnection:exit-on-close for more details.
2220  *
2221  * Returns: Whether the process is terminated when @connection is
2222  * closed by the remote peer.
2223  *
2224  * Since: 2.26
2225  */
2226 gboolean
2227 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2228 {
2229   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2230   return connection->priv->exit_on_close;
2231 }
2232
2233 /**
2234  * g_dbus_connection_get_guid:
2235  * @connection: A #GDBusConnection.
2236  *
2237  * The GUID of the peer performing the role of server when
2238  * authenticating. See #GDBusConnection:guid for more details.
2239  *
2240  * Returns: The GUID. Do not free this string, it is owned by
2241  * @connection.
2242  *
2243  * Since: 2.26
2244  */
2245 const gchar *
2246 g_dbus_connection_get_guid (GDBusConnection *connection)
2247 {
2248   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2249   return connection->priv->guid;
2250 }
2251
2252 /**
2253  * g_dbus_connection_get_unique_name:
2254  * @connection: A #GDBusConnection.
2255  *
2256  * Gets the unique name of @connection as assigned by the message
2257  * bus. This can also be used to figure out if @connection is a
2258  * message bus connection.
2259  *
2260  * Returns: The unique name or %NULL if @connection is not a message
2261  * bus connection. Do not free this string, it is owned by
2262  * @connection.
2263  *
2264  * Since: 2.26
2265  */
2266 const gchar *
2267 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2268 {
2269   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2270   return connection->priv->bus_unique_name;
2271 }
2272
2273 /**
2274  * g_dbus_connection_get_peer_credentials:
2275  * @connection: A #GDBusConnection.
2276  *
2277  * Gets the credentials of the authenticated peer. This will always
2278  * return %NULL unless @connection acted as a server
2279  * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2280  * when set up and the client passed credentials as part of the
2281  * authentication process.
2282  *
2283  * In a message bus setup, the message bus is always the server and
2284  * each application is a client. So this method will always return
2285  * %NULL for message bus clients.
2286  *
2287  * Returns: A #GCredentials or %NULL if not available. Do not free
2288  * this object, it is owned by @connection.
2289  *
2290  * Since: 2.26
2291  */
2292 GCredentials *
2293 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2294 {
2295   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2296   return connection->priv->crendentials;
2297 }
2298
2299 /* ---------------------------------------------------------------------------------------------------- */
2300
2301 static guint _global_filter_id = 1;
2302
2303 /**
2304  * g_dbus_connection_add_filter:
2305  * @connection: A #GDBusConnection.
2306  * @filter_function: A filter function.
2307  * @user_data: User data to pass to @filter_function.
2308  * @user_data_free_func: Function to free @user_data with when filter
2309  * is removed or %NULL.
2310  *
2311  * Adds a message filter. Filters are handlers that are run on all
2312  * incoming messages, prior to standard dispatch. Filters are run in
2313  * the order that they were added.  The same handler can be added as a
2314  * filter more than once, in which case it will be run more than once.
2315  * Filters added during a filter callback won't be run on the message
2316  * being processed.
2317  *
2318  * Note that filters are run in a dedicated message handling thread so
2319  * they can't block and, generally, can't do anything but signal a
2320  * worker thread. Also note that filters are rarely needed - use API
2321  * such as g_dbus_connection_send_message_with_reply(),
2322  * g_dbus_connection_signal_subscribe() or
2323  * g_dbus_connection_call() instead.
2324  *
2325  * Returns: A filter identifier that can be used with
2326  * g_dbus_connection_remove_filter().
2327  *
2328  * Since: 2.26
2329  */
2330 guint
2331 g_dbus_connection_add_filter (GDBusConnection            *connection,
2332                               GDBusMessageFilterFunction  filter_function,
2333                               gpointer                    user_data,
2334                               GDestroyNotify              user_data_free_func)
2335 {
2336   FilterData *data;
2337
2338   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2339   g_return_val_if_fail (filter_function != NULL, 0);
2340
2341   CONNECTION_LOCK (connection);
2342   data = g_new0 (FilterData, 1);
2343   data->id = _global_filter_id++; /* TODO: overflow etc. */
2344   data->filter_function = filter_function;
2345   data->user_data = user_data;
2346   data->user_data_free_func = user_data_free_func;
2347   g_ptr_array_add (connection->priv->filters, data);
2348   CONNECTION_UNLOCK (connection);
2349
2350   return data->id;
2351 }
2352
2353 /* only called from finalize(), removes all filters */
2354 static void
2355 purge_all_filters (GDBusConnection *connection)
2356 {
2357   guint n;
2358   for (n = 0; n < connection->priv->filters->len; n++)
2359     {
2360       FilterData *data = connection->priv->filters->pdata[n];
2361       if (data->user_data_free_func != NULL)
2362         data->user_data_free_func (data->user_data);
2363       g_free (data);
2364     }
2365 }
2366
2367 /**
2368  * g_dbus_connection_remove_filter:
2369  * @connection: a #GDBusConnection
2370  * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2371  *
2372  * Removes a filter.
2373  *
2374  * Since: 2.26
2375  */
2376 void
2377 g_dbus_connection_remove_filter (GDBusConnection *connection,
2378                                  guint            filter_id)
2379 {
2380   guint n;
2381   FilterData *to_destroy;
2382
2383   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2384
2385   CONNECTION_LOCK (connection);
2386   to_destroy = NULL;
2387   for (n = 0; n < connection->priv->filters->len; n++)
2388     {
2389       FilterData *data = connection->priv->filters->pdata[n];
2390       if (data->id == filter_id)
2391         {
2392           g_ptr_array_remove_index (connection->priv->filters, n);
2393           to_destroy = data;
2394           break;
2395         }
2396     }
2397   CONNECTION_UNLOCK (connection);
2398
2399   /* do free without holding lock */
2400   if (to_destroy != NULL)
2401     {
2402       if (to_destroy->user_data_free_func != NULL)
2403         to_destroy->user_data_free_func (to_destroy->user_data);
2404       g_free (to_destroy);
2405     }
2406   else
2407     {
2408       g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2409     }
2410 }
2411
2412 /* ---------------------------------------------------------------------------------------------------- */
2413
2414 typedef struct
2415 {
2416   gchar *rule;
2417   gchar *sender;
2418   gchar *interface_name;
2419   gchar *member;
2420   gchar *object_path;
2421   gchar *arg0;
2422   GArray *subscribers;
2423 } SignalData;
2424
2425 typedef struct
2426 {
2427   GDBusSignalCallback callback;
2428   gpointer user_data;
2429   GDestroyNotify user_data_free_func;
2430   guint id;
2431   GMainContext *context;
2432 } SignalSubscriber;
2433
2434 static void
2435 signal_data_free (SignalData *data)
2436 {
2437   g_free (data->rule);
2438   g_free (data->sender);
2439   g_free (data->interface_name);
2440   g_free (data->member);
2441   g_free (data->object_path);
2442   g_free (data->arg0);
2443   g_array_free (data->subscribers, TRUE);
2444   g_free (data);
2445 }
2446
2447 static gchar *
2448 args_to_rule (const gchar *sender,
2449               const gchar *interface_name,
2450               const gchar *member,
2451               const gchar *object_path,
2452               const gchar *arg0)
2453 {
2454   GString *rule;
2455
2456   rule = g_string_new ("type='signal'");
2457   if (sender != NULL)
2458     g_string_append_printf (rule, ",sender='%s'", sender);
2459   if (interface_name != NULL)
2460     g_string_append_printf (rule, ",interface='%s'", interface_name);
2461   if (member != NULL)
2462     g_string_append_printf (rule, ",member='%s'", member);
2463   if (object_path != NULL)
2464     g_string_append_printf (rule, ",path='%s'", object_path);
2465   if (arg0 != NULL)
2466     g_string_append_printf (rule, ",arg0='%s'", arg0);
2467
2468   return g_string_free (rule, FALSE);
2469 }
2470
2471 static guint _global_subscriber_id = 1;
2472 static guint _global_registration_id = 1;
2473 static guint _global_subtree_registration_id = 1;
2474
2475 /* ---------------------------------------------------------------------------------------------------- */
2476
2477 /* must hold lock when calling */
2478 static void
2479 add_match_rule (GDBusConnection *connection,
2480                 const gchar     *match_rule)
2481 {
2482   GError *error;
2483   GDBusMessage *message;
2484
2485   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2486                                             "/org/freedesktop/DBus", /* path */
2487                                             "org.freedesktop.DBus", /* interface */
2488                                             "AddMatch");
2489   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2490
2491   error = NULL;
2492   if (!g_dbus_connection_send_message_unlocked (connection,
2493                                                 message,
2494                                                 NULL,
2495                                                 &error))
2496     {
2497       g_critical ("Error while sending AddMatch() message: %s", error->message);
2498       g_error_free (error);
2499     }
2500   g_object_unref (message);
2501 }
2502
2503 /* ---------------------------------------------------------------------------------------------------- */
2504
2505 /* must hold lock when calling */
2506 static void
2507 remove_match_rule (GDBusConnection *connection,
2508                    const gchar     *match_rule)
2509 {
2510   GError *error;
2511   GDBusMessage *message;
2512
2513   message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2514                                             "/org/freedesktop/DBus", /* path */
2515                                             "org.freedesktop.DBus", /* interface */
2516                                             "RemoveMatch");
2517   g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2518
2519   error = NULL;
2520   if (!g_dbus_connection_send_message_unlocked (connection,
2521                                                 message,
2522                                                 NULL,
2523                                                 &error))
2524     {
2525       g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2526       g_error_free (error);
2527     }
2528   g_object_unref (message);
2529 }
2530
2531 /* ---------------------------------------------------------------------------------------------------- */
2532
2533 static gboolean
2534 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2535 {
2536   return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2537          g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2538          g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2539          (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2540           g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2541 }
2542
2543 /* ---------------------------------------------------------------------------------------------------- */
2544
2545 /**
2546  * g_dbus_connection_signal_subscribe:
2547  * @connection: A #GDBusConnection.
2548  * @sender: Sender name to match on. Must be either <literal>org.freedesktop.DBus</literal> (for listening to signals from the message bus daemon) or a unique name or %NULL to listen from all senders.
2549  * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2550  * @member: D-Bus signal name to match on or %NULL to match on all signals.
2551  * @object_path: Object path to match on or %NULL to match on all object paths.
2552  * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2553  * @callback: Callback to invoke when there is a signal matching the requested data.
2554  * @user_data: User data to pass to @callback.
2555  * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2556  *
2557  * Subscribes to signals on @connection and invokes @callback with a
2558  * whenever the signal is received. Note that @callback
2559  * will be invoked in the <link
2560  * linkend="g-main-context-push-thread-default">thread-default main
2561  * loop</link> of the thread you are calling this method from.
2562  *
2563  * It is considered a programming error to use this function if @connection is closed.
2564  *
2565  * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2566  * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2567  * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2568  * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2569  * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2570  * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2571  *
2572  * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2573  *
2574  * Since: 2.26
2575  */
2576 guint
2577 g_dbus_connection_signal_subscribe (GDBusConnection     *connection,
2578                                     const gchar         *sender,
2579                                     const gchar         *interface_name,
2580                                     const gchar         *member,
2581                                     const gchar         *object_path,
2582                                     const gchar         *arg0,
2583                                     GDBusSignalCallback  callback,
2584                                     gpointer             user_data,
2585                                     GDestroyNotify       user_data_free_func)
2586 {
2587   gchar *rule;
2588   SignalData *signal_data;
2589   SignalSubscriber subscriber;
2590   GPtrArray *signal_data_array;
2591
2592   /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2593    * an OOM condition. We might want to change that but that would involve making
2594    * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2595    * handle that. And there's really no sensible way of handling this short of retrying
2596    * to add the match rule... and then there's the little thing that, hey, maybe there's
2597    * a reason the bus in an OOM condition.
2598    *
2599    * Doable, but not really sure it's worth it...
2600    */
2601
2602   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2603   g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2604   g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2605                                            (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2606   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2607   g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2608   g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2609   g_return_val_if_fail (callback != NULL, 0);
2610
2611   CONNECTION_LOCK (connection);
2612
2613   rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2614
2615   if (sender == NULL)
2616     sender = "";
2617
2618   subscriber.callback = callback;
2619   subscriber.user_data = user_data;
2620   subscriber.user_data_free_func = user_data_free_func;
2621   subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2622   subscriber.context = g_main_context_get_thread_default ();
2623   if (subscriber.context != NULL)
2624     g_main_context_ref (subscriber.context);
2625
2626   /* see if we've already have this rule */
2627   signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2628   if (signal_data != NULL)
2629     {
2630       g_array_append_val (signal_data->subscribers, subscriber);
2631       g_free (rule);
2632       goto out;
2633     }
2634
2635   signal_data = g_new0 (SignalData, 1);
2636   signal_data->rule           = rule;
2637   signal_data->sender         = g_strdup (sender);
2638   signal_data->interface_name = g_strdup (interface_name);
2639   signal_data->member         = g_strdup (member);
2640   signal_data->object_path    = g_strdup (object_path);
2641   signal_data->arg0           = g_strdup (arg0);
2642   signal_data->subscribers    = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2643   g_array_append_val (signal_data->subscribers, subscriber);
2644
2645   g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2646                        signal_data->rule,
2647                        signal_data);
2648
2649   /* Add the match rule to the bus...
2650    *
2651    * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2652    * always send such messages to us.
2653    */
2654   if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2655     {
2656       if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2657         add_match_rule (connection, signal_data->rule);
2658     }
2659
2660  out:
2661   g_hash_table_insert (connection->priv->map_id_to_signal_data,
2662                        GUINT_TO_POINTER (subscriber.id),
2663                        signal_data);
2664
2665   signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2666                                            signal_data->sender);
2667   if (signal_data_array == NULL)
2668     {
2669       signal_data_array = g_ptr_array_new ();
2670       g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2671                            g_strdup (signal_data->sender),
2672                            signal_data_array);
2673     }
2674   g_ptr_array_add (signal_data_array, signal_data);
2675
2676   CONNECTION_UNLOCK (connection);
2677
2678   return subscriber.id;
2679 }
2680
2681 /* ---------------------------------------------------------------------------------------------------- */
2682
2683 /* must hold lock when calling this */
2684 static void
2685 unsubscribe_id_internal (GDBusConnection *connection,
2686                          guint            subscription_id,
2687                          GArray          *out_removed_subscribers)
2688 {
2689   SignalData *signal_data;
2690   GPtrArray *signal_data_array;
2691   guint n;
2692
2693   signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2694                                      GUINT_TO_POINTER (subscription_id));
2695   if (signal_data == NULL)
2696     {
2697       /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2698       goto out;
2699     }
2700
2701   for (n = 0; n < signal_data->subscribers->len; n++)
2702     {
2703       SignalSubscriber *subscriber;
2704
2705       subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2706       if (subscriber->id != subscription_id)
2707         continue;
2708
2709       g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2710                                            GUINT_TO_POINTER (subscription_id)));
2711       g_array_append_val (out_removed_subscribers, *subscriber);
2712       g_array_remove_index (signal_data->subscribers, n);
2713
2714       if (signal_data->subscribers->len == 0)
2715         g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2716
2717       signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2718                                                signal_data->sender);
2719       g_warn_if_fail (signal_data_array != NULL);
2720       g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2721
2722       if (signal_data_array->len == 0)
2723         {
2724           g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2725
2726           /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2727           if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2728             {
2729               if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2730                 remove_match_rule (connection, signal_data->rule);
2731             }
2732
2733           signal_data_free (signal_data);
2734         }
2735
2736       goto out;
2737     }
2738
2739   g_assert_not_reached ();
2740
2741  out:
2742   ;
2743 }
2744
2745 /**
2746  * g_dbus_connection_signal_unsubscribe:
2747  * @connection: A #GDBusConnection.
2748  * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2749  *
2750  * Unsubscribes from signals.
2751  *
2752  * Since: 2.26
2753  */
2754 void
2755 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2756                                       guint            subscription_id)
2757 {
2758   GArray *subscribers;
2759   guint n;
2760
2761   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2762
2763   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2764
2765   CONNECTION_LOCK (connection);
2766   unsubscribe_id_internal (connection,
2767                            subscription_id,
2768                            subscribers);
2769   CONNECTION_UNLOCK (connection);
2770
2771   /* invariant */
2772   g_assert (subscribers->len == 0 || subscribers->len == 1);
2773
2774   /* call GDestroyNotify without lock held */
2775   for (n = 0; n < subscribers->len; n++)
2776     {
2777       SignalSubscriber *subscriber;
2778       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2779       if (subscriber->user_data_free_func != NULL)
2780         subscriber->user_data_free_func (subscriber->user_data);
2781       if (subscriber->context != NULL)
2782         g_main_context_unref (subscriber->context);
2783     }
2784
2785   g_array_free (subscribers, TRUE);
2786 }
2787
2788 /* ---------------------------------------------------------------------------------------------------- */
2789
2790 typedef struct
2791 {
2792   guint                subscription_id;
2793   GDBusSignalCallback  callback;
2794   gpointer             user_data;
2795   GDBusMessage        *message;
2796   GDBusConnection     *connection;
2797   const gchar         *sender;
2798   const gchar         *path;
2799   const gchar         *interface;
2800   const gchar         *member;
2801 } SignalInstance;
2802
2803 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2804  * no locks held
2805  */
2806 static gboolean
2807 emit_signal_instance_in_idle_cb (gpointer data)
2808 {
2809   SignalInstance *signal_instance = data;
2810   GVariant *parameters;
2811   gboolean has_subscription;
2812
2813   parameters = g_dbus_message_get_body (signal_instance->message);
2814   if (parameters == NULL)
2815     {
2816       parameters = g_variant_new ("()");
2817       g_variant_ref_sink (parameters);
2818     }
2819   else
2820     {
2821       g_variant_ref_sink (parameters);
2822     }
2823
2824 #if 0
2825   g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2826            signal_instance->sender,
2827            signal_instance->path,
2828            signal_instance->interface,
2829            signal_instance->member,
2830            g_variant_print (parameters, TRUE));
2831 #endif
2832
2833   /* Careful here, don't do the callback if we no longer has the subscription */
2834   CONNECTION_LOCK (signal_instance->connection);
2835   has_subscription = FALSE;
2836   if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2837                            GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2838     has_subscription = TRUE;
2839   CONNECTION_UNLOCK (signal_instance->connection);
2840
2841   if (has_subscription)
2842     signal_instance->callback (signal_instance->connection,
2843                                signal_instance->sender,
2844                                signal_instance->path,
2845                                signal_instance->interface,
2846                                signal_instance->member,
2847                                parameters,
2848                                signal_instance->user_data);
2849
2850   if (parameters != NULL)
2851     g_variant_unref (parameters);
2852
2853   return FALSE;
2854 }
2855
2856 static void
2857 signal_instance_free (SignalInstance *signal_instance)
2858 {
2859   g_object_unref (signal_instance->message);
2860   g_object_unref (signal_instance->connection);
2861   g_free (signal_instance);
2862 }
2863
2864 /* called in message handler thread WITH lock held */
2865 static void
2866 schedule_callbacks (GDBusConnection *connection,
2867                     GPtrArray       *signal_data_array,
2868                     GDBusMessage    *message,
2869                     const gchar     *sender)
2870 {
2871   guint n, m;
2872   const gchar *interface;
2873   const gchar *member;
2874   const gchar *path;
2875   const gchar *arg0;
2876
2877   interface = NULL;
2878   member = NULL;
2879   path = NULL;
2880   arg0 = NULL;
2881
2882   interface = g_dbus_message_get_interface (message);
2883   member = g_dbus_message_get_member (message);
2884   path = g_dbus_message_get_path (message);
2885   arg0 = g_dbus_message_get_arg0 (message);
2886
2887 #if 0
2888   g_debug ("sender    = `%s'", sender);
2889   g_debug ("interface = `%s'", interface);
2890   g_debug ("member    = `%s'", member);
2891   g_debug ("path      = `%s'", path);
2892   g_debug ("arg0      = `%s'", arg0);
2893 #endif
2894
2895   /* TODO: if this is slow, then we can change signal_data_array into
2896    *       map_object_path_to_signal_data_array or something.
2897    */
2898   for (n = 0; n < signal_data_array->len; n++)
2899     {
2900       SignalData *signal_data = signal_data_array->pdata[n];
2901
2902       if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2903         continue;
2904
2905       if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2906         continue;
2907
2908       if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2909         continue;
2910
2911       if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2912         continue;
2913
2914       for (m = 0; m < signal_data->subscribers->len; m++)
2915         {
2916           SignalSubscriber *subscriber;
2917           GSource *idle_source;
2918           SignalInstance *signal_instance;
2919
2920           subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2921
2922           signal_instance = g_new0 (SignalInstance, 1);
2923           signal_instance->subscription_id = subscriber->id;
2924           signal_instance->callback = subscriber->callback;
2925           signal_instance->user_data = subscriber->user_data;
2926           signal_instance->message = g_object_ref (message);
2927           signal_instance->connection = g_object_ref (connection);
2928           signal_instance->sender = sender;
2929           signal_instance->path = path;
2930           signal_instance->interface = interface;
2931           signal_instance->member = member;
2932
2933           idle_source = g_idle_source_new ();
2934           g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2935           g_source_set_callback (idle_source,
2936                                  emit_signal_instance_in_idle_cb,
2937                                  signal_instance,
2938                                  (GDestroyNotify) signal_instance_free);
2939           g_source_attach (idle_source, subscriber->context);
2940           g_source_unref (idle_source);
2941         }
2942     }
2943 }
2944
2945 /* called in message handler thread with lock held */
2946 static void
2947 distribute_signals (GDBusConnection *connection,
2948                     GDBusMessage    *message)
2949 {
2950   GPtrArray *signal_data_array;
2951   const gchar *sender;
2952
2953   sender = g_dbus_message_get_sender (message);
2954
2955   /* collect subscribers that match on sender */
2956   if (sender != NULL)
2957     {
2958       signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2959       if (signal_data_array != NULL)
2960         schedule_callbacks (connection, signal_data_array, message, sender);
2961     }
2962
2963   /* collect subscribers not matching on sender */
2964   signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2965   if (signal_data_array != NULL)
2966     schedule_callbacks (connection, signal_data_array, message, sender);
2967 }
2968
2969 /* ---------------------------------------------------------------------------------------------------- */
2970
2971 /* only called from finalize(), removes all subscriptions */
2972 static void
2973 purge_all_signal_subscriptions (GDBusConnection *connection)
2974 {
2975   GHashTableIter iter;
2976   gpointer key;
2977   GArray *ids;
2978   GArray *subscribers;
2979   guint n;
2980
2981   ids = g_array_new (FALSE, FALSE, sizeof (guint));
2982   g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2983   while (g_hash_table_iter_next (&iter, &key, NULL))
2984     {
2985       guint subscription_id = GPOINTER_TO_UINT (key);
2986       g_array_append_val (ids, subscription_id);
2987     }
2988
2989   subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2990   for (n = 0; n < ids->len; n++)
2991     {
2992       guint subscription_id = g_array_index (ids, guint, n);
2993       unsubscribe_id_internal (connection,
2994                                subscription_id,
2995                                subscribers);
2996     }
2997   g_array_free (ids, TRUE);
2998
2999   /* call GDestroyNotify without lock held */
3000   for (n = 0; n < subscribers->len; n++)
3001     {
3002       SignalSubscriber *subscriber;
3003       subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3004       if (subscriber->user_data_free_func != NULL)
3005         subscriber->user_data_free_func (subscriber->user_data);
3006       if (subscriber->context != NULL)
3007         g_main_context_unref (subscriber->context);
3008     }
3009
3010   g_array_free (subscribers, TRUE);
3011 }
3012
3013 /* ---------------------------------------------------------------------------------------------------- */
3014
3015 struct ExportedObject
3016 {
3017   gchar *object_path;
3018   GDBusConnection *connection;
3019
3020   /* maps gchar* -> ExportedInterface* */
3021   GHashTable *map_if_name_to_ei;
3022 };
3023
3024 /* only called with lock held */
3025 static void
3026 exported_object_free (ExportedObject *eo)
3027 {
3028   g_free (eo->object_path);
3029   g_hash_table_unref (eo->map_if_name_to_ei);
3030   g_free (eo);
3031 }
3032
3033 typedef struct
3034 {
3035   ExportedObject *eo;
3036
3037   guint                       id;
3038   gchar                      *interface_name;
3039   const GDBusInterfaceVTable *vtable;
3040   const GDBusInterfaceInfo   *introspection_data;
3041
3042   GMainContext               *context;
3043   gpointer                    user_data;
3044   GDestroyNotify              user_data_free_func;
3045 } ExportedInterface;
3046
3047 /* called with lock held */
3048 static void
3049 exported_interface_free (ExportedInterface *ei)
3050 {
3051   if (ei->user_data_free_func != NULL)
3052     /* TODO: push to thread-default mainloop */
3053     ei->user_data_free_func (ei->user_data);
3054
3055   if (ei->context != NULL)
3056     g_main_context_unref (ei->context);
3057
3058   g_free (ei->interface_name);
3059   g_free (ei);
3060 }
3061
3062 /* ---------------------------------------------------------------------------------------------------- */
3063
3064 typedef struct
3065 {
3066   GDBusConnection *connection;
3067   GDBusMessage *message;
3068   gpointer user_data;
3069   const char *property_name;
3070   const GDBusInterfaceVTable *vtable;
3071   const GDBusInterfaceInfo *interface_info;
3072   const GDBusPropertyInfo *property_info;
3073 } PropertyData;
3074
3075 static void
3076 property_data_free (PropertyData *data)
3077 {
3078   g_object_unref (data->connection);
3079   g_object_unref (data->message);
3080   g_free (data);
3081 }
3082
3083 /* called in thread where object was registered - no locks held */
3084 static gboolean
3085 invoke_get_property_in_idle_cb (gpointer _data)
3086 {
3087   PropertyData *data = _data;
3088   GVariant *value;
3089   GError *error;
3090   GDBusMessage *reply;
3091
3092   error = NULL;
3093   value = data->vtable->get_property (data->connection,
3094                                       g_dbus_message_get_sender (data->message),
3095                                       g_dbus_message_get_path (data->message),
3096                                       data->interface_info->name,
3097                                       data->property_name,
3098                                       &error,
3099                                       data->user_data);
3100
3101
3102   if (value != NULL)
3103     {
3104       g_assert_no_error (error);
3105
3106       g_variant_ref_sink (value);
3107       reply = g_dbus_message_new_method_reply (data->message);
3108       g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3109       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3110       g_variant_unref (value);
3111       g_object_unref (reply);
3112     }
3113   else
3114     {
3115       gchar *dbus_error_name;
3116
3117       g_assert (error != NULL);
3118
3119       dbus_error_name = g_dbus_error_encode_gerror (error);
3120       reply = g_dbus_message_new_method_error_literal (data->message,
3121                                                        dbus_error_name,
3122                                                        error->message);
3123       g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3124       g_free (dbus_error_name);
3125       g_error_free (error);
3126       g_object_unref (reply);
3127     }
3128
3129   return FALSE;
3130 }
3131
3132 /* called in thread where object was registered - no locks held */
3133 static gboolean
3134 invoke_set_property_in_idle_cb (gpointer _data)
3135 {
3136   PropertyData *data = _data;
3137   GError *error;
3138   GDBusMessage *reply;
3139   GVariant *value;
3140
3141   error = NULL;
3142   value = NULL;
3143
3144   g_variant_get (g_dbus_message_get_body (data->message),
3145                  "(ssv)",
3146                  NULL,
3147                  NULL,
3148                  &value);
3149
3150   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3151    * of the given value is wrong
3152    */
3153   if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3154     {
3155       reply = g_dbus_message_new_method_error (data->message,
3156                                                "org.freedesktop.DBus.Error.InvalidArgs",
3157                                                _("Error setting property `%s': Expected type `%s' but got `%s'"),
3158                                                data->property_info->name,
3159                                                data->property_info->signature,
3160                                                g_variant_get_type_string (value));
3161       goto out;
3162     }
3163
3164   if (!data->vtable->set_property (data->connection,
3165                                    g_dbus_message_get_sender (data->message),
3166                                    g_dbus_message_get_path (data->message),
3167                                    data->interface_info->name,
3168                                    data->property_name,
3169                                    value,
3170                                    &error,
3171                                    data->user_data))
3172     {
3173       gchar *dbus_error_name;
3174       g_assert (error != NULL);
3175       dbus_error_name = g_dbus_error_encode_gerror (error);
3176       reply = g_dbus_message_new_method_error_literal (data->message,
3177                                                        dbus_error_name,
3178                                                        error->message);
3179       g_free (dbus_error_name);
3180       g_error_free (error);
3181     }
3182   else
3183     {
3184       reply = g_dbus_message_new_method_reply (data->message);
3185     }
3186
3187  out:
3188   g_assert (reply != NULL);
3189   g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3190   g_object_unref (reply);
3191
3192   return FALSE;
3193 }
3194
3195 /* called with lock held */
3196 static gboolean
3197 validate_and_maybe_schedule_property_getset (GDBusConnection            *connection,
3198                                              GDBusMessage               *message,
3199                                              gboolean                    is_get,
3200                                              const GDBusInterfaceInfo   *introspection_data,
3201                                              const GDBusInterfaceVTable *vtable,
3202                                              GMainContext               *main_context,
3203                                              gpointer                    user_data)
3204 {
3205   gboolean handled;
3206   const char *interface_name;
3207   const char *property_name;
3208   const GDBusPropertyInfo *property_info;
3209   GSource *idle_source;
3210   PropertyData *property_data;
3211   GDBusMessage *reply;
3212
3213   handled = FALSE;
3214
3215   if (is_get)
3216     g_variant_get (g_dbus_message_get_body (message),
3217                    "(&s&s)",
3218                    &interface_name,
3219                    &property_name);
3220   else
3221     g_variant_get (g_dbus_message_get_body (message),
3222                    "(&s&sv)",
3223                    &interface_name,
3224                    &property_name,
3225                    NULL);
3226
3227
3228   if (is_get)
3229     {
3230       if (vtable == NULL || vtable->get_property == NULL)
3231         goto out;
3232     }
3233   else
3234     {
3235       if (vtable == NULL || vtable->set_property == NULL)
3236         goto out;
3237     }
3238
3239   /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3240    */
3241   property_info = NULL;
3242
3243   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3244   property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3245   if (property_info == NULL)
3246     {
3247       reply = g_dbus_message_new_method_error (message,
3248                                                "org.freedesktop.DBus.Error.InvalidArgs",
3249                                                _("No such property `%s'"),
3250                                                property_name);
3251       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3252       g_object_unref (reply);
3253       handled = TRUE;
3254       goto out;
3255     }
3256
3257   if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3258     {
3259       reply = g_dbus_message_new_method_error (message,
3260                                                "org.freedesktop.DBus.Error.InvalidArgs",
3261                                                _("Property `%s' is not readable"),
3262                                                property_name);
3263       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3264       g_object_unref (reply);
3265       handled = TRUE;
3266       goto out;
3267     }
3268   else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3269     {
3270       reply = g_dbus_message_new_method_error (message,
3271                                                "org.freedesktop.DBus.Error.InvalidArgs",
3272                                                _("Property `%s' is not writable"),
3273                                                property_name);
3274       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3275       g_object_unref (reply);
3276       handled = TRUE;
3277       goto out;
3278     }
3279
3280   /* ok, got the property info - call user code in an idle handler */
3281   property_data = g_new0 (PropertyData, 1);
3282   property_data->connection = g_object_ref (connection);
3283   property_data->message = g_object_ref (message);
3284   property_data->user_data = user_data;
3285   property_data->property_name = property_name;
3286   property_data->vtable = vtable;
3287   property_data->interface_info = introspection_data;
3288   property_data->property_info = property_info;
3289
3290   idle_source = g_idle_source_new ();
3291   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3292   g_source_set_callback (idle_source,
3293                          is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3294                          property_data,
3295                          (GDestroyNotify) property_data_free);
3296   g_source_attach (idle_source, main_context);
3297   g_source_unref (idle_source);
3298
3299   handled = TRUE;
3300
3301  out:
3302   return handled;
3303 }
3304
3305 /* called with lock held */
3306 static gboolean
3307 handle_getset_property (GDBusConnection *connection,
3308                         ExportedObject  *eo,
3309                         GDBusMessage    *message,
3310                         gboolean         is_get)
3311 {
3312   ExportedInterface *ei;
3313   gboolean handled;
3314   const char *interface_name;
3315   const char *property_name;
3316
3317   handled = FALSE;
3318
3319   if (is_get)
3320     g_variant_get (g_dbus_message_get_body (message),
3321                    "(&s&s)",
3322                    &interface_name,
3323                    &property_name);
3324   else
3325     g_variant_get (g_dbus_message_get_body (message),
3326                    "(&s&sv)",
3327                    &interface_name,
3328                    &property_name,
3329                    NULL);
3330
3331   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3332    * no such interface registered
3333    */
3334   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3335   if (ei == NULL)
3336     {
3337       GDBusMessage *reply;
3338       reply = g_dbus_message_new_method_error (message,
3339                                                "org.freedesktop.DBus.Error.InvalidArgs",
3340                                                _("No such interface `%s'"),
3341                                                interface_name);
3342       g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3343       g_object_unref (reply);
3344       handled = TRUE;
3345       goto out;
3346     }
3347
3348   handled = validate_and_maybe_schedule_property_getset (eo->connection,
3349                                                          message,
3350                                                          is_get,
3351                                                          ei->introspection_data,
3352                                                          ei->vtable,
3353                                                          ei->context,
3354                                                          ei->user_data);
3355  out:
3356   return handled;
3357 }
3358
3359 /* ---------------------------------------------------------------------------------------------------- */
3360
3361 typedef struct
3362 {
3363   GDBusConnection *connection;
3364   GDBusMessage *message;
3365   gpointer user_data;
3366   const GDBusInterfaceVTable *vtable;
3367   const GDBusInterfaceInfo *interface_info;
3368 } PropertyGetAllData;
3369
3370 static void
3371 property_get_all_data_free (PropertyData *data)
3372 {
3373   g_object_unref (data->connection);
3374   g_object_unref (data->message);
3375   g_free (data);
3376 }
3377
3378 /* called in thread where object was registered - no locks held */
3379 static gboolean
3380 invoke_get_all_properties_in_idle_cb (gpointer _data)
3381 {
3382   PropertyGetAllData *data = _data;
3383   GVariantBuilder builder;
3384   GError *error;
3385   GDBusMessage *reply;
3386   guint n;
3387
3388   error = NULL;
3389
3390   /* TODO: Right now we never fail this call - we just omit values if
3391    *       a get_property() call is failing.
3392    *
3393    *       We could fail the whole call if just a single get_property() call
3394    *       returns an error. We need clarification in the D-Bus spec about this.
3395    */
3396   g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3397   g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3398   for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3399     {
3400       const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3401       GVariant *value;
3402
3403       if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3404         continue;
3405
3406       value = data->vtable->get_property (data->connection,
3407                                           g_dbus_message_get_sender (data->message),
3408                                           g_dbus_message_get_path (data->message),
3409                                           data->interface_info->name,
3410                                           property_info->name,
3411                                           NULL,
3412                                           data->user_data);
3413
3414       if (value == NULL)
3415         continue;
3416
3417       g_variant_builder_add (&builder,
3418                              "{sv}",
3419                              property_info->name,
3420                              value);
3421     }
3422   g_variant_builder_close (&builder);
3423
3424   reply = g_dbus_message_new_method_reply (data->message);
3425   g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3426   g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3427   g_object_unref (reply);
3428
3429   return FALSE;
3430 }
3431
3432 /* called with lock held */
3433 static gboolean
3434 validate_and_maybe_schedule_property_get_all (GDBusConnection            *connection,
3435                                               GDBusMessage               *message,
3436                                               const GDBusInterfaceInfo   *introspection_data,
3437                                               const GDBusInterfaceVTable *vtable,
3438                                               GMainContext               *main_context,
3439                                               gpointer                    user_data)
3440 {
3441   gboolean handled;
3442   const char *interface_name;
3443   GSource *idle_source;
3444   PropertyGetAllData *property_get_all_data;
3445
3446   handled = FALSE;
3447
3448   g_variant_get (g_dbus_message_get_body (message),
3449                  "(&s)",
3450                  &interface_name);
3451
3452   if (vtable == NULL || vtable->get_property == NULL)
3453     goto out;
3454
3455   /* ok, got the property info - call user in an idle handler */
3456   property_get_all_data = g_new0 (PropertyGetAllData, 1);
3457   property_get_all_data->connection = g_object_ref (connection);
3458   property_get_all_data->message = g_object_ref (message);
3459   property_get_all_data->user_data = user_data;
3460   property_get_all_data->vtable = vtable;
3461   property_get_all_data->interface_info = introspection_data;
3462
3463   idle_source = g_idle_source_new ();
3464   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3465   g_source_set_callback (idle_source,
3466                          invoke_get_all_properties_in_idle_cb,
3467                          property_get_all_data,
3468                          (GDestroyNotify) property_get_all_data_free);
3469   g_source_attach (idle_source, main_context);
3470   g_source_unref (idle_source);
3471
3472   handled = TRUE;
3473
3474  out:
3475   return handled;
3476 }
3477
3478 /* called with lock held */
3479 static gboolean
3480 handle_get_all_properties (GDBusConnection *connection,
3481                            ExportedObject  *eo,
3482                            GDBusMessage    *message)
3483 {
3484   ExportedInterface *ei;
3485   gboolean handled;
3486   const char *interface_name;
3487
3488   handled = FALSE;
3489
3490   g_variant_get (g_dbus_message_get_body (message),
3491                  "(&s)",
3492                  &interface_name);
3493
3494   /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3495    * no such interface registered
3496    */
3497   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3498   if (ei == NULL)
3499     {
3500       GDBusMessage *reply;
3501       reply = g_dbus_message_new_method_error (message,
3502                                                "org.freedesktop.DBus.Error.InvalidArgs",
3503                                                _("No such interface"),
3504                                                interface_name);
3505       g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3506       g_object_unref (reply);
3507       handled = TRUE;
3508       goto out;
3509     }
3510
3511   handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3512                                                           message,
3513                                                           ei->introspection_data,
3514                                                           ei->vtable,
3515                                                           ei->context,
3516                                                           ei->user_data);
3517  out:
3518   return handled;
3519 }
3520
3521 /* ---------------------------------------------------------------------------------------------------- */
3522
3523 static const gchar introspect_header[] =
3524   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3525   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3526   "<!-- GDBus " PACKAGE_VERSION " -->\n"
3527   "<node>\n";
3528
3529 static const gchar introspect_tail[] =
3530   "</node>\n";
3531
3532 static const gchar introspect_standard_interfaces[] =
3533   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
3534   "    <method name=\"Get\">\n"
3535   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3536   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3537   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3538   "    </method>\n"
3539   "    <method name=\"GetAll\">\n"
3540   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3541   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3542   "    </method>\n"
3543   "    <method name=\"Set\">\n"
3544   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3545   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3546   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3547   "    </method>\n"
3548   "    <signal name=\"PropertiesChanged\">\n"
3549   "      <arg type=\"s\" name=\"interface_name\"/>\n"
3550   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3551   "      <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3552   "    </signal>\n"
3553   "  </interface>\n"
3554   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3555   "    <method name=\"Introspect\">\n"
3556   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3557   "    </method>\n"
3558   "  </interface>\n"
3559   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
3560   "    <method name=\"Ping\"/>\n"
3561   "    <method name=\"GetMachineId\">\n"
3562   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3563   "    </method>\n"
3564   "  </interface>\n";
3565
3566 static void
3567 introspect_append_header (GString *s)
3568 {
3569   g_string_append (s, introspect_header);
3570 }
3571
3572 static void
3573 introspect_append_standard_interfaces (GString *s)
3574 {
3575   g_string_append (s, introspect_standard_interfaces);
3576 }
3577
3578 static void
3579 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3580 {
3581   if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len)
3582     {
3583       const gchar *begin;
3584       const gchar *end;
3585       gchar *s;
3586
3587       begin = object_path + path_len;
3588       end = strchr (begin, '/');
3589
3590       if (end != NULL)
3591         s = g_strndup (begin, end - begin);
3592       else
3593         s = g_strdup (begin);
3594
3595       if (g_hash_table_lookup (set, s) == NULL)
3596         g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3597       else
3598         g_free (s);
3599     }
3600 }
3601
3602 /* TODO: we want a nicer public interface for this */
3603 static gchar **
3604 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3605                                             const gchar     *path)
3606 {
3607   GPtrArray *p;
3608   gchar **ret;
3609   GHashTableIter hash_iter;
3610   const gchar *object_path;
3611   gsize path_len;
3612   GHashTable *set;
3613   GList *keys;
3614   GList *l;
3615
3616   CONNECTION_ENSURE_LOCK (connection);
3617
3618   path_len = strlen (path);
3619   if (path_len > 1)
3620     path_len++;
3621
3622   set = g_hash_table_new (g_str_hash, g_str_equal);
3623
3624   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3625   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3626     maybe_add_path (path, path_len, object_path, set);
3627
3628   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3629   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3630     maybe_add_path (path, path_len, object_path, set);
3631
3632   p = g_ptr_array_new ();
3633   keys = g_hash_table_get_keys (set);
3634   for (l = keys; l != NULL; l = l->next)
3635     g_ptr_array_add (p, l->data);
3636   g_hash_table_unref (set);
3637   g_list_free (keys);
3638
3639   g_ptr_array_add (p, NULL);
3640   ret = (gchar **) g_ptr_array_free (p, FALSE);
3641   return ret;
3642 }
3643
3644 static gchar **
3645 g_dbus_connection_list_registered (GDBusConnection *connection,
3646                                    const gchar     *path)
3647 {
3648   gchar **ret;
3649   CONNECTION_LOCK (connection);
3650   ret = g_dbus_connection_list_registered_unlocked (connection, path);
3651   CONNECTION_UNLOCK (connection);
3652   return ret;
3653 }
3654
3655 /* called in message handler thread with lock held */
3656 static gboolean
3657 handle_introspect (GDBusConnection *connection,
3658                    ExportedObject  *eo,
3659                    GDBusMessage    *message)
3660 {
3661   guint n;
3662   GString *s;
3663   GDBusMessage *reply;
3664   GHashTableIter hash_iter;
3665   ExportedInterface *ei;
3666   gchar **registered;
3667
3668   /* first the header with the standard interfaces */
3669   s = g_string_sized_new (sizeof (introspect_header) +
3670                           sizeof (introspect_standard_interfaces) +
3671                           sizeof (introspect_tail));
3672   introspect_append_header (s);
3673   introspect_append_standard_interfaces (s);
3674
3675   /* then include the registered interfaces */
3676   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3677   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3678     g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3679
3680   /* finally include nodes registered below us */
3681   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3682   for (n = 0; registered != NULL && registered[n] != NULL; n++)
3683     g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
3684   g_strfreev (registered);
3685   g_string_append (s, introspect_tail);
3686
3687   reply = g_dbus_message_new_method_reply (message);
3688   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3689   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3690   g_object_unref (reply);
3691   g_string_free (s, TRUE);
3692
3693   return TRUE;
3694 }
3695
3696 /* called in thread where object was registered - no locks held */
3697 static gboolean
3698 call_in_idle_cb (gpointer user_data)
3699 {
3700   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3701   GDBusInterfaceVTable *vtable;
3702
3703   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3704   g_assert (vtable != NULL && vtable->method_call != NULL);
3705
3706   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3707                        g_dbus_method_invocation_get_sender (invocation),
3708                        g_dbus_method_invocation_get_object_path (invocation),
3709                        g_dbus_method_invocation_get_interface_name (invocation),
3710                        g_dbus_method_invocation_get_method_name (invocation),
3711                        g_dbus_method_invocation_get_parameters (invocation),
3712                        g_object_ref (invocation),
3713                        g_dbus_method_invocation_get_user_data (invocation));
3714
3715   return FALSE;
3716 }
3717
3718 /* called in message handler thread with lock held */
3719 static gboolean
3720 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
3721                                          GDBusMessage               *message,
3722                                          const GDBusInterfaceInfo   *introspection_data,
3723                                          const GDBusInterfaceVTable *vtable,
3724                                          GMainContext               *main_context,
3725                                          gpointer                    user_data)
3726 {
3727   GDBusMethodInvocation *invocation;
3728   const GDBusMethodInfo *method_info;
3729   GDBusMessage *reply;
3730   GVariant *parameters;
3731   GSource *idle_source;
3732   gboolean handled;
3733   gchar *in_signature;
3734
3735   handled = FALSE;
3736
3737   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3738   method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3739
3740   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3741    * error to the caller
3742    */
3743   if (method_info == NULL)
3744     {
3745       reply = g_dbus_message_new_method_error (message,
3746                                                "org.freedesktop.DBus.Error.UnknownMethod",
3747                                                _("No such method `%s'"),
3748                                                g_dbus_message_get_member (message));
3749       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3750       g_object_unref (reply);
3751       handled = TRUE;
3752       goto out;
3753     }
3754
3755   /* Check that the incoming args are of the right type - if they are not, return
3756    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3757    *
3758    * TODO: might also be worth caching the combined signature.
3759    */
3760   in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3761   if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3762     {
3763       reply = g_dbus_message_new_method_error (message,
3764                                                "org.freedesktop.DBus.Error.InvalidArgs",
3765                                                _("Signature of message, `%s', does not match expected signature `%s'"),
3766                                                g_dbus_message_get_signature (message),
3767                                                in_signature);
3768       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3769       g_object_unref (reply);
3770       g_free (in_signature);
3771       handled = TRUE;
3772       goto out;
3773     }
3774   g_free (in_signature);
3775
3776   parameters = g_dbus_message_get_body (message);
3777   if (parameters == NULL)
3778     {
3779       parameters = g_variant_new ("()");
3780       g_variant_ref_sink (parameters);
3781     }
3782   else
3783     {
3784       g_variant_ref (parameters);
3785     }
3786
3787   /* schedule the call in idle */
3788   invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3789                                              g_dbus_message_get_path (message),
3790                                              g_dbus_message_get_interface (message),
3791                                              g_dbus_message_get_member (message),
3792                                              method_info,
3793                                              connection,
3794                                              message,
3795                                              parameters,
3796                                              user_data);
3797   g_variant_unref (parameters);
3798   g_object_set_data (G_OBJECT (invocation),
3799                      "g-dbus-interface-vtable",
3800                      (gpointer) vtable);
3801
3802   idle_source = g_idle_source_new ();
3803   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3804   g_source_set_callback (idle_source,
3805                          call_in_idle_cb,
3806                          invocation,
3807                          g_object_unref);
3808   g_source_attach (idle_source, main_context);
3809   g_source_unref (idle_source);
3810
3811   handled = TRUE;
3812
3813  out:
3814   return handled;
3815 }
3816
3817 /* ---------------------------------------------------------------------------------------------------- */
3818
3819 /* called in message handler thread with lock held */
3820 static gboolean
3821 obj_message_func (GDBusConnection *connection,
3822                   ExportedObject  *eo,
3823                   GDBusMessage    *message)
3824 {
3825   const gchar *interface_name;
3826   const gchar *member;
3827   const gchar *signature;
3828   gboolean handled;
3829
3830   handled = FALSE;
3831
3832   interface_name = g_dbus_message_get_interface (message);
3833   member = g_dbus_message_get_member (message);
3834   signature = g_dbus_message_get_signature (message);
3835
3836   /* see if we have an interface for handling this call */
3837   if (interface_name != NULL)
3838     {
3839       ExportedInterface *ei;
3840       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3841       if (ei != NULL)
3842         {
3843           /* we do - invoke the handler in idle in the right thread */
3844
3845           /* handle no vtable or handler being present */
3846           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3847             goto out;
3848
3849           handled = validate_and_maybe_schedule_method_call (connection,
3850                                                              message,
3851                                                              ei->introspection_data,
3852                                                              ei->vtable,
3853                                                              ei->context,
3854                                                              ei->user_data);
3855           goto out;
3856         }
3857     }
3858
3859   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3860       g_strcmp0 (member, "Introspect") == 0 &&
3861       g_strcmp0 (signature, "") == 0)
3862     {
3863       handled = handle_introspect (connection, eo, message);
3864       goto out;
3865     }
3866   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3867            g_strcmp0 (member, "Get") == 0 &&
3868            g_strcmp0 (signature, "ss") == 0)
3869     {
3870       handled = handle_getset_property (connection, eo, message, TRUE);
3871       goto out;
3872     }
3873   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3874            g_strcmp0 (member, "Set") == 0 &&
3875            g_strcmp0 (signature, "ssv") == 0)
3876     {
3877       handled = handle_getset_property (connection, eo, message, FALSE);
3878       goto out;
3879     }
3880   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3881            g_strcmp0 (member, "GetAll") == 0 &&
3882            g_strcmp0 (signature, "s") == 0)
3883     {
3884       handled = handle_get_all_properties (connection, eo, message);
3885       goto out;
3886     }
3887
3888  out:
3889   return handled;
3890 }
3891
3892 /**
3893  * g_dbus_connection_register_object:
3894  * @connection: A #GDBusConnection.
3895  * @object_path: The object path to register at.
3896  * @introspection_data: Introspection data for the interface.
3897  * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3898  * @user_data: Data to pass to functions in @vtable.
3899  * @user_data_free_func: Function to call when the object path is unregistered.
3900  * @error: Return location for error or %NULL.
3901  *
3902  * Registers callbacks for exported objects at @object_path with the
3903  * D-Bus interface that is described in @introspection_data.
3904  *
3905  * Calls to functions in @vtable (and @user_data_free_func) will
3906  * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3907  * loop</link> of the thread you are calling this method from.
3908  *
3909  * Note that all #GVariant values passed to functions in @vtable will match
3910  * the signature given in @introspection_data - if a remote caller passes
3911  * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3912  * is returned to the remote caller.
3913  *
3914  * Additionally, if the remote caller attempts to invoke methods or
3915  * access properties not mentioned in @introspection_data the
3916  * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3917  * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3918  * are returned to the caller.
3919  *
3920  * It is considered a programming error if the
3921  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3922  * #GVariant of incorrect type.
3923  *
3924  * If an existing callback is already registered at @object_path and
3925  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3926  *
3927  * GDBus automatically implements the standard D-Bus interfaces
3928  * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
3929  * and org.freedesktop.Peer, so you don't have to implement those for
3930  * the objects you export. You <emphasis>can</emphasis> implement
3931  * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
3932  * and setting of properties asynchronously.
3933  *
3934  * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3935  *
3936  * Returns: 0 if @error is set, otherwise a registration id (never 0)
3937  * that can be used with g_dbus_connection_unregister_object() .
3938  *
3939  * Since: 2.26
3940  */
3941 guint
3942 g_dbus_connection_register_object (GDBusConnection            *connection,
3943                                    const gchar                *object_path,
3944                                    const GDBusInterfaceInfo   *introspection_data,
3945                                    const GDBusInterfaceVTable *vtable,
3946                                    gpointer                    user_data,
3947                                    GDestroyNotify              user_data_free_func,
3948                                    GError                    **error)
3949 {
3950   ExportedObject *eo;
3951   ExportedInterface *ei;
3952   guint ret;
3953
3954   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3955   g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3956   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3957   g_return_val_if_fail (introspection_data != NULL, 0);
3958   g_return_val_if_fail (g_dbus_is_interface_name (introspection_data->name), 0);
3959   g_return_val_if_fail (error == NULL || *error == NULL, 0);
3960
3961   ret = 0;
3962
3963   CONNECTION_LOCK (connection);
3964
3965   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3966   if (eo == NULL)
3967     {
3968       eo = g_new0 (ExportedObject, 1);
3969       eo->object_path = g_strdup (object_path);
3970       eo->connection = connection;
3971       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3972                                                      g_str_equal,
3973                                                      NULL,
3974                                                      (GDestroyNotify) exported_interface_free);
3975       g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3976     }
3977
3978   ei = g_hash_table_lookup (eo->map_if_name_to_ei, introspection_data->name);
3979   if (ei != NULL)
3980     {
3981       g_set_error (error,
3982                    G_IO_ERROR,
3983                    G_IO_ERROR_EXISTS,
3984                    _("An object is already exported for the interface %s at %s"),
3985                    introspection_data->name,
3986                    object_path);
3987       goto out;
3988     }
3989
3990   ei = g_new0 (ExportedInterface, 1);
3991   ei->id = _global_registration_id++; /* TODO: overflow etc. */
3992   ei->eo = eo;
3993   ei->user_data = user_data;
3994   ei->user_data_free_func = user_data_free_func;
3995   ei->vtable = vtable;
3996   ei->introspection_data = introspection_data;
3997   ei->interface_name = g_strdup (introspection_data->name);
3998   ei->context = g_main_context_get_thread_default ();
3999   if (ei->context != NULL)
4000     g_main_context_ref (ei->context);
4001
4002   g_hash_table_insert (eo->map_if_name_to_ei,
4003                        (gpointer) ei->interface_name,
4004                        ei);
4005   g_hash_table_insert (connection->priv->map_id_to_ei,
4006                        GUINT_TO_POINTER (ei->id),
4007                        ei);
4008
4009   ret = ei->id;
4010
4011  out:
4012   CONNECTION_UNLOCK (connection);
4013
4014   return ret;
4015 }
4016
4017 /**
4018  * g_dbus_connection_unregister_object:
4019  * @connection: A #GDBusConnection.
4020  * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4021  *
4022  * Unregisters an object.
4023  *
4024  * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4025  *
4026  * Since: 2.26
4027  */
4028 gboolean
4029 g_dbus_connection_unregister_object (GDBusConnection *connection,
4030                                      guint            registration_id)
4031 {
4032   ExportedInterface *ei;
4033   ExportedObject *eo;
4034   gboolean ret;
4035
4036   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4037
4038   ret = FALSE;
4039
4040   CONNECTION_LOCK (connection);
4041
4042   ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4043                             GUINT_TO_POINTER (registration_id));
4044   if (ei == NULL)
4045     goto out;
4046
4047   eo = ei->eo;
4048
4049   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4050   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4051   /* unregister object path if we have no more exported interfaces */
4052   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4053     g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4054                                          eo->object_path));
4055
4056   ret = TRUE;
4057
4058  out:
4059   CONNECTION_UNLOCK (connection);
4060
4061   return ret;
4062 }
4063
4064 /* ---------------------------------------------------------------------------------------------------- */
4065
4066 /**
4067  * g_dbus_connection_emit_signal:
4068  * @connection: A #GDBusConnection.
4069  * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4070  * @object_path: Path of remote object.
4071  * @interface_name: D-Bus interface to emit a signal on.
4072  * @signal_name: The name of the signal to emit.
4073  * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4074  * @error: Return location for error or %NULL.
4075  *
4076  * Emits a signal.
4077  *
4078  * If the parameters GVariant is floating, it is consumed.
4079  *
4080  * This can only fail if @parameters is not compatible with the D-Bus protocol.
4081  *
4082  * Returns: %TRUE unless @error is set.
4083  *
4084  * Since: 2.26
4085  */
4086 gboolean
4087 g_dbus_connection_emit_signal (GDBusConnection  *connection,
4088                                const gchar      *destination_bus_name,
4089                                const gchar      *object_path,
4090                                const gchar      *interface_name,
4091                                const gchar      *signal_name,
4092                                GVariant         *parameters,
4093                                GError          **error)
4094 {
4095   GDBusMessage *message;
4096   gboolean ret;
4097
4098   message = NULL;
4099   ret = FALSE;
4100
4101   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4102   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4103   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4104   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4105   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4106   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4107
4108   message = g_dbus_message_new_signal (object_path,
4109                                        interface_name,
4110                                        signal_name);
4111
4112   if (destination_bus_name != NULL)
4113     g_dbus_message_set_header (message,
4114                                G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4115                                g_variant_new_string (destination_bus_name));
4116
4117   if (parameters != NULL)
4118     g_dbus_message_set_body (message, parameters);
4119
4120   ret = g_dbus_connection_send_message (connection, message, NULL, error);
4121   g_object_unref (message);
4122
4123   return ret;
4124 }
4125
4126 static void
4127 add_call_flags (GDBusMessage           *message,
4128                          GDBusCallFlags  flags)
4129 {
4130   if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4131     g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4132 }
4133
4134 /**
4135  * g_dbus_connection_call:
4136  * @connection: A #GDBusConnection.
4137  * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4138  * @object_path: Path of remote object.
4139  * @interface_name: D-Bus interface to invoke method on.
4140  * @method_name: The name of the method to invoke.
4141  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4142  * @flags: Flags from the #GDBusCallFlags enumeration.
4143  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4144  * @cancellable: A #GCancellable or %NULL.
4145  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4146  * care about the result of the method invocation.
4147  * @user_data: The data to pass to @callback.
4148  *
4149  * Asynchronously invokes the @method_name method on the
4150  * @interface_name D-Bus interface on the remote object at
4151  * @object_path owned by @bus_name.
4152  *
4153  * If @connection is closed then the operation will fail with
4154  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4155  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4156  * not compatible with the D-Bus protocol, the operation fails with
4157  * %G_IO_ERROR_INVALID_ARGUMENT.
4158  *
4159  * If the @parameters #GVariant is floating, it is consumed. This allows
4160  * convenient 'inline' use of g_variant_new(), e.g.:
4161  * |[
4162  *  g_dbus_connection_call (connection,
4163  *                          "org.freedesktop.StringThings",
4164  *                          "/org/freedesktop/StringThings",
4165  *                          "org.freedesktop.StringThings",
4166  *                          "TwoStrings",
4167  *                          g_variant_new ("(ss)",
4168  *                                         "Thing One",
4169  *                                         "Thing Two"),
4170  *                          G_DBUS_CALL_FLAGS_NONE,
4171  *                          -1,
4172  *                          NULL,
4173  *                          (GAsyncReadyCallback) two_strings_done,
4174  *                          NULL);
4175  * ]|
4176  *
4177  * This is an asynchronous method. When the operation is finished, @callback will be invoked
4178  * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4179  * of the thread you are calling this method from. You can then call
4180  * g_dbus_connection_call_finish() to get the result of the operation.
4181  * See g_dbus_connection_call_sync() for the synchronous version of this
4182  * function.
4183  *
4184  * Since: 2.26
4185  */
4186 void
4187 g_dbus_connection_call (GDBusConnection        *connection,
4188                         const gchar            *bus_name,
4189                         const gchar            *object_path,
4190                         const gchar            *interface_name,
4191                         const gchar            *method_name,
4192                         GVariant               *parameters,
4193                         GDBusCallFlags          flags,
4194                         gint                    timeout_msec,
4195                         GCancellable           *cancellable,
4196                         GAsyncReadyCallback     callback,
4197                         gpointer                user_data)
4198 {
4199   GDBusMessage *message;
4200
4201   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4202   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4203   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4204   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4205   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4206   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4207   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4208
4209   message = g_dbus_message_new_method_call (bus_name,
4210                                             object_path,
4211                                             interface_name,
4212                                             method_name);
4213   add_call_flags (message, flags);
4214   if (parameters != NULL)
4215     g_dbus_message_set_body (message, parameters);
4216
4217   g_dbus_connection_send_message_with_reply (connection,
4218                                              message,
4219                                              timeout_msec,
4220                                              NULL, /* volatile guint32 *out_serial */
4221                                              cancellable,
4222                                              callback,
4223                                              user_data);
4224
4225   if (message != NULL)
4226     g_object_unref (message);
4227 }
4228
4229 static GVariant *
4230 decode_method_reply (GDBusMessage  *reply,
4231                      GError       **error)
4232 {
4233   GVariant *result;
4234
4235   result = NULL;
4236   switch (g_dbus_message_get_message_type (reply))
4237     {
4238     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4239       result = g_dbus_message_get_body (reply);
4240       if (result == NULL)
4241         {
4242           result = g_variant_new ("()");
4243           g_variant_ref_sink (result);
4244         }
4245       else
4246         {
4247           g_variant_ref (result);
4248         }
4249       break;
4250
4251     case G_DBUS_MESSAGE_TYPE_ERROR:
4252       g_dbus_message_to_gerror (reply, error);
4253       break;
4254
4255     default:
4256       g_assert_not_reached ();
4257       break;
4258     }
4259
4260   return result;
4261 }
4262
4263 /**
4264  * g_dbus_connection_call_finish:
4265  * @connection: A #GDBusConnection.
4266  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4267  * @error: Return location for error or %NULL.
4268  *
4269  * Finishes an operation started with g_dbus_connection_call().
4270  *
4271  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4272  * return values. Free with g_variant_unref().
4273  *
4274  * Since: 2.26
4275  */
4276 GVariant *
4277 g_dbus_connection_call_finish (GDBusConnection  *connection,
4278                                GAsyncResult     *res,
4279                                GError          **error)
4280 {
4281   GDBusMessage *reply;
4282   GVariant *result;
4283
4284   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4285   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4286   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4287
4288   result = NULL;
4289
4290   reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4291   if (reply == NULL)
4292     goto out;
4293
4294   result = decode_method_reply (reply, error);
4295
4296   g_object_unref (reply);
4297
4298  out:
4299   return result;
4300 }
4301
4302 /* ---------------------------------------------------------------------------------------------------- */
4303
4304 /**
4305  * g_dbus_connection_call_sync:
4306  * @connection: A #GDBusConnection.
4307  * @bus_name: A unique or well-known bus name.
4308  * @object_path: Path of remote object.
4309  * @interface_name: D-Bus interface to invoke method on.
4310  * @method_name: The name of the method to invoke.
4311  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4312  * @flags: Flags from the #GDBusCallFlags enumeration.
4313  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4314  * @cancellable: A #GCancellable or %NULL.
4315  * @error: Return location for error or %NULL.
4316  *
4317  * Synchronously invokes the @method_name method on the
4318  * @interface_name D-Bus interface on the remote object at
4319  * @object_path owned by @bus_name.
4320  *
4321  * If @connection is closed then the operation will fail with
4322  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4323  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4324  * contains a value not compatible with the D-Bus protocol, the operation
4325  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4326  *
4327  * If the @parameters #GVariant is floating, it is consumed.
4328  * This allows convenient 'inline' use of g_variant_new(), e.g.:
4329  * |[
4330  *  g_dbus_connection_call_sync (connection,
4331  *                               "org.freedesktop.StringThings",
4332  *                               "/org/freedesktop/StringThings",
4333  *                               "org.freedesktop.StringThings",
4334  *                               "TwoStrings",
4335  *                               g_variant_new ("(ss)",
4336  *                                              "Thing One",
4337  *                                              "Thing Two"),
4338  *                               G_DBUS_CALL_FLAGS_NONE,
4339  *                               -1,
4340  *                               NULL,
4341  *                               &amp;error);
4342  * ]|
4343  *
4344  * The calling thread is blocked until a reply is received. See
4345  * g_dbus_connection_call() for the asynchronous version of
4346  * this method.
4347  *
4348  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4349  * return values. Free with g_variant_unref().
4350  *
4351  * Since: 2.26
4352  */
4353 GVariant *
4354 g_dbus_connection_call_sync (GDBusConnection         *connection,
4355                              const gchar             *bus_name,
4356                              const gchar             *object_path,
4357                              const gchar             *interface_name,
4358                              const gchar             *method_name,
4359                              GVariant                *parameters,
4360                              GDBusCallFlags           flags,
4361                              gint                     timeout_msec,
4362                              GCancellable            *cancellable,
4363                              GError                 **error)
4364 {
4365   GDBusMessage *message;
4366   GDBusMessage *reply;
4367   GVariant *result;
4368
4369   message = NULL;
4370   reply = NULL;
4371   result = NULL;
4372
4373   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4374   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4375   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4376   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4377   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4378   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4379   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4380
4381   message = g_dbus_message_new_method_call (bus_name,
4382                                             object_path,
4383                                             interface_name,
4384                                             method_name);
4385   add_call_flags (message, flags);
4386   if (parameters != NULL)
4387     g_dbus_message_set_body (message, parameters);
4388
4389   reply = g_dbus_connection_send_message_with_reply_sync (connection,
4390                                                           message,
4391                                                           timeout_msec,
4392                                                           NULL, /* volatile guint32 *out_serial */
4393                                                           cancellable,
4394                                                           error);
4395
4396   if (reply == NULL)
4397     goto out;
4398
4399   result = decode_method_reply (reply, error);
4400
4401  out:
4402   if (message != NULL)
4403     g_object_unref (message);
4404   if (reply != NULL)
4405     g_object_unref (reply);
4406
4407   return result;
4408 }
4409
4410 /* ---------------------------------------------------------------------------------------------------- */
4411
4412 struct ExportedSubtree
4413 {
4414   guint                     id;
4415   gchar                    *object_path;
4416   GDBusConnection          *connection;
4417   const GDBusSubtreeVTable *vtable;
4418   GDBusSubtreeFlags         flags;
4419
4420   GMainContext             *context;
4421   gpointer                  user_data;
4422   GDestroyNotify            user_data_free_func;
4423 };
4424
4425 static void
4426 exported_subtree_free (ExportedSubtree *es)
4427 {
4428   if (es->user_data_free_func != NULL)
4429     /* TODO: push to thread-default mainloop */
4430     es->user_data_free_func (es->user_data);
4431
4432   if (es->context != NULL)
4433     g_main_context_unref (es->context);
4434
4435   g_free (es->object_path);
4436   g_free (es);
4437 }
4438
4439 /* called without lock held */
4440 static gboolean
4441 handle_subtree_introspect (GDBusConnection *connection,
4442                            ExportedSubtree *es,
4443                            GDBusMessage    *message)
4444 {
4445   GString *s;
4446   gboolean handled;
4447   GDBusMessage *reply;
4448   gchar **children;
4449   gboolean is_root;
4450   const gchar *sender;
4451   const gchar *requested_object_path;
4452   const gchar *requested_node;
4453   GPtrArray *interfaces;
4454   guint n;
4455   gchar **subnode_paths;
4456
4457   handled = FALSE;
4458
4459   requested_object_path = g_dbus_message_get_path (message);
4460   sender = g_dbus_message_get_sender (message);
4461   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4462
4463   s = g_string_new (NULL);
4464   introspect_append_header (s);
4465
4466   /* Strictly we don't need the children in dynamic mode, but we avoid the
4467    * conditionals to preserve code clarity
4468    */
4469   children = es->vtable->enumerate (es->connection,
4470                                     sender,
4471                                     es->object_path,
4472                                     es->user_data);
4473
4474   if (!is_root)
4475     {
4476       requested_node = strrchr (requested_object_path, '/') + 1;
4477
4478       /* Assert existence of object if we are not dynamic */
4479       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4480           !_g_strv_has_string ((const gchar * const *) children, requested_node))
4481         goto out;
4482     }
4483   else
4484     {
4485       requested_node = "/";
4486     }
4487
4488   interfaces = es->vtable->introspect (es->connection,
4489                                        sender,
4490                                        es->object_path,
4491                                        requested_node,
4492                                        es->user_data);
4493   if (interfaces != NULL)
4494     {
4495       if (interfaces->len > 0)
4496         {
4497           /* we're in business */
4498           introspect_append_standard_interfaces (s);
4499
4500           for (n = 0; n < interfaces->len; n++)
4501             {
4502               const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4503               g_dbus_interface_info_generate_xml (interface_info, 2, s);
4504             }
4505         }
4506       g_ptr_array_unref (interfaces);
4507     }
4508
4509   /* then include <node> entries from the Subtree for the root */
4510   if (is_root)
4511     {
4512       for (n = 0; children != NULL && children[n] != NULL; n++)
4513         g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
4514     }
4515
4516   /* finally include nodes registered below us */
4517   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4518   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4519     g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
4520   g_strfreev (subnode_paths);
4521
4522   g_string_append (s, "</node>\n");
4523
4524   reply = g_dbus_message_new_method_reply (message);
4525   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4526   g_dbus_connection_send_message (connection, reply, NULL, NULL);
4527   g_object_unref (reply);
4528
4529   handled = TRUE;
4530
4531  out:
4532   g_string_free (s, TRUE);
4533   g_strfreev (children);
4534   return handled;
4535 }
4536
4537 /* called without lock held */
4538 static gboolean
4539 handle_subtree_method_invocation (GDBusConnection *connection,
4540                                   ExportedSubtree *es,
4541                                   GDBusMessage    *message)
4542 {
4543   gboolean handled;;
4544   const gchar *sender;
4545   const gchar *interface_name;
4546   const gchar *member;
4547   const gchar *signature;
4548   const gchar *requested_object_path;
4549   const gchar *requested_node;
4550   gboolean is_root;
4551   gchar **children;
4552   const GDBusInterfaceInfo *introspection_data;
4553   const GDBusInterfaceVTable *interface_vtable;
4554   gpointer interface_user_data;
4555   guint n;
4556   GPtrArray *interfaces;
4557   gboolean is_property_get;
4558   gboolean is_property_set;
4559   gboolean is_property_get_all;
4560
4561   handled = FALSE;
4562   interfaces = NULL;
4563
4564   requested_object_path = g_dbus_message_get_path (message);
4565   sender = g_dbus_message_get_sender (message);
4566   interface_name = g_dbus_message_get_interface (message);
4567   member = g_dbus_message_get_member (message);
4568   signature = g_dbus_message_get_signature (message);
4569   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4570
4571   is_property_get = FALSE;
4572   is_property_set = FALSE;
4573   is_property_get_all = FALSE;
4574   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4575     {
4576       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4577         is_property_get = TRUE;
4578       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4579         is_property_set = TRUE;
4580       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4581         is_property_get_all = TRUE;
4582     }
4583
4584   children = es->vtable->enumerate (es->connection,
4585                                     sender,
4586                                     es->object_path,
4587                                     es->user_data);
4588
4589   if (!is_root)
4590     {
4591       requested_node = strrchr (requested_object_path, '/') + 1;
4592
4593       /* If not dynamic, skip if requested node is not part of children */
4594       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4595           !_g_strv_has_string ((const gchar * const *) children, requested_node))
4596         goto out;
4597     }
4598   else
4599     {
4600       requested_node = "/";
4601     }
4602
4603   /* get introspection data for the node */
4604   interfaces = es->vtable->introspect (es->connection,
4605                                        sender,
4606                                        requested_object_path,
4607                                        requested_node,
4608                                        es->user_data);
4609   g_assert (interfaces != NULL);
4610   introspection_data = NULL;
4611   for (n = 0; n < interfaces->len; n++)
4612     {
4613       const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4614       if (g_strcmp0 (id_n->name, interface_name) == 0)
4615         introspection_data = id_n;
4616     }
4617
4618   /* dispatch the call if the user wants to handle it */
4619   if (introspection_data != NULL)
4620     {
4621       /* figure out where to dispatch the method call */
4622       interface_user_data = NULL;
4623       interface_vtable = es->vtable->dispatch (es->connection,
4624                                                sender,
4625                                                es->object_path,
4626                                                interface_name,
4627                                                requested_node,
4628                                                &interface_user_data,
4629                                                es->user_data);
4630       if (interface_vtable == NULL)
4631         goto out;
4632
4633       CONNECTION_LOCK (connection);
4634       handled = validate_and_maybe_schedule_method_call (es->connection,
4635                                                          message,
4636                                                          introspection_data,
4637                                                          interface_vtable,
4638                                                          es->context,
4639                                                          interface_user_data);
4640       CONNECTION_UNLOCK (connection);
4641     }
4642   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4643   else if (is_property_get || is_property_set || is_property_get_all)
4644     {
4645       if (is_property_get)
4646         g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
4647       else if (is_property_set)
4648         g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
4649       else if (is_property_get_all)
4650         g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
4651       else
4652         g_assert_not_reached ();
4653
4654       /* see if the object supports this interface at all */
4655       for (n = 0; n < interfaces->len; n++)
4656         {
4657           const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4658           if (g_strcmp0 (id_n->name, interface_name) == 0)
4659             introspection_data = id_n;
4660         }
4661
4662       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4663        * claims it won't support the interface
4664        */
4665       if (introspection_data == NULL)
4666         {
4667           GDBusMessage *reply;
4668           reply = g_dbus_message_new_method_error (message,
4669                                                    "org.freedesktop.DBus.Error.InvalidArgs",
4670                                                    _("No such interface `%s'"),
4671                                                    interface_name);
4672           g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4673           g_object_unref (reply);
4674           handled = TRUE;
4675           goto out;
4676         }
4677
4678       /* figure out where to dispatch the property get/set/getall calls */
4679       interface_user_data = NULL;
4680       interface_vtable = es->vtable->dispatch (es->connection,
4681                                                sender,
4682                                                es->object_path,
4683                                                interface_name,
4684                                                requested_node,
4685                                                &interface_user_data,
4686                                                es->user_data);
4687       if (interface_vtable == NULL)
4688         goto out;
4689
4690       if (is_property_get || is_property_set)
4691         {
4692           CONNECTION_LOCK (connection);
4693           handled = validate_and_maybe_schedule_property_getset (es->connection,
4694                                                                  message,
4695                                                                  is_property_get,
4696                                                                  introspection_data,
4697                                                                  interface_vtable,
4698                                                                  es->context,
4699                                                                  interface_user_data);
4700           CONNECTION_UNLOCK (connection);
4701         }
4702       else if (is_property_get_all)
4703         {
4704           CONNECTION_LOCK (connection);
4705           handled = validate_and_maybe_schedule_property_get_all (es->connection,
4706                                                                   message,
4707                                                                   introspection_data,
4708                                                                   interface_vtable,
4709                                                                   es->context,
4710                                                                   interface_user_data);
4711           CONNECTION_UNLOCK (connection);
4712         }
4713     }
4714
4715  out:
4716   if (interfaces != NULL)
4717     g_ptr_array_unref (interfaces);
4718   g_strfreev (children);
4719   return handled;
4720 }
4721
4722 typedef struct
4723 {
4724   GDBusMessage *message;
4725   ExportedSubtree *es;
4726 } SubtreeDeferredData;
4727
4728 static void
4729 subtree_deferred_data_free (SubtreeDeferredData *data)
4730 {
4731   g_object_unref (data->message);
4732   g_free (data);
4733 }
4734
4735 /* called without lock held in the thread where the caller registered the subtree */
4736 static gboolean
4737 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4738 {
4739   SubtreeDeferredData *data = _data;
4740   gboolean handled;
4741
4742   handled = FALSE;
4743
4744   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4745       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4746       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4747     handled = handle_subtree_introspect (data->es->connection,
4748                                          data->es,
4749                                          data->message);
4750   else
4751     handled = handle_subtree_method_invocation (data->es->connection,
4752                                                 data->es,
4753                                                 data->message);
4754
4755   if (!handled)
4756     {
4757       CONNECTION_LOCK (data->es->connection);
4758       handled = handle_generic_unlocked (data->es->connection, data->message);
4759       CONNECTION_UNLOCK (data->es->connection);
4760     }
4761
4762   /* if we couldn't handle the request, just bail with the UnknownMethod error */
4763   if (!handled)
4764     {
4765       GDBusMessage *reply;
4766       reply = g_dbus_message_new_method_error (data->message,
4767                                                "org.freedesktop.DBus.Error.UnknownMethod",
4768                                                _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4769                                                g_dbus_message_get_member (data->message),
4770                                                g_dbus_message_get_interface (data->message),
4771                                                g_dbus_message_get_signature (data->message));
4772       g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4773       g_object_unref (reply);
4774     }
4775
4776   return FALSE;
4777 }
4778
4779 /* called in message handler thread with lock held */
4780 static gboolean
4781 subtree_message_func (GDBusConnection *connection,
4782                       ExportedSubtree *es,
4783                       GDBusMessage    *message)
4784 {
4785   GSource *idle_source;
4786   SubtreeDeferredData *data;
4787
4788   data = g_new0 (SubtreeDeferredData, 1);
4789   data->message = g_object_ref (message);
4790   data->es = es;
4791
4792   /* defer this call to an idle handler in the right thread */
4793   idle_source = g_idle_source_new ();
4794   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4795   g_source_set_callback (idle_source,
4796                          process_subtree_vtable_message_in_idle_cb,
4797                          data,
4798                          (GDestroyNotify) subtree_deferred_data_free);
4799   g_source_attach (idle_source, es->context);
4800   g_source_unref (idle_source);
4801
4802   /* since we own the entire subtree, handlers for objects not in the subtree have been
4803    * tried already by libdbus-1 - so we just need to ensure that we're always going
4804    * to reply to the message
4805    */
4806   return TRUE;
4807 }
4808
4809 /**
4810  * g_dbus_connection_register_subtree:
4811  * @connection: A #GDBusConnection.
4812  * @object_path: The object path to register the subtree at.
4813  * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4814  * @flags: Flags used to fine tune the behavior of the subtree.
4815  * @user_data: Data to pass to functions in @vtable.
4816  * @user_data_free_func: Function to call when the subtree is unregistered.
4817  * @error: Return location for error or %NULL.
4818  *
4819  * Registers a whole subtree of <quote>dynamic</quote> objects.
4820  *
4821  * The @enumerate and @introspection functions in @vtable are used to
4822  * convey, to remote callers, what nodes exist in the subtree rooted
4823  * by @object_path.
4824  *
4825  * When handling remote calls into any node in the subtree, first the
4826  * @enumerate function is used to check if the node exists. If the node exists
4827  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4828  * the @introspection function is used to check if the node supports the
4829  * requested method. If so, the @dispatch function is used to determine
4830  * where to dispatch the call. The collected #GDBusInterfaceVTable and
4831  * #gpointer will be used to call into the interface vtable for processing
4832  * the request.
4833  *
4834  * All calls into user-provided code will be invoked in the <link
4835  * linkend="g-main-context-push-thread-default">thread-default main
4836  * loop</link> of the thread you are calling this method from.
4837  *
4838  * If an existing subtree is already registered at @object_path or
4839  * then @error is set to #G_IO_ERROR_EXISTS.
4840  *
4841  * Note that it is valid to register regular objects (using
4842  * g_dbus_connection_register_object()) in a subtree registered with
4843  * g_dbus_connection_register_subtree() - if so, the subtree handler
4844  * is tried as the last resort. One way to think about a subtree
4845  * handler is to consider it a <quote>fallback handler</quote>
4846  * for object paths not registered via g_dbus_connection_register_object()
4847  * or other bindings.
4848  *
4849  * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4850  *
4851  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4852  * that can be used with g_dbus_connection_unregister_subtree() .
4853  *
4854  * Since: 2.26
4855  */
4856 guint
4857 g_dbus_connection_register_subtree (GDBusConnection           *connection,
4858                                     const gchar               *object_path,
4859                                     const GDBusSubtreeVTable  *vtable,
4860                                     GDBusSubtreeFlags          flags,
4861                                     gpointer                   user_data,
4862                                     GDestroyNotify             user_data_free_func,
4863                                     GError                   **error)
4864 {
4865   guint ret;
4866   ExportedSubtree *es;
4867
4868   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4869   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4870   g_return_val_if_fail (vtable != NULL, 0);
4871   g_return_val_if_fail (error == NULL || *error == NULL, 0);
4872
4873   ret = 0;
4874
4875   CONNECTION_LOCK (connection);
4876
4877   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4878   if (es != NULL)
4879     {
4880       g_set_error (error,
4881                    G_IO_ERROR,
4882                    G_IO_ERROR_EXISTS,
4883                    _("A subtree is already exported for %s"),
4884                    object_path);
4885       goto out;
4886     }
4887
4888   es = g_new0 (ExportedSubtree, 1);
4889   es->object_path = g_strdup (object_path);
4890   es->connection = connection;
4891
4892   es->vtable = vtable;
4893   es->flags = flags;
4894   es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4895   es->user_data = user_data;
4896   es->user_data_free_func = user_data_free_func;
4897   es->context = g_main_context_get_thread_default ();
4898   if (es->context != NULL)
4899     g_main_context_ref (es->context);
4900
4901   g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4902   g_hash_table_insert (connection->priv->map_id_to_es,
4903                        GUINT_TO_POINTER (es->id),
4904                        es);
4905
4906   ret = es->id;
4907
4908  out:
4909   CONNECTION_UNLOCK (connection);
4910
4911   return ret;
4912 }
4913
4914 /* ---------------------------------------------------------------------------------------------------- */
4915
4916 /**
4917  * g_dbus_connection_unregister_subtree:
4918  * @connection: A #GDBusConnection.
4919  * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4920  *
4921  * Unregisters a subtree.
4922  *
4923  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4924  *
4925  * Since: 2.26
4926  */
4927 gboolean
4928 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4929                                       guint            registration_id)
4930 {
4931   ExportedSubtree *es;
4932   gboolean ret;
4933
4934   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4935
4936   ret = FALSE;
4937
4938   CONNECTION_LOCK (connection);
4939
4940   es = g_hash_table_lookup (connection->priv->map_id_to_es,
4941                             GUINT_TO_POINTER (registration_id));
4942   if (es == NULL)
4943     goto out;
4944
4945   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4946   g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4947
4948   ret = TRUE;
4949
4950  out:
4951   CONNECTION_UNLOCK (connection);
4952
4953   return ret;
4954 }
4955
4956 /* ---------------------------------------------------------------------------------------------------- */
4957
4958 /* must be called with lock held */
4959 static void
4960 handle_generic_ping_unlocked (GDBusConnection *connection,
4961                               const gchar     *object_path,
4962                               GDBusMessage    *message)
4963 {
4964   GDBusMessage *reply;
4965   reply = g_dbus_message_new_method_reply (message);
4966   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4967   g_object_unref (reply);
4968 }
4969
4970 /* must be called with lock held */
4971 static void
4972 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4973                                         const gchar     *object_path,
4974                                         GDBusMessage    *message)
4975 {
4976   GDBusMessage *reply;
4977
4978   reply = NULL;
4979   if (connection->priv->machine_id == NULL)
4980     {
4981       GError *error;
4982       error = NULL;
4983       /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4984       if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4985                                 &connection->priv->machine_id,
4986                                 NULL,
4987                                 &error))
4988         {
4989           reply = g_dbus_message_new_method_error (message,
4990                                                    "org.freedesktop.DBus.Error.Failed",
4991                                                    _("Unable to load /var/lib/dbus/machine-id: %s"),
4992                                                    error->message);
4993           g_error_free (error);
4994         }
4995       else
4996         {
4997           g_strstrip (connection->priv->machine_id);
4998           /* TODO: validate value */
4999         }
5000     }
5001
5002   if (reply == NULL)
5003     {
5004       reply = g_dbus_message_new_method_reply (message);
5005       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5006     }
5007   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5008   g_object_unref (reply);
5009 }
5010
5011 /* must be called with lock held */
5012 static void
5013 handle_generic_introspect_unlocked (GDBusConnection *connection,
5014                                     const gchar     *object_path,
5015                                     GDBusMessage    *message)
5016 {
5017   guint n;
5018   GString *s;
5019   gchar **registered;
5020   GDBusMessage *reply;
5021
5022   /* first the header */
5023   s = g_string_new (NULL);
5024   introspect_append_header (s);
5025
5026   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5027   for (n = 0; registered != NULL && registered[n] != NULL; n++)
5028       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
5029   g_strfreev (registered);
5030   g_string_append (s, "</node>\n");
5031
5032   reply = g_dbus_message_new_method_reply (message);
5033   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5034   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5035   g_object_unref (reply);
5036   g_string_free (s, TRUE);
5037 }
5038
5039 /* must be called with lock held */
5040 static gboolean
5041 handle_generic_unlocked (GDBusConnection *connection,
5042                          GDBusMessage    *message)
5043 {
5044   gboolean handled;
5045   const gchar *interface_name;
5046   const gchar *member;
5047   const gchar *signature;
5048   const gchar *path;
5049
5050   CONNECTION_ENSURE_LOCK (connection);
5051
5052   handled = FALSE;
5053
5054   interface_name = g_dbus_message_get_interface (message);
5055   member = g_dbus_message_get_member (message);
5056   signature = g_dbus_message_get_signature (message);
5057   path = g_dbus_message_get_path (message);
5058
5059   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5060       g_strcmp0 (member, "Introspect") == 0 &&
5061       g_strcmp0 (signature, "") == 0)
5062     {
5063       handle_generic_introspect_unlocked (connection, path, message);
5064       handled = TRUE;
5065     }
5066   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5067            g_strcmp0 (member, "Ping") == 0 &&
5068            g_strcmp0 (signature, "") == 0)
5069     {
5070       handle_generic_ping_unlocked (connection, path, message);
5071       handled = TRUE;
5072     }
5073   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5074            g_strcmp0 (member, "GetMachineId") == 0 &&
5075            g_strcmp0 (signature, "") == 0)
5076     {
5077       handle_generic_get_machine_id_unlocked (connection, path, message);
5078       handled = TRUE;
5079     }
5080
5081   return handled;
5082 }
5083
5084 /* ---------------------------------------------------------------------------------------------------- */
5085
5086 /* called in message handler thread with lock held */
5087 static void
5088 distribute_method_call (GDBusConnection *connection,
5089                         GDBusMessage    *message)
5090 {
5091   ExportedObject *eo;
5092   ExportedSubtree *es;
5093   const gchar *object_path;
5094   const gchar *interface_name;
5095   const gchar *member;
5096   const gchar *signature;
5097   const gchar *path;
5098   gchar *subtree_path;
5099   gchar *needle;
5100
5101   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5102
5103   interface_name = g_dbus_message_get_interface (message);
5104   member = g_dbus_message_get_member (message);
5105   signature = g_dbus_message_get_signature (message);
5106   path = g_dbus_message_get_path (message);
5107   subtree_path = g_strdup (path);
5108   needle = strrchr (subtree_path, '/');
5109   if (needle != NULL && needle != subtree_path)
5110     {
5111       *needle = '\0';
5112     }
5113   else
5114     {
5115       g_free (subtree_path);
5116       subtree_path = NULL;
5117     }
5118
5119 #if 0
5120   g_debug ("interface    = `%s'", interface_name);
5121   g_debug ("member       = `%s'", member);
5122   g_debug ("signature    = `%s'", signature);
5123   g_debug ("path         = `%s'", path);
5124   g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5125 #endif
5126
5127   object_path = g_dbus_message_get_path (message);
5128   g_assert (object_path != NULL);
5129
5130   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5131   if (eo != NULL)
5132     {
5133       if (obj_message_func (connection, eo, message))
5134         goto out;
5135     }
5136
5137   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5138   if (es != NULL)
5139     {
5140       if (subtree_message_func (connection, es, message))
5141         goto out;
5142     }
5143
5144   if (subtree_path != NULL)
5145     {
5146       es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5147       if (es != NULL)
5148         {
5149           if (subtree_message_func (connection, es, message))
5150             goto out;
5151         }
5152     }
5153
5154   if (handle_generic_unlocked (connection, message))
5155     goto out;
5156
5157   /* if we end up here, the message has not been not handled */
5158
5159  out:
5160   g_free (subtree_path);
5161 }
5162
5163 /* ---------------------------------------------------------------------------------------------------- */
5164
5165 static GDBusConnection **
5166 message_bus_get_singleton (GBusType   bus_type,
5167                            GError   **error)
5168 {
5169   GDBusConnection **ret;
5170   const gchar *starter_bus;
5171
5172   ret = NULL;
5173
5174   switch (bus_type)
5175     {
5176     case G_BUS_TYPE_SESSION:
5177       ret = &the_session_bus;
5178       break;
5179
5180     case G_BUS_TYPE_SYSTEM:
5181       ret = &the_system_bus;
5182       break;
5183
5184     case G_BUS_TYPE_STARTER:
5185       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5186       if (g_strcmp0 (starter_bus, "session") == 0)
5187         {
5188           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5189           goto out;
5190         }
5191       else if (g_strcmp0 (starter_bus, "system") == 0)
5192         {
5193           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5194           goto out;
5195         }
5196       else
5197         {
5198           if (starter_bus != NULL)
5199             {
5200               g_set_error (error,
5201                            G_IO_ERROR,
5202                            G_IO_ERROR_INVALID_ARGUMENT,
5203                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5204                              " - unknown value `%s'"),
5205                            starter_bus);
5206             }
5207           else
5208             {
5209               g_set_error_literal (error,
5210                                    G_IO_ERROR,
5211                                    G_IO_ERROR_INVALID_ARGUMENT,
5212                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5213                                      "variable is not set"));
5214             }
5215         }
5216       break;
5217
5218     default:
5219       g_assert_not_reached ();
5220       break;
5221     }
5222
5223  out:
5224   return ret;
5225 }
5226
5227 static GDBusConnection *
5228 get_uninitialized_connection (GBusType       bus_type,
5229                               GCancellable  *cancellable,
5230                               GError       **error)
5231 {
5232   GDBusConnection **singleton;
5233   GDBusConnection *ret;
5234
5235   ret = NULL;
5236
5237   G_LOCK (message_bus_lock);
5238   singleton = message_bus_get_singleton (bus_type, error);
5239   if (singleton == NULL)
5240     goto out;
5241
5242   if (*singleton == NULL)
5243     {
5244       gchar *address;
5245       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5246       if (address == NULL)
5247         goto out;
5248       ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5249                                        "address", address,
5250                                        "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5251                                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5252                                        "exit-on-close", TRUE,
5253                                        NULL);
5254       g_free (address);
5255     }
5256   else
5257     {
5258       ret = g_object_ref (*singleton);
5259     }
5260
5261   g_assert (ret != NULL);
5262
5263  out:
5264   G_UNLOCK (message_bus_lock);
5265   return ret;
5266 }
5267
5268 /**
5269  * g_bus_get_sync:
5270  * @bus_type: A #GBusType.
5271  * @cancellable: A #GCancellable or %NULL.
5272  * @error: Return location for error or %NULL.
5273  *
5274  * Synchronously connects to the message bus specified by @bus_type.
5275  * Note that the returned object may shared with other callers,
5276  * e.g. if two separate parts of a process calls this function with
5277  * the same @bus_type, they will share the same object.
5278  *
5279  * This is a synchronous failable function. See g_bus_get() and
5280  * g_bus_get_finish() for the asynchronous version.
5281  *
5282  * The returned object is a singleton, that is, shared with other
5283  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5284  * event that you need a private message bus connection, use
5285  * g_dbus_address_get_for_bus_sync() and
5286  * g_dbus_connection_new_for_address().
5287  *
5288  * Note that the returned #GDBusConnection object will (usually) have
5289  * the #GDBusConnection:exit-on-close property set to %TRUE.
5290  *
5291  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5292  *
5293  * Since: 2.26
5294  */
5295 GDBusConnection *
5296 g_bus_get_sync (GBusType       bus_type,
5297                 GCancellable  *cancellable,
5298                 GError       **error)
5299 {
5300   GDBusConnection *connection;
5301
5302   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5303
5304   connection = get_uninitialized_connection (bus_type, cancellable, error);
5305   if (connection == NULL)
5306     goto out;
5307
5308   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5309     {
5310       g_object_unref (connection);
5311       connection = NULL;
5312     }
5313
5314  out:
5315   return connection;
5316 }
5317
5318 static void
5319 bus_get_async_initable_cb (GObject      *source_object,
5320                            GAsyncResult *res,
5321                            gpointer      user_data)
5322 {
5323   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5324   GError *error;
5325
5326   error = NULL;
5327   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5328                                      res,
5329                                      &error))
5330     {
5331       g_assert (error != NULL);
5332       g_simple_async_result_set_from_error (simple, error);
5333       g_error_free (error);
5334       g_object_unref (source_object);
5335     }
5336   else
5337     {
5338       g_simple_async_result_set_op_res_gpointer (simple,
5339                                                  source_object,
5340                                                  g_object_unref);
5341     }
5342   g_simple_async_result_complete_in_idle (simple);
5343   g_object_unref (simple);
5344 }
5345
5346 /**
5347  * g_bus_get:
5348  * @bus_type: A #GBusType.
5349  * @cancellable: A #GCancellable or %NULL.
5350  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5351  * @user_data: The data to pass to @callback.
5352  *
5353  * Asynchronously connects to the message bus specified by @bus_type.
5354  *
5355  * When the operation is finished, @callback will be invoked. You can
5356  * then call g_bus_get_finish() to get the result of the operation.
5357  *
5358  * This is a asynchronous failable function. See g_bus_get_sync() for
5359  * the synchronous version.
5360  *
5361  * Since: 2.26
5362  */
5363 void
5364 g_bus_get (GBusType             bus_type,
5365            GCancellable        *cancellable,
5366            GAsyncReadyCallback  callback,
5367            gpointer             user_data)
5368 {
5369   GDBusConnection *connection;
5370   GSimpleAsyncResult *simple;
5371   GError *error;
5372
5373   simple = g_simple_async_result_new (NULL,
5374                                       callback,
5375                                       user_data,
5376                                       g_bus_get);
5377
5378   error = NULL;
5379   connection = get_uninitialized_connection (bus_type, cancellable, &error);
5380   if (connection == NULL)
5381     {
5382       g_assert (error != NULL);
5383       g_simple_async_result_set_from_error (simple, error);
5384       g_error_free (error);
5385       g_simple_async_result_complete_in_idle (simple);
5386       g_object_unref (simple);
5387     }
5388   else
5389     {
5390       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5391                                    G_PRIORITY_DEFAULT,
5392                                    cancellable,
5393                                    bus_get_async_initable_cb,
5394                                    simple);
5395     }
5396 }
5397
5398 /**
5399  * g_bus_get_finish:
5400  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5401  * @error: Return location for error or %NULL.
5402  *
5403  * Finishes an operation started with g_bus_get().
5404  *
5405  * The returned object is a singleton, that is, shared with other
5406  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5407  * event that you need a private message bus connection, use
5408  * g_dbus_address_get_for_bus() and
5409  * g_dbus_connection_new_for_address().
5410  *
5411  * Note that the returned #GDBusConnection object will (usually) have
5412  * the #GDBusConnection:exit-on-close property set to %TRUE.
5413  *
5414  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5415  *
5416  * Since: 2.26
5417  */
5418 GDBusConnection *
5419 g_bus_get_finish (GAsyncResult  *res,
5420                   GError       **error)
5421 {
5422   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5423   GObject *object;
5424   GDBusConnection *ret;
5425
5426   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5427
5428   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5429
5430   ret = NULL;
5431
5432   if (g_simple_async_result_propagate_error (simple, error))
5433     goto out;
5434
5435   object = g_simple_async_result_get_op_res_gpointer (simple);
5436   g_assert (object != NULL);
5437   ret = g_object_ref (G_DBUS_CONNECTION (object));
5438
5439  out:
5440   return ret;
5441 }
5442
5443 /* ---------------------------------------------------------------------------------------------------- */
5444
5445 #define __G_DBUS_CONNECTION_C__
5446 #include "gioaliasdef.c"