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