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