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