Microoptimize string reallocations
[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  * The #GDBusConnection type is used for D-Bus connections to remote
109  * peers such as a message buses. It is a low-level API that offers a
110  * lot of flexibility. For instance, it lets you establish a connection
111  * over any transport that can by represented as an #GIOStream.
112  *
113  * This class is rarely used directly in D-Bus clients. If you are writing
114  * an D-Bus client, it is often easier to use the g_bus_own_name(),
115  * g_bus_watch_name() or g_bus_watch_proxy() APIs.
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 const gchar introspect_header[] =
3481   "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3482   "                      \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3483   "<!-- GDBus " PACKAGE_VERSION " -->\n"
3484   "<node>\n";
3485
3486 static const gchar introspect_tail[] =
3487   "</node>\n";
3488
3489 static const gchar introspect_standard_interfaces[] =
3490   "  <interface name=\"org.freedesktop.DBus.Properties\">\n"
3491   "    <method name=\"Get\">\n"
3492   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3493   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3494   "      <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3495   "    </method>\n"
3496   "    <method name=\"GetAll\">\n"
3497   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3498   "      <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3499   "    </method>\n"
3500   "    <method name=\"Set\">\n"
3501   "      <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3502   "      <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3503   "      <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3504   "    </method>\n"
3505   "    <signal name=\"PropertiesChanged\">\n"
3506   "      <arg type=\"s\" name=\"interface_name\"/>\n"
3507   "      <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3508   "    </signal>\n"
3509   "  </interface>\n"
3510   "  <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3511   "    <method name=\"Introspect\">\n"
3512   "      <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3513   "    </method>\n"
3514   "  </interface>\n"
3515   "  <interface name=\"org.freedesktop.DBus.Peer\">\n"
3516   "    <method name=\"Ping\"/>\n"
3517   "    <method name=\"GetMachineId\">\n"
3518   "      <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3519   "    </method>\n"
3520   "  </interface>\n";
3521
3522 static void
3523 introspect_append_header (GString *s)
3524 {
3525   g_string_append (s, introspect_header);
3526 }
3527
3528 static void
3529 introspect_append_standard_interfaces (GString *s)
3530 {
3531   g_string_append (s, introspect_standard_interfaces);
3532 }
3533
3534 static void
3535 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3536 {
3537   if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3538     {
3539       const gchar *begin;
3540       const gchar *end;
3541       gchar *s;
3542
3543       begin = object_path + path_len;
3544       end = strchr (begin, '/');
3545
3546       if (end != NULL)
3547         {
3548           s = g_strndup (begin, end - begin);
3549         }
3550       else
3551         {
3552           s = g_strdup (begin);
3553         }
3554
3555       if (g_hash_table_lookup (set, s) == NULL)
3556         {
3557           g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3558         }
3559       else
3560         {
3561           g_free (s);
3562         }
3563     }
3564 }
3565
3566 /* TODO: we want a nicer public interface for this */
3567 static gchar **
3568 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3569                                             const gchar     *path)
3570 {
3571   GPtrArray *p;
3572   gchar **ret;
3573   GHashTableIter hash_iter;
3574   const gchar *object_path;
3575   gsize path_len;
3576   GHashTable *set;
3577   GList *keys;
3578   GList *l;
3579
3580   CONNECTION_ENSURE_LOCK (connection);
3581
3582   path_len = strlen (path);
3583   if (path_len > 1)
3584     path_len++;
3585
3586   set = g_hash_table_new (g_str_hash, g_str_equal);
3587
3588   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3589   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3590     maybe_add_path (path, path_len, object_path, set);
3591
3592   g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3593   while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3594     maybe_add_path (path, path_len, object_path, set);
3595
3596   p = g_ptr_array_new ();
3597   keys = g_hash_table_get_keys (set);
3598   for (l = keys; l != NULL; l = l->next)
3599     {
3600       g_ptr_array_add (p, l->data);
3601     }
3602   g_hash_table_unref (set);
3603   g_list_free (keys);
3604
3605   g_ptr_array_add (p, NULL);
3606   ret = (gchar **) g_ptr_array_free (p, FALSE);
3607   return ret;
3608 }
3609
3610 static gchar **
3611 g_dbus_connection_list_registered (GDBusConnection *connection,
3612                                    const gchar     *path)
3613 {
3614   gchar **ret;
3615   CONNECTION_LOCK (connection);
3616   ret = g_dbus_connection_list_registered_unlocked (connection, path);
3617   CONNECTION_UNLOCK (connection);
3618   return ret;
3619 }
3620
3621 /* called in message handler thread with lock held */
3622 static gboolean
3623 handle_introspect (GDBusConnection *connection,
3624                    ExportedObject  *eo,
3625                    GDBusMessage    *message)
3626 {
3627   guint n;
3628   GString *s;
3629   GDBusMessage *reply;
3630   GHashTableIter hash_iter;
3631   ExportedInterface *ei;
3632   gchar **registered;
3633
3634   /* first the header with the standard interfaces */
3635   s = g_string_sized_new (sizeof (introspect_header) +
3636                           sizeof (introspect_standard_interfaces) +
3637                           sizeof (introspect_tail));
3638   introspect_append_header (s);
3639   introspect_append_standard_interfaces (s);
3640
3641   /* then include the registered interfaces */
3642   g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3643   while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3644     {
3645       g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3646     }
3647
3648   /* finally include nodes registered below us */
3649   registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3650   for (n = 0; registered != NULL && registered[n] != NULL; n++)
3651     {
3652       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
3653     }
3654   g_strfreev (registered);
3655   g_string_append (s, introspect_tail);
3656
3657   reply = g_dbus_message_new_method_reply (message);
3658   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3659   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3660   g_object_unref (reply);
3661   g_string_free (s, TRUE);
3662
3663   return TRUE;
3664 }
3665
3666 /* called in thread where object was registered - no locks held */
3667 static gboolean
3668 invoke_method_in_idle_cb (gpointer user_data)
3669 {
3670   GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3671   GDBusInterfaceVTable *vtable;
3672
3673   vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3674   g_assert (vtable != NULL && vtable->method_call != NULL);
3675
3676   vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3677                        g_dbus_method_invocation_get_sender (invocation),
3678                        g_dbus_method_invocation_get_object_path (invocation),
3679                        g_dbus_method_invocation_get_interface_name (invocation),
3680                        g_dbus_method_invocation_get_method_name (invocation),
3681                        g_dbus_method_invocation_get_parameters (invocation),
3682                        g_object_ref (invocation),
3683                        g_dbus_method_invocation_get_user_data (invocation));
3684
3685   return FALSE;
3686 }
3687
3688 /* called in message handler thread with lock held */
3689 static gboolean
3690 validate_and_maybe_schedule_method_call (GDBusConnection            *connection,
3691                                          GDBusMessage               *message,
3692                                          const GDBusInterfaceInfo   *introspection_data,
3693                                          const GDBusInterfaceVTable *vtable,
3694                                          GMainContext               *main_context,
3695                                          gpointer                    user_data)
3696 {
3697   GDBusMethodInvocation *invocation;
3698   const GDBusMethodInfo *method_info;
3699   GDBusMessage *reply;
3700   GVariant *parameters;
3701   GSource *idle_source;
3702   gboolean handled;
3703   gchar *in_signature;
3704
3705   handled = FALSE;
3706
3707   /* TODO: the cost of this is O(n) - it might be worth caching the result */
3708   method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3709
3710   /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3711    * error to the caller
3712    */
3713   if (method_info == NULL)
3714     {
3715       reply = g_dbus_message_new_method_error (message,
3716                                                "org.freedesktop.DBus.Error.UnknownMethod",
3717                                                _("No such method `%s'"),
3718                                                g_dbus_message_get_member (message));
3719       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3720       g_object_unref (reply);
3721       handled = TRUE;
3722       goto out;
3723     }
3724
3725   /* Check that the incoming args are of the right type - if they are not, return
3726    * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3727    *
3728    * TODO: might also be worth caching the combined signature.
3729    */
3730   in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3731   if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3732     {
3733       reply = g_dbus_message_new_method_error (message,
3734                                                "org.freedesktop.DBus.Error.InvalidArgs",
3735                                                _("Signature of message, `%s', does not match expected signature `%s'"),
3736                                                g_dbus_message_get_signature (message),
3737                                                in_signature);
3738       g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3739       g_object_unref (reply);
3740       g_free (in_signature);
3741       handled = TRUE;
3742       goto out;
3743     }
3744   g_free (in_signature);
3745
3746   parameters = g_dbus_message_get_body (message);
3747   if (parameters == NULL)
3748     {
3749       parameters = g_variant_new ("()");
3750       g_variant_ref_sink (parameters);
3751     }
3752   else
3753     {
3754       g_variant_ref (parameters);
3755     }
3756
3757   /* schedule the call in idle */
3758   invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3759                                              g_dbus_message_get_path (message),
3760                                              g_dbus_message_get_interface (message),
3761                                              g_dbus_message_get_member (message),
3762                                              method_info,
3763                                              connection,
3764                                              message,
3765                                              parameters,
3766                                              user_data);
3767   g_variant_unref (parameters);
3768   g_object_set_data (G_OBJECT (invocation),
3769                      "g-dbus-interface-vtable",
3770                      (gpointer) vtable);
3771
3772   idle_source = g_idle_source_new ();
3773   g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3774   g_source_set_callback (idle_source,
3775                          invoke_method_in_idle_cb,
3776                          invocation,
3777                          g_object_unref);
3778   g_source_attach (idle_source, main_context);
3779   g_source_unref (idle_source);
3780
3781   handled = TRUE;
3782
3783  out:
3784
3785   return handled;
3786 }
3787
3788 /* ---------------------------------------------------------------------------------------------------- */
3789
3790 /* called in message handler thread with lock held */
3791 static gboolean
3792 obj_message_func (GDBusConnection *connection,
3793                   ExportedObject  *eo,
3794                   GDBusMessage    *message)
3795 {
3796   const gchar *interface_name;
3797   const gchar *member;
3798   const gchar *signature;
3799   gboolean handled;
3800
3801   handled = FALSE;
3802
3803   interface_name = g_dbus_message_get_interface (message);
3804   member = g_dbus_message_get_member (message);
3805   signature = g_dbus_message_get_signature (message);
3806
3807   /* see if we have an interface for handling this call */
3808   if (interface_name != NULL)
3809     {
3810       ExportedInterface *ei;
3811       ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3812       if (ei != NULL)
3813         {
3814           /* we do - invoke the handler in idle in the right thread */
3815
3816           /* handle no vtable or handler being present */
3817           if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3818             goto out;
3819
3820           handled = validate_and_maybe_schedule_method_call (connection,
3821                                                              message,
3822                                                              ei->introspection_data,
3823                                                              ei->vtable,
3824                                                              ei->context,
3825                                                              ei->user_data);
3826           goto out;
3827         }
3828     }
3829
3830   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3831       g_strcmp0 (member, "Introspect") == 0 &&
3832       g_strcmp0 (signature, "") == 0)
3833     {
3834       handled = handle_introspect (connection, eo, message);
3835       goto out;
3836     }
3837   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3838            g_strcmp0 (member, "Get") == 0 &&
3839            g_strcmp0 (signature, "ss") == 0)
3840     {
3841       handled = handle_getset_property (connection, eo, message, TRUE);
3842       goto out;
3843     }
3844   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3845            g_strcmp0 (member, "Set") == 0 &&
3846            g_strcmp0 (signature, "ssv") == 0)
3847     {
3848       handled = handle_getset_property (connection, eo, message, FALSE);
3849       goto out;
3850     }
3851   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3852            g_strcmp0 (member, "GetAll") == 0 &&
3853            g_strcmp0 (signature, "s") == 0)
3854     {
3855       handled = handle_get_all_properties (connection, eo, message);
3856       goto out;
3857     }
3858
3859  out:
3860   return handled;
3861 }
3862
3863 /**
3864  * g_dbus_connection_register_object:
3865  * @connection: A #GDBusConnection.
3866  * @object_path: The object path to register at.
3867  * @interface_name: The D-Bus interface to register.
3868  * @introspection_data: Introspection data for the interface.
3869  * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3870  * @user_data: Data to pass to functions in @vtable.
3871  * @user_data_free_func: Function to call when the object path is unregistered.
3872  * @error: Return location for error or %NULL.
3873  *
3874  * Registers callbacks for exported objects at @object_path with the
3875  * D-Bus interface @interface_name.
3876  *
3877  * Calls to functions in @vtable (and @user_data_free_func) will
3878  * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3879  * loop</link> of the thread you are calling this method from.
3880  *
3881  * Note that all #GVariant values passed to functions in @vtable will match
3882  * the signature given in @introspection_data - if a remote caller passes
3883  * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3884  * is returned to the remote caller.
3885  *
3886  * Additionally, if the remote caller attempts to invoke methods or
3887  * access properties not mentioned in @introspection_data the
3888  * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3889  * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3890  * are returned to the caller.
3891  *
3892  * It is considered a programming error if the
3893  * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3894  * #GVariant of incorrect type.
3895  *
3896  * If an existing callback is already registered at @object_path and
3897  * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3898  *
3899  * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3900  *
3901  * Returns: 0 if @error is set, otherwise a registration id (never 0)
3902  * that can be used with g_dbus_connection_unregister_object() .
3903  *
3904  * Since: 2.26
3905  */
3906 guint
3907 g_dbus_connection_register_object (GDBusConnection            *connection,
3908                                    const gchar                *object_path,
3909                                    const gchar                *interface_name,
3910                                    const GDBusInterfaceInfo   *introspection_data,
3911                                    const GDBusInterfaceVTable *vtable,
3912                                    gpointer                    user_data,
3913                                    GDestroyNotify              user_data_free_func,
3914                                    GError                    **error)
3915 {
3916   ExportedObject *eo;
3917   ExportedInterface *ei;
3918   guint ret;
3919
3920   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3921   g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3922   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3923   g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3924   g_return_val_if_fail (introspection_data != NULL, 0);
3925   g_return_val_if_fail (error == NULL || *error == NULL, 0);
3926
3927   ret = 0;
3928
3929   CONNECTION_LOCK (connection);
3930
3931   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3932   if (eo == NULL)
3933     {
3934       eo = g_new0 (ExportedObject, 1);
3935       eo->object_path = g_strdup (object_path);
3936       eo->connection = connection;
3937       eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3938                                                      g_str_equal,
3939                                                      NULL,
3940                                                      (GDestroyNotify) exported_interface_free);
3941       g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3942     }
3943
3944   ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3945   if (ei != NULL)
3946     {
3947       g_set_error (error,
3948                    G_IO_ERROR,
3949                    G_IO_ERROR_EXISTS,
3950                    _("An object is already exported for the interface %s at %s"),
3951                    interface_name,
3952                    object_path);
3953       goto out;
3954     }
3955
3956   ei = g_new0 (ExportedInterface, 1);
3957   ei->id = _global_registration_id++; /* TODO: overflow etc. */
3958   ei->eo = eo;
3959   ei->user_data = user_data;
3960   ei->user_data_free_func = user_data_free_func;
3961   ei->vtable = vtable;
3962   ei->introspection_data = introspection_data;
3963   ei->interface_name = g_strdup (interface_name);
3964   ei->context = g_main_context_get_thread_default ();
3965   if (ei->context != NULL)
3966     g_main_context_ref (ei->context);
3967
3968   g_hash_table_insert (eo->map_if_name_to_ei,
3969                        (gpointer) ei->interface_name,
3970                        ei);
3971   g_hash_table_insert (connection->priv->map_id_to_ei,
3972                        GUINT_TO_POINTER (ei->id),
3973                        ei);
3974
3975   ret = ei->id;
3976
3977  out:
3978   CONNECTION_UNLOCK (connection);
3979
3980   return ret;
3981 }
3982
3983 /**
3984  * g_dbus_connection_unregister_object:
3985  * @connection: A #GDBusConnection.
3986  * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3987  *
3988  * Unregisters an object.
3989  *
3990  * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3991  *
3992  * Since: 2.26
3993  */
3994 gboolean
3995 g_dbus_connection_unregister_object (GDBusConnection *connection,
3996                                      guint            registration_id)
3997 {
3998   ExportedInterface *ei;
3999   ExportedObject *eo;
4000   gboolean ret;
4001
4002   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4003
4004   ret = FALSE;
4005
4006   CONNECTION_LOCK (connection);
4007
4008   ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4009                             GUINT_TO_POINTER (registration_id));
4010   if (ei == NULL)
4011     {
4012       goto out;
4013     }
4014
4015   eo = ei->eo;
4016
4017   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4018   g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4019   /* unregister object path if we have no more exported interfaces */
4020   if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4021     {
4022       g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4023                                            eo->object_path));
4024     }
4025
4026   ret = TRUE;
4027
4028  out:
4029   CONNECTION_UNLOCK (connection);
4030
4031   return ret;
4032 }
4033
4034 /* ---------------------------------------------------------------------------------------------------- */
4035
4036 /**
4037  * g_dbus_connection_emit_signal:
4038  * @connection: A #GDBusConnection.
4039  * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4040  * @object_path: Path of remote object.
4041  * @interface_name: D-Bus interface to emit a signal on.
4042  * @signal_name: The name of the signal to emit.
4043  * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4044  * @error: Return location for error or %NULL.
4045  *
4046  * Emits a signal.
4047  *
4048  * This can only fail if @parameters is not compatible with the D-Bus protocol.
4049  *
4050  * Returns: %TRUE unless @error is set.
4051  *
4052  * Since: 2.26
4053  */
4054 gboolean
4055 g_dbus_connection_emit_signal (GDBusConnection    *connection,
4056                                const gchar        *destination_bus_name,
4057                                const gchar        *object_path,
4058                                const gchar        *interface_name,
4059                                const gchar        *signal_name,
4060                                GVariant           *parameters,
4061                                GError            **error)
4062 {
4063   GDBusMessage *message;
4064   gboolean ret;
4065
4066   message = NULL;
4067   ret = FALSE;
4068
4069   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4070   g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4071   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4072   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4073   g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4074   g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4075
4076   message = g_dbus_message_new_signal (object_path,
4077                                        interface_name,
4078                                        signal_name);
4079
4080   if (destination_bus_name != NULL)
4081     {
4082       g_dbus_message_set_header (message,
4083                                  G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4084                                  g_variant_new_string (destination_bus_name));
4085     }
4086
4087   if (parameters != NULL)
4088     g_dbus_message_set_body (message, parameters);
4089
4090   ret = g_dbus_connection_send_message (connection, message, NULL, error);
4091   g_object_unref (message);
4092
4093   return ret;
4094 }
4095
4096 static void
4097 add_invoke_method_flags (GDBusMessage *message,
4098                          GDBusInvokeMethodFlags flags)
4099 {
4100   if (flags & G_DBUS_INVOKE_METHOD_FLAGS_NO_AUTO_START)
4101     g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4102 }
4103
4104 /**
4105  * g_dbus_connection_invoke_method:
4106  * @connection: A #GDBusConnection.
4107  * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4108  * @object_path: Path of remote object.
4109  * @interface_name: D-Bus interface to invoke method on.
4110  * @method_name: The name of the method to invoke.
4111  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4112  * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4113  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4114  * @cancellable: A #GCancellable or %NULL.
4115  * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4116  * care about the result of the method invocation.
4117  * @user_data: The data to pass to @callback.
4118  *
4119  * Asynchronously invokes the @method_name method on the
4120  * @interface_name D-Bus interface on the remote object at
4121  * @object_path owned by @bus_name.
4122  *
4123  * If @connection is closed then the operation will fail with
4124  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4125  * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4126  * not compatible with the D-Bus protocol, the operation fails with
4127  * %G_IO_ERROR_INVALID_ARGUMENT.
4128  *
4129  * This is an asynchronous method. When the operation is finished, @callback will be invoked
4130  * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4131  * of the thread you are calling this method from. You can then call
4132  * g_dbus_connection_invoke_method_finish() to get the result of the operation.
4133  * See g_dbus_connection_invoke_method_sync() for the synchronous version of this
4134  * function.
4135  *
4136  * Since: 2.26
4137  */
4138 void
4139 g_dbus_connection_invoke_method (GDBusConnection       *connection,
4140                                  const gchar           *bus_name,
4141                                  const gchar           *object_path,
4142                                  const gchar           *interface_name,
4143                                  const gchar           *method_name,
4144                                  GVariant              *parameters,
4145                                  GDBusInvokeMethodFlags flags,
4146                                  gint                   timeout_msec,
4147                                  GCancellable          *cancellable,
4148                                  GAsyncReadyCallback    callback,
4149                                  gpointer               user_data)
4150 {
4151   GDBusMessage *message;
4152
4153   g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4154   g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4155   g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4156   g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4157   g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4158   g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4159   g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4160
4161   message = g_dbus_message_new_method_call (bus_name,
4162                                             object_path,
4163                                             interface_name,
4164                                             method_name);
4165   add_invoke_method_flags (message, flags);
4166   if (parameters != NULL)
4167     g_dbus_message_set_body (message, parameters);
4168
4169   g_dbus_connection_send_message_with_reply (connection,
4170                                              message,
4171                                              timeout_msec,
4172                                              NULL, /* volatile guint32 *out_serial */
4173                                              cancellable,
4174                                              callback,
4175                                              user_data);
4176
4177    if (message != NULL)
4178     g_object_unref (message);
4179 }
4180
4181 static GVariant *
4182 decode_method_reply (GDBusMessage *reply, GError **error)
4183 {
4184   GVariant *result;
4185
4186   result = NULL;
4187   switch (g_dbus_message_get_message_type (reply))
4188     {
4189     case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4190       result = g_dbus_message_get_body (reply);
4191       if (result == NULL)
4192         {
4193           result = g_variant_new ("()");
4194           g_variant_ref_sink (result);
4195         }
4196       else
4197         {
4198           g_variant_ref (result);
4199         }
4200       break;
4201     case G_DBUS_MESSAGE_TYPE_ERROR:
4202       g_dbus_message_to_gerror (reply, error);
4203       break;
4204
4205     default:
4206       g_assert_not_reached ();
4207       break;
4208     }
4209
4210   return result;
4211 }
4212
4213 /**
4214  * g_dbus_connection_invoke_method_finish:
4215  * @connection: A #GDBusConnection.
4216  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_invoke_method().
4217  * @error: Return location for error or %NULL.
4218  *
4219  * Finishes an operation started with g_dbus_connection_invoke_method().
4220  *
4221  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4222  * return values. Free with g_variant_unref().
4223  *
4224  * Since: 2.26
4225  */
4226 GVariant *
4227 g_dbus_connection_invoke_method_finish (GDBusConnection    *connection,
4228                                         GAsyncResult       *res,
4229                                         GError            **error)
4230 {
4231   GDBusMessage *reply;
4232   GVariant *result;
4233
4234   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4235   g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4236   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4237
4238   result = NULL;
4239
4240   reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4241   if (reply == NULL)
4242     goto out;
4243
4244   result = decode_method_reply (reply, error);
4245
4246   g_object_unref (reply);
4247
4248  out:
4249   return result;
4250 }
4251
4252 /* ---------------------------------------------------------------------------------------------------- */
4253
4254 /**
4255  * g_dbus_connection_invoke_method_sync:
4256  * @connection: A #GDBusConnection.
4257  * @bus_name: A unique or well-known bus name.
4258  * @object_path: Path of remote object.
4259  * @interface_name: D-Bus interface to invoke method on.
4260  * @method_name: The name of the method to invoke.
4261  * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4262  * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4263  * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4264  * @cancellable: A #GCancellable or %NULL.
4265  * @error: Return location for error or %NULL.
4266  *
4267  * Synchronously invokes the @method_name method on the
4268  * @interface_name D-Bus interface on the remote object at
4269  * @object_path owned by @bus_name.
4270  *
4271  * If @connection is closed then the operation will fail with
4272  * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4273  * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4274  * contains a value not compatible with the D-Bus protocol, the operation
4275  * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4276  *
4277  * The calling thread is blocked until a reply is received. See
4278  * g_dbus_connection_invoke_method() for the asynchronous version of
4279  * this method.
4280  *
4281  * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4282  * return values. Free with g_variant_unref().
4283  *
4284  * Since: 2.26
4285  */
4286 GVariant *
4287 g_dbus_connection_invoke_method_sync (GDBusConnection       *connection,
4288                                       const gchar           *bus_name,
4289                                       const gchar           *object_path,
4290                                       const gchar           *interface_name,
4291                                       const gchar           *method_name,
4292                                       GVariant              *parameters,
4293                                       GDBusInvokeMethodFlags flags,
4294                                       gint                   timeout_msec,
4295                                       GCancellable          *cancellable,
4296                                       GError               **error)
4297 {
4298   GDBusMessage *message;
4299   GDBusMessage *reply;
4300   GVariant *result;
4301
4302   message = NULL;
4303   reply = NULL;
4304   result = NULL;
4305
4306   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4307   g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4308   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4309   g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4310   g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4311   g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4312   g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4313
4314   message = g_dbus_message_new_method_call (bus_name,
4315                                             object_path,
4316                                             interface_name,
4317                                             method_name);
4318   add_invoke_method_flags (message, flags);
4319   if (parameters != NULL)
4320     g_dbus_message_set_body (message, parameters);
4321
4322   reply = g_dbus_connection_send_message_with_reply_sync (connection,
4323                                                           message,
4324                                                           timeout_msec,
4325                                                           NULL, /* volatile guint32 *out_serial */
4326                                                           cancellable,
4327                                                           error);
4328
4329   if (reply == NULL)
4330     goto out;
4331
4332   result = decode_method_reply (reply, error);
4333
4334  out:
4335   if (message != NULL)
4336     g_object_unref (message);
4337   if (reply != NULL)
4338     g_object_unref (reply);
4339
4340   return result;
4341 }
4342
4343 /* ---------------------------------------------------------------------------------------------------- */
4344
4345 struct ExportedSubtree
4346 {
4347   guint                     id;
4348   gchar                    *object_path;
4349   GDBusConnection          *connection;
4350   const GDBusSubtreeVTable *vtable;
4351   GDBusSubtreeFlags         flags;
4352
4353   GMainContext             *context;
4354   gpointer                  user_data;
4355   GDestroyNotify            user_data_free_func;
4356 };
4357
4358 static void
4359 exported_subtree_free (ExportedSubtree *es)
4360 {
4361   if (es->user_data_free_func != NULL)
4362     {
4363       /* TODO: push to thread-default mainloop */
4364       es->user_data_free_func (es->user_data);
4365     }
4366   if (es->context != NULL)
4367     {
4368       g_main_context_unref (es->context);
4369     }
4370   g_free (es->object_path);
4371   g_free (es);
4372 }
4373
4374 /* called without lock held */
4375 static gboolean
4376 handle_subtree_introspect (GDBusConnection  *connection,
4377                            ExportedSubtree  *es,
4378                            GDBusMessage     *message)
4379 {
4380   GString *s;
4381   gboolean handled;
4382   GDBusMessage *reply;
4383   gchar **children;
4384   gboolean is_root;
4385   const gchar *sender;
4386   const gchar *requested_object_path;
4387   const gchar *requested_node;
4388   GPtrArray *interfaces;
4389   guint n;
4390   gchar **subnode_paths;
4391
4392   handled = FALSE;
4393
4394   requested_object_path = g_dbus_message_get_path (message);
4395   sender = g_dbus_message_get_sender (message);
4396   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4397
4398   s = g_string_new (NULL);
4399   introspect_append_header (s);
4400
4401   /* Strictly we don't need the children in dynamic mode, but we avoid the
4402    * conditionals to preserve code clarity
4403    */
4404   children = es->vtable->enumerate (es->connection,
4405                                     sender,
4406                                     es->object_path,
4407                                     es->user_data);
4408
4409   if (!is_root)
4410     {
4411       requested_node = strrchr (requested_object_path, '/') + 1;
4412
4413       /* Assert existence of object if we are not dynamic */
4414       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4415           !_g_strv_has_string ((const gchar * const *) children, requested_node))
4416         goto out;
4417     }
4418   else
4419     {
4420       requested_node = "/";
4421     }
4422
4423   interfaces = es->vtable->introspect (es->connection,
4424                                        sender,
4425                                        es->object_path,
4426                                        requested_node,
4427                                        es->user_data);
4428   if (interfaces != NULL)
4429     {
4430       if (interfaces->len > 0)
4431         {
4432           /* we're in business */
4433           introspect_append_standard_interfaces (s);
4434
4435           for (n = 0; n < interfaces->len; n++)
4436             {
4437               const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4438               g_dbus_interface_info_generate_xml (interface_info, 2, s);
4439             }
4440         }
4441       g_ptr_array_unref (interfaces);
4442     }
4443
4444   /* then include <node> entries from the Subtree for the root */
4445   if (is_root)
4446     {
4447       for (n = 0; children != NULL && children[n] != NULL; n++)
4448         {
4449           g_string_append_printf (s, "  <node name=\"%s\"/>\n", children[n]);
4450         }
4451     }
4452
4453   /* finally include nodes registered below us */
4454   subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4455   for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4456     {
4457       g_string_append_printf (s, "  <node name=\"%s\"/>\n", subnode_paths[n]);
4458     }
4459   g_strfreev (subnode_paths);
4460
4461   g_string_append (s, "</node>\n");
4462
4463   reply = g_dbus_message_new_method_reply (message);
4464   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4465   g_dbus_connection_send_message (connection, reply, NULL, NULL);
4466   g_object_unref (reply);
4467
4468   handled = TRUE;
4469
4470  out:
4471   g_string_free (s, TRUE);
4472   g_strfreev (children);
4473   return handled;
4474 }
4475
4476 /* called without lock held */
4477 static gboolean
4478 handle_subtree_method_invocation (GDBusConnection  *connection,
4479                                   ExportedSubtree  *es,
4480                                   GDBusMessage     *message)
4481 {
4482   gboolean handled;;
4483   const gchar *sender;
4484   const gchar *interface_name;
4485   const gchar *member;
4486   const gchar *signature;
4487   const gchar *requested_object_path;
4488   const gchar *requested_node;
4489   gboolean is_root;
4490   gchar **children;
4491   const GDBusInterfaceInfo *introspection_data;
4492   const GDBusInterfaceVTable *interface_vtable;
4493   gpointer interface_user_data;
4494   guint n;
4495   GPtrArray *interfaces;
4496   gboolean is_property_get;
4497   gboolean is_property_set;
4498   gboolean is_property_get_all;
4499
4500   handled = FALSE;
4501   interfaces = NULL;
4502
4503   requested_object_path = g_dbus_message_get_path (message);
4504   sender = g_dbus_message_get_sender (message);
4505   interface_name = g_dbus_message_get_interface (message);
4506   member = g_dbus_message_get_member (message);
4507   signature = g_dbus_message_get_signature (message);
4508   is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4509
4510   is_property_get = FALSE;
4511   is_property_set = FALSE;
4512   is_property_get_all = FALSE;
4513   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4514     {
4515       if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4516         {
4517           is_property_get = TRUE;
4518         }
4519       else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4520         {
4521           is_property_set = TRUE;
4522         }
4523       else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4524         {
4525           is_property_get_all = TRUE;
4526         }
4527     }
4528
4529   children = es->vtable->enumerate (es->connection,
4530                                     sender,
4531                                     es->object_path,
4532                                     es->user_data);
4533
4534   if (!is_root)
4535     {
4536       requested_node = strrchr (requested_object_path, '/') + 1;
4537
4538       /* If not dynamic, skip if requested node is not part of children */
4539       if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4540           !_g_strv_has_string ((const gchar * const *) children, requested_node))
4541         goto out;
4542     }
4543   else
4544     {
4545       requested_node = "/";
4546     }
4547
4548   /* get introspection data for the node */
4549   interfaces = es->vtable->introspect (es->connection,
4550                                        sender,
4551                                        requested_object_path,
4552                                        requested_node,
4553                                        es->user_data);
4554   g_assert (interfaces != NULL);
4555   introspection_data = NULL;
4556   for (n = 0; n < interfaces->len; n++)
4557     {
4558       const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4559       if (g_strcmp0 (id_n->name, interface_name) == 0)
4560         {
4561           introspection_data = id_n;
4562         }
4563     }
4564
4565   /* dispatch the call if the user wants to handle it */
4566   if (introspection_data != NULL)
4567     {
4568       /* figure out where to dispatch the method call */
4569       interface_user_data = NULL;
4570       interface_vtable = es->vtable->dispatch (es->connection,
4571                                                sender,
4572                                                es->object_path,
4573                                                interface_name,
4574                                                requested_node,
4575                                                &interface_user_data,
4576                                                es->user_data);
4577       if (interface_vtable == NULL)
4578         goto out;
4579
4580       CONNECTION_LOCK (connection);
4581       handled = validate_and_maybe_schedule_method_call (es->connection,
4582                                                          message,
4583                                                          introspection_data,
4584                                                          interface_vtable,
4585                                                          es->context,
4586                                                          interface_user_data);
4587       CONNECTION_UNLOCK (connection);
4588     }
4589   /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4590   else if (is_property_get || is_property_set || is_property_get_all)
4591     {
4592       if (is_property_get)
4593         g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4594       else if (is_property_set)
4595         g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4596       else if (is_property_get_all)
4597         g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4598       else
4599         g_assert_not_reached ();
4600
4601       /* see if the object supports this interface at all */
4602       for (n = 0; n < interfaces->len; n++)
4603         {
4604           const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4605           if (g_strcmp0 (id_n->name, interface_name) == 0)
4606             {
4607               introspection_data = id_n;
4608             }
4609         }
4610
4611       /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4612        * claims it won't support the interface
4613        */
4614       if (introspection_data == NULL)
4615         {
4616           GDBusMessage *reply;
4617           reply = g_dbus_message_new_method_error (message,
4618                                                    "org.freedesktop.DBus.Error.InvalidArgs",
4619                                                    _("No such interface `%s'"),
4620                                                    interface_name);
4621           g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4622           g_object_unref (reply);
4623           handled = TRUE;
4624           goto out;
4625         }
4626
4627       /* figure out where to dispatch the property get/set/getall calls */
4628       interface_user_data = NULL;
4629       interface_vtable = es->vtable->dispatch (es->connection,
4630                                                sender,
4631                                                es->object_path,
4632                                                interface_name,
4633                                                requested_node,
4634                                                &interface_user_data,
4635                                                es->user_data);
4636       if (interface_vtable == NULL)
4637         goto out;
4638
4639       if (is_property_get || is_property_set)
4640         {
4641           CONNECTION_LOCK (connection);
4642           handled = validate_and_maybe_schedule_property_getset (es->connection,
4643                                                                  message,
4644                                                                  is_property_get,
4645                                                                  introspection_data,
4646                                                                  interface_vtable,
4647                                                                  es->context,
4648                                                                  interface_user_data);
4649           CONNECTION_UNLOCK (connection);
4650         }
4651       else if (is_property_get_all)
4652         {
4653           CONNECTION_LOCK (connection);
4654           handled = validate_and_maybe_schedule_property_get_all (es->connection,
4655                                                                   message,
4656                                                                   introspection_data,
4657                                                                   interface_vtable,
4658                                                                   es->context,
4659                                                                   interface_user_data);
4660           CONNECTION_UNLOCK (connection);
4661         }
4662     }
4663
4664  out:
4665   if (interfaces != NULL)
4666     g_ptr_array_unref (interfaces);
4667   g_strfreev (children);
4668   return handled;
4669 }
4670
4671 typedef struct
4672 {
4673   GDBusMessage *message;
4674   ExportedSubtree *es;
4675 } SubtreeDeferredData;
4676
4677 static void
4678 subtree_deferred_data_free (SubtreeDeferredData *data)
4679 {
4680   g_object_unref (data->message);
4681   g_free (data);
4682 }
4683
4684 /* called without lock held in the thread where the caller registered the subtree */
4685 static gboolean
4686 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4687 {
4688   SubtreeDeferredData *data = _data;
4689   gboolean handled;
4690
4691   handled = FALSE;
4692
4693   if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4694       g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4695       g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4696     {
4697       handled = handle_subtree_introspect (data->es->connection,
4698                                            data->es,
4699                                            data->message);
4700     }
4701   else
4702     {
4703       handled = handle_subtree_method_invocation (data->es->connection,
4704                                                   data->es,
4705                                                   data->message);
4706     }
4707
4708
4709   if (!handled)
4710     {
4711       CONNECTION_LOCK (data->es->connection);
4712       handled = handle_generic_unlocked (data->es->connection, data->message);
4713       CONNECTION_UNLOCK (data->es->connection);
4714     }
4715
4716   /* if we couldn't handle the request, just bail with the UnknownMethod error */
4717   if (!handled)
4718     {
4719       GDBusMessage *reply;
4720       reply = g_dbus_message_new_method_error (data->message,
4721                                                "org.freedesktop.DBus.Error.UnknownMethod",
4722                                                _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4723                                                g_dbus_message_get_member (data->message),
4724                                                g_dbus_message_get_interface (data->message),
4725                                                g_dbus_message_get_signature (data->message));
4726       g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4727       g_object_unref (reply);
4728     }
4729
4730   return FALSE;
4731 }
4732
4733 /* called in message handler thread with lock held */
4734 static gboolean
4735 subtree_message_func (GDBusConnection *connection,
4736                       ExportedSubtree *es,
4737                       GDBusMessage    *message)
4738 {
4739   GSource *idle_source;
4740   SubtreeDeferredData *data;
4741
4742   data = g_new0 (SubtreeDeferredData, 1);
4743   data->message = g_object_ref (message);
4744   data->es = es;
4745
4746   /* defer this call to an idle handler in the right thread */
4747   idle_source = g_idle_source_new ();
4748   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4749   g_source_set_callback (idle_source,
4750                          process_subtree_vtable_message_in_idle_cb,
4751                          data,
4752                          (GDestroyNotify) subtree_deferred_data_free);
4753   g_source_attach (idle_source, es->context);
4754   g_source_unref (idle_source);
4755
4756   /* since we own the entire subtree, handlers for objects not in the subtree have been
4757    * tried already by libdbus-1 - so we just need to ensure that we're always going
4758    * to reply to the message
4759    */
4760   return TRUE;
4761 }
4762
4763 /**
4764  * g_dbus_connection_register_subtree:
4765  * @connection: A #GDBusConnection.
4766  * @object_path: The object path to register the subtree at.
4767  * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4768  * @flags: Flags used to fine tune the behavior of the subtree.
4769  * @user_data: Data to pass to functions in @vtable.
4770  * @user_data_free_func: Function to call when the subtree is unregistered.
4771  * @error: Return location for error or %NULL.
4772  *
4773  * Registers a whole subtree of <quote>dynamic</quote> objects.
4774  *
4775  * The @enumerate and @introspection functions in @vtable are used to
4776  * convey, to remote callers, what nodes exist in the subtree rooted
4777  * by @object_path.
4778  *
4779  * When handling remote calls into any node in the subtree, first the
4780  * @enumerate function is used to check if the node exists. If the node exists
4781  * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4782  * the @introspection function is used to check if the node supports the
4783  * requested method. If so, the @dispatch function is used to determine
4784  * where to dispatch the call. The collected #GDBusInterfaceVTable and
4785  * #gpointer will be used to call into the interface vtable for processing
4786  * the request.
4787  *
4788  * All calls into user-provided code will be invoked in the <link
4789  * linkend="g-main-context-push-thread-default">thread-default main
4790  * loop</link> of the thread you are calling this method from.
4791  *
4792  * If an existing subtree is already registered at @object_path or
4793  * then @error is set to #G_IO_ERROR_EXISTS.
4794  *
4795  * Note that it is valid to register regular objects (using
4796  * g_dbus_connection_register_object()) in a subtree registered with
4797  * g_dbus_connection_register_subtree() - if so, the subtree handler
4798  * is tried as the last resort. One way to think about a subtree
4799  * handler is to consider it a <quote>fallback handler</quote>
4800  * for object paths not registered via g_dbus_connection_register_object()
4801  * or other bindings.
4802  *
4803  * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4804  *
4805  * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4806  * that can be used with g_dbus_connection_unregister_subtree() .
4807  *
4808  * Since: 2.26
4809  */
4810 guint
4811 g_dbus_connection_register_subtree (GDBusConnection            *connection,
4812                                     const gchar                *object_path,
4813                                     const GDBusSubtreeVTable   *vtable,
4814                                     GDBusSubtreeFlags           flags,
4815                                     gpointer                    user_data,
4816                                     GDestroyNotify              user_data_free_func,
4817                                     GError                    **error)
4818 {
4819   guint ret;
4820   ExportedSubtree *es;
4821
4822   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4823   g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4824   g_return_val_if_fail (vtable != NULL, 0);
4825   g_return_val_if_fail (error == NULL || *error == NULL, 0);
4826
4827   ret = 0;
4828
4829   CONNECTION_LOCK (connection);
4830
4831   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4832   if (es != NULL)
4833     {
4834       g_set_error (error,
4835                    G_IO_ERROR,
4836                    G_IO_ERROR_EXISTS,
4837                    _("A subtree is already exported for %s"),
4838                    object_path);
4839       goto out;
4840     }
4841
4842   es = g_new0 (ExportedSubtree, 1);
4843   es->object_path = g_strdup (object_path);
4844   es->connection = connection;
4845
4846   es->vtable = vtable;
4847   es->flags = flags;
4848   es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4849   es->user_data = user_data;
4850   es->user_data_free_func = user_data_free_func;
4851   es->context = g_main_context_get_thread_default ();
4852   if (es->context != NULL)
4853     g_main_context_ref (es->context);
4854
4855   g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4856   g_hash_table_insert (connection->priv->map_id_to_es,
4857                        GUINT_TO_POINTER (es->id),
4858                        es);
4859
4860   ret = es->id;
4861
4862  out:
4863   CONNECTION_UNLOCK (connection);
4864
4865   return ret;
4866 }
4867
4868 /* ---------------------------------------------------------------------------------------------------- */
4869
4870 /**
4871  * g_dbus_connection_unregister_subtree:
4872  * @connection: A #GDBusConnection.
4873  * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4874  *
4875  * Unregisters a subtree.
4876  *
4877  * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4878  *
4879  * Since: 2.26
4880  */
4881 gboolean
4882 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4883                                       guint            registration_id)
4884 {
4885   ExportedSubtree *es;
4886   gboolean ret;
4887
4888   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4889
4890   ret = FALSE;
4891
4892   CONNECTION_LOCK (connection);
4893
4894   es = g_hash_table_lookup (connection->priv->map_id_to_es,
4895                             GUINT_TO_POINTER (registration_id));
4896   if (es == NULL)
4897     {
4898       goto out;
4899     }
4900
4901   g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4902   g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4903
4904   ret = TRUE;
4905
4906  out:
4907   CONNECTION_UNLOCK (connection);
4908
4909   return ret;
4910 }
4911
4912 /* ---------------------------------------------------------------------------------------------------- */
4913
4914 /* must be called with lock held */
4915 static void
4916 handle_generic_ping_unlocked (GDBusConnection  *connection,
4917                               const gchar      *object_path,
4918                               GDBusMessage     *message)
4919 {
4920   GDBusMessage *reply;
4921   reply = g_dbus_message_new_method_reply (message);
4922   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4923   g_object_unref (reply);
4924 }
4925
4926 /* must be called with lock held */
4927 static void
4928 handle_generic_get_machine_id_unlocked (GDBusConnection  *connection,
4929                                         const gchar      *object_path,
4930                                         GDBusMessage     *message)
4931 {
4932   GDBusMessage *reply;
4933
4934   reply = NULL;
4935   if (connection->priv->machine_id == NULL)
4936     {
4937       GError *error;
4938       error = NULL;
4939       /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4940       if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4941                                 &connection->priv->machine_id,
4942                                 NULL,
4943                                 &error))
4944         {
4945           reply = g_dbus_message_new_method_error (message,
4946                                                    "org.freedesktop.DBus.Error.Failed",
4947                                                    _("Unable to load /var/lib/dbus/machine-id: %s"),
4948                                                    error->message);
4949           g_error_free (error);
4950         }
4951       else
4952         {
4953           g_strstrip (connection->priv->machine_id);
4954           /* TODO: validate value */
4955         }
4956     }
4957
4958   if (reply == NULL)
4959     {
4960       reply = g_dbus_message_new_method_reply (message);
4961       g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4962     }
4963   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4964   g_object_unref (reply);
4965 }
4966
4967 /* must be called with lock held */
4968 static void
4969 handle_generic_introspect_unlocked (GDBusConnection  *connection,
4970                                     const gchar      *object_path,
4971                                     GDBusMessage     *message)
4972 {
4973   guint n;
4974   GString *s;
4975   gchar **registered;
4976   GDBusMessage *reply;
4977
4978   /* first the header */
4979   s = g_string_new (NULL);
4980   introspect_append_header (s);
4981
4982   registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4983   for (n = 0; registered != NULL && registered[n] != NULL; n++)
4984     {
4985       g_string_append_printf (s, "  <node name=\"%s\"/>\n", registered[n]);
4986     }
4987   g_strfreev (registered);
4988   g_string_append (s, "</node>\n");
4989
4990   reply = g_dbus_message_new_method_reply (message);
4991   g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4992   g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4993   g_object_unref (reply);
4994   g_string_free (s, TRUE);
4995 }
4996
4997 /* must be called with lock held */
4998 static gboolean
4999 handle_generic_unlocked (GDBusConnection *connection,
5000                          GDBusMessage    *message)
5001 {
5002   gboolean handled;
5003   const gchar *interface_name;
5004   const gchar *member;
5005   const gchar *signature;
5006   const gchar *path;
5007
5008   CONNECTION_ENSURE_LOCK (connection);
5009
5010   handled = FALSE;
5011
5012   interface_name = g_dbus_message_get_interface (message);
5013   member = g_dbus_message_get_member (message);
5014   signature = g_dbus_message_get_signature (message);
5015   path = g_dbus_message_get_path (message);
5016
5017   if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5018       g_strcmp0 (member, "Introspect") == 0 &&
5019       g_strcmp0 (signature, "") == 0)
5020     {
5021       handle_generic_introspect_unlocked (connection, path, message);
5022       handled = TRUE;
5023     }
5024   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5025            g_strcmp0 (member, "Ping") == 0 &&
5026            g_strcmp0 (signature, "") == 0)
5027     {
5028       handle_generic_ping_unlocked (connection, path, message);
5029       handled = TRUE;
5030     }
5031   else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5032            g_strcmp0 (member, "GetMachineId") == 0 &&
5033            g_strcmp0 (signature, "") == 0)
5034     {
5035       handle_generic_get_machine_id_unlocked (connection, path, message);
5036       handled = TRUE;
5037     }
5038
5039   return handled;
5040 }
5041
5042 /* ---------------------------------------------------------------------------------------------------- */
5043
5044 /* called in message handler thread with lock held */
5045 static void
5046 distribute_method_call (GDBusConnection  *connection,
5047                         GDBusMessage     *message)
5048 {
5049   ExportedObject *eo;
5050   ExportedSubtree *es;
5051   const gchar *object_path;
5052   const gchar *interface_name;
5053   const gchar *member;
5054   const gchar *signature;
5055   const gchar *path;
5056   gchar *subtree_path;
5057   gchar *needle;
5058
5059   g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5060
5061   interface_name = g_dbus_message_get_interface (message);
5062   member = g_dbus_message_get_member (message);
5063   signature = g_dbus_message_get_signature (message);
5064   path = g_dbus_message_get_path (message);
5065   subtree_path = g_strdup (path);
5066   needle = strrchr (subtree_path, '/');
5067   if (needle != NULL && needle != subtree_path)
5068     {
5069       *needle = '\0';
5070     }
5071   else
5072     {
5073       g_free (subtree_path);
5074       subtree_path = NULL;
5075     }
5076
5077 #if 0
5078   g_debug ("interface    = `%s'", interface_name);
5079   g_debug ("member       = `%s'", member);
5080   g_debug ("signature    = `%s'", signature);
5081   g_debug ("path         = `%s'", path);
5082   g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5083 #endif
5084
5085   object_path = g_dbus_message_get_path (message);
5086   g_assert (object_path != NULL);
5087
5088   eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5089   if (eo != NULL)
5090     {
5091       if (obj_message_func (connection, eo, message))
5092         goto out;
5093     }
5094
5095   es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5096   if (es != NULL)
5097     {
5098       if (subtree_message_func (connection, es, message))
5099         goto out;
5100     }
5101
5102   if (subtree_path != NULL)
5103     {
5104       es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5105       if (es != NULL)
5106         {
5107           if (subtree_message_func (connection, es, message))
5108             goto out;
5109         }
5110     }
5111
5112   if (handle_generic_unlocked (connection, message))
5113     goto out;
5114
5115   /* if we end up here, the message has not been not handled */
5116
5117  out:
5118   g_free (subtree_path);
5119 }
5120
5121 /* ---------------------------------------------------------------------------------------------------- */
5122
5123 static GDBusConnection **
5124 message_bus_get_singleton (GBusType   bus_type,
5125                            GError   **error)
5126 {
5127   GDBusConnection **ret;
5128   const gchar *starter_bus;
5129
5130   ret = NULL;
5131
5132   switch (bus_type)
5133     {
5134     default:
5135       g_assert_not_reached ();
5136       break;
5137
5138     case G_BUS_TYPE_SESSION:
5139       ret = &the_session_bus;
5140       break;
5141
5142     case G_BUS_TYPE_SYSTEM:
5143       ret = &the_system_bus;
5144       break;
5145
5146     case G_BUS_TYPE_STARTER:
5147       starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5148       if (g_strcmp0 (starter_bus, "session") == 0)
5149         {
5150           ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5151           goto out;
5152         }
5153       else if (g_strcmp0 (starter_bus, "system") == 0)
5154         {
5155           ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5156           goto out;
5157         }
5158       else
5159         {
5160           if (starter_bus != NULL)
5161             {
5162               g_set_error (error,
5163                            G_IO_ERROR,
5164                            G_IO_ERROR_INVALID_ARGUMENT,
5165                            _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5166                              " - unknown value `%s'"),
5167                            starter_bus);
5168             }
5169           else
5170             {
5171               g_set_error_literal (error,
5172                                    G_IO_ERROR,
5173                                    G_IO_ERROR_INVALID_ARGUMENT,
5174                                    _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5175                                      "variable is not set"));
5176             }
5177         }
5178       break;
5179     }
5180  out:
5181   return ret;
5182 }
5183
5184 static GDBusConnection *
5185 get_uninitialized_connection (GBusType            bus_type,
5186                               GCancellable       *cancellable,
5187                               GError            **error)
5188 {
5189   GDBusConnection **singleton;
5190   GDBusConnection *ret;
5191
5192   ret = NULL;
5193
5194   G_LOCK (message_bus_lock);
5195   singleton = message_bus_get_singleton (bus_type, error);
5196   if (singleton == NULL)
5197     goto out;
5198
5199   if (*singleton == NULL)
5200     {
5201       gchar *address;
5202       address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5203       if (address == NULL)
5204         goto out;
5205       ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5206                                        "address", address,
5207                                        "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5208                                                 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5209                                        "exit-on-close", TRUE,
5210                                        NULL);
5211     }
5212   else
5213     {
5214       ret = g_object_ref (*singleton);
5215     }
5216
5217   g_assert (ret != NULL);
5218
5219  out:
5220   G_UNLOCK (message_bus_lock);
5221   return ret;
5222 }
5223
5224 /**
5225  * g_bus_get_sync:
5226  * @bus_type: A #GBusType.
5227  * @cancellable: A #GCancellable or %NULL.
5228  * @error: Return location for error or %NULL.
5229  *
5230  * Synchronously connects to the message bus specified by @bus_type.
5231  * Note that the returned object may shared with other callers,
5232  * e.g. if two separate parts of a process calls this function with
5233  * the same @bus_type, they will share the same object.
5234  *
5235  * This is a synchronous failable function. See g_bus_get() and
5236  * g_bus_get_finish() for the asynchronous version.
5237  *
5238  * The returned object is a singleton, that is, shared with other
5239  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5240  * event that you need a private message bus connection, use
5241  * g_dbus_address_get_for_bus() and
5242  * g_dbus_connection_new_for_address().
5243  *
5244  * Note that the returned #GDBusConnection object will (usually) have
5245  * the #GDBusConnection:exit-on-close property set to %TRUE.
5246  *
5247  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5248  *
5249  * Since: 2.26
5250  */
5251 GDBusConnection *
5252 g_bus_get_sync (GBusType            bus_type,
5253                 GCancellable       *cancellable,
5254                 GError            **error)
5255 {
5256   GDBusConnection *connection;
5257
5258   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5259
5260   connection = get_uninitialized_connection (bus_type, cancellable, error);
5261   if (connection == NULL)
5262     goto out;
5263
5264   if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5265     {
5266       g_object_unref (connection);
5267       connection = NULL;
5268     }
5269
5270  out:
5271   return connection;
5272 }
5273
5274 static void
5275 bus_get_async_initable_cb (GObject      *source_object,
5276                            GAsyncResult *res,
5277                            gpointer      user_data)
5278 {
5279   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5280   GError *error;
5281
5282   error = NULL;
5283   if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5284                                      res,
5285                                      &error))
5286     {
5287       g_assert (error != NULL);
5288       g_simple_async_result_set_from_error (simple, error);
5289       g_error_free (error);
5290       g_object_unref (source_object);
5291     }
5292   else
5293     {
5294       g_simple_async_result_set_op_res_gpointer (simple,
5295                                                  source_object,
5296                                                  g_object_unref);
5297     }
5298   g_simple_async_result_complete_in_idle (simple);
5299   g_object_unref (simple);
5300 }
5301
5302 /**
5303  * g_bus_get:
5304  * @bus_type: A #GBusType.
5305  * @cancellable: A #GCancellable or %NULL.
5306  * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5307  * @user_data: The data to pass to @callback.
5308  *
5309  * Asynchronously connects to the message bus specified by @bus_type.
5310  *
5311  * When the operation is finished, @callback will be invoked. You can
5312  * then call g_bus_get_finish() to get the result of the operation.
5313  *
5314  * This is a asynchronous failable function. See g_bus_get_sync() for
5315  * the synchronous version.
5316  *
5317  * Since: 2.26
5318  */
5319 void
5320 g_bus_get (GBusType             bus_type,
5321            GCancellable        *cancellable,
5322            GAsyncReadyCallback  callback,
5323            gpointer             user_data)
5324 {
5325   GDBusConnection *connection;
5326   GSimpleAsyncResult *simple;
5327   GError *error;
5328
5329   simple = g_simple_async_result_new (NULL,
5330                                       callback,
5331                                       user_data,
5332                                       g_bus_get);
5333
5334   error = NULL;
5335   connection = get_uninitialized_connection (bus_type, cancellable, &error);
5336   if (connection == NULL)
5337     {
5338       g_assert (error != NULL);
5339       g_simple_async_result_set_from_error (simple, error);
5340       g_error_free (error);
5341       g_simple_async_result_complete_in_idle (simple);
5342       g_object_unref (simple);
5343     }
5344   else
5345     {
5346       g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5347                                    G_PRIORITY_DEFAULT,
5348                                    cancellable,
5349                                    bus_get_async_initable_cb,
5350                                    simple);
5351     }
5352 }
5353
5354 /**
5355  * g_bus_get_finish:
5356  * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5357  * @error: Return location for error or %NULL.
5358  *
5359  * Finishes an operation started with g_bus_get().
5360  *
5361  * The returned object is a singleton, that is, shared with other
5362  * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5363  * event that you need a private message bus connection, use
5364  * g_dbus_address_get_for_bus() and
5365  * g_dbus_connection_new_for_address().
5366  *
5367  * Note that the returned #GDBusConnection object will (usually) have
5368  * the #GDBusConnection:exit-on-close property set to %TRUE.
5369  *
5370  * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5371  *
5372  * Since: 2.26
5373  */
5374 GDBusConnection *
5375 g_bus_get_finish (GAsyncResult  *res,
5376                   GError       **error)
5377 {
5378   GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5379   GObject *object;
5380   GDBusConnection *ret;
5381
5382   g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5383
5384   g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5385
5386   ret = NULL;
5387
5388   if (g_simple_async_result_propagate_error (simple, error))
5389     goto out;
5390
5391   object = g_simple_async_result_get_op_res_gpointer (simple);
5392   g_assert (object != NULL);
5393   ret = g_object_ref (G_DBUS_CONNECTION (object));
5394
5395  out:
5396   return ret;
5397 }
5398
5399 /* ---------------------------------------------------------------------------------------------------- */
5400
5401 #define __G_DBUS_CONNECTION_C__
5402 #include "gioaliasdef.c"