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