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