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