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