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