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