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