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