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