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