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