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