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