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