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