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