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