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