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