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