1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
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.1 of the License, or (at your option) any later version.
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.
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/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
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
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
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)
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.
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
64 * - see g_dbus_address_connect() in gdbusaddress.c
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
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
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
78 * e.g. not of much use.
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)
98 #include "gdbusauth.h"
99 #include "gdbusutils.h"
100 #include "gdbusaddress.h"
101 #include "gdbusmessage.h"
102 #include "gdbusconnection.h"
103 #include "gdbuserror.h"
104 #include "gioenumtypes.h"
105 #include "gdbusintrospection.h"
106 #include "gdbusmethodinvocation.h"
107 #include "gdbusprivate.h"
108 #include "gdbusauthobserver.h"
109 #include "ginitable.h"
110 #include "gasyncinitable.h"
111 #include "giostream.h"
112 #include "gasyncresult.h"
114 #include "gmarshal-internal.h"
117 #include "gunixconnection.h"
118 #include "gunixfdmessage.h"
121 #include "glibintl.h"
124 * SECTION:gdbusconnection
125 * @short_description: D-Bus Connections
126 * @include: gio/gio.h
128 * The #GDBusConnection type is used for D-Bus connections to remote
129 * peers such as a message buses. It is a low-level API that offers a
130 * lot of flexibility. For instance, it lets you establish a connection
131 * over any transport that can by represented as a #GIOStream.
133 * This class is rarely used directly in D-Bus clients. If you are writing
134 * a D-Bus client, it is often easier to use the g_bus_own_name(),
135 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
137 * As an exception to the usual GLib rule that a particular object must not
138 * be used by two threads at the same time, #GDBusConnection's methods may be
139 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
140 * can safely return the same #GDBusConnection when called from any thread.
142 * Most of the ways to obtain a #GDBusConnection automatically initialize it
143 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
144 * g_bus_get(), and the synchronous versions of those methods, give you an
145 * initialized connection. Language bindings for GIO should use
146 * g_initable_new() or g_async_initable_new_async(), which also initialize the
149 * If you construct an uninitialized #GDBusConnection, such as via
150 * g_object_new(), you must initialize it via g_initable_init() or
151 * g_async_initable_init_async() before using its methods or properties.
152 * Calling methods or accessing properties on a #GDBusConnection that has not
153 * completed initialization successfully is considered to be invalid, and leads
154 * to undefined behaviour. In particular, if initialization fails with a
155 * #GError, the only valid thing you can do with that #GDBusConnection is to
156 * free it with g_object_unref().
158 * ## An example D-Bus server # {#gdbus-server}
160 * Here is an example for a D-Bus server:
161 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
163 * ## An example for exporting a subtree # {#gdbus-subtree-server}
165 * Here is an example for exporting a subtree:
166 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
168 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
170 * Here is an example for passing UNIX file descriptors:
171 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-unix-fd-client.c)
173 * ## An example for exporting a GObject # {#gdbus-export}
175 * Here is an example for exporting a #GObject:
176 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
179 /* ---------------------------------------------------------------------------------------------------- */
181 typedef struct _GDBusConnectionClass GDBusConnectionClass;
184 * GDBusConnectionClass:
185 * @closed: Signal class handler for the #GDBusConnection::closed signal.
187 * Class structure for #GDBusConnection.
191 struct _GDBusConnectionClass
194 GObjectClass parent_class;
198 void (*closed) (GDBusConnection *connection,
199 gboolean remote_peer_vanished,
203 G_LOCK_DEFINE_STATIC (message_bus_lock);
205 static GWeakRef the_session_bus;
206 static GWeakRef the_system_bus;
208 /* Extra pseudo-member of GDBusSendMessageFlags.
209 * Set by initable_init() to indicate that despite not being initialized yet,
210 * enough of the only-valid-after-init members are set that we can send a
211 * message, and we're being called from its thread, so no memory barrier is
212 * required before accessing them.
214 #define SEND_MESSAGE_FLAGS_INITIALIZING (1u << 31)
216 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
217 #define CALL_FLAGS_INITIALIZING (1u << 31)
219 /* ---------------------------------------------------------------------------------------------------- */
223 GDestroyNotify callback;
225 GMainContext *context;
226 } CallDestroyNotifyData;
229 call_destroy_notify_data_in_idle (gpointer user_data)
231 CallDestroyNotifyData *data = user_data;
232 data->callback (data->user_data);
237 call_destroy_notify_data_free (CallDestroyNotifyData *data)
239 if (data->context != NULL)
240 g_main_context_unref (data->context);
245 * call_destroy_notify: <internal>
246 * @context: (nullable): A #GMainContext or %NULL.
247 * @callback: (nullable): A #GDestroyNotify or %NULL.
248 * @user_data: Data to pass to @callback.
250 * Schedules @callback to run in @context.
253 call_destroy_notify (GMainContext *context,
254 GDestroyNotify callback,
257 GSource *idle_source;
258 CallDestroyNotifyData *data;
260 if (callback == NULL)
263 data = g_new0 (CallDestroyNotifyData, 1);
264 data->callback = callback;
265 data->user_data = user_data;
266 data->context = context;
267 if (data->context != NULL)
268 g_main_context_ref (data->context);
270 idle_source = g_idle_source_new ();
271 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
272 g_source_set_callback (idle_source,
273 call_destroy_notify_data_in_idle,
275 (GDestroyNotify) call_destroy_notify_data_free);
276 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
277 g_source_attach (idle_source, data->context);
278 g_source_unref (idle_source);
284 /* ---------------------------------------------------------------------------------------------------- */
287 _g_strv_has_string (const gchar* const *haystack,
292 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
294 if (g_strcmp0 (haystack[n], needle) == 0)
300 /* ---------------------------------------------------------------------------------------------------- */
303 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
305 // TODO: for some reason this doesn't work on Windows
306 #define CONNECTION_ENSURE_LOCK(obj) do { \
307 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
309 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
310 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
315 #define CONNECTION_LOCK(obj) do { \
316 g_mutex_lock (&(obj)->lock); \
319 #define CONNECTION_UNLOCK(obj) do { \
320 g_mutex_unlock (&(obj)->lock); \
323 /* Flags in connection->atomic_flags */
325 FLAG_INITIALIZED = 1 << 0,
326 FLAG_EXIT_ON_CLOSE = 1 << 1,
333 * The #GDBusConnection structure contains only private data and
334 * should only be accessed using the provided API.
338 struct _GDBusConnection
341 GObject parent_instance;
343 /* ------------------------------------------------------------------------ */
344 /* -- General object state ------------------------------------------------ */
345 /* ------------------------------------------------------------------------ */
347 /* General-purpose lock for most fields */
350 /* A lock used in the init() method of the GInitable interface - see comments
351 * in initable_init() for why a separate lock is needed.
353 * If you need both @lock and @init_lock, you must take @init_lock first.
357 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
358 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
362 /* The underlying stream used for communication
363 * Read-only after initable_init(), so it may be read if you either
364 * hold @init_lock or check for initialization first.
368 /* The object used for authentication (if any).
369 * Read-only after initable_init(), so it may be read if you either
370 * hold @init_lock or check for initialization first.
374 /* Last serial used. Protected by @lock. */
377 /* The object used to send/receive messages.
378 * Read-only after initable_init(), so it may be read if you either
379 * hold @init_lock or check for initialization first.
383 /* If connected to a message bus, this contains the unique name assigned to
384 * us by the bus (e.g. ":1.42").
385 * Read-only after initable_init(), so it may be read if you either
386 * hold @init_lock or check for initialization first.
388 gchar *bus_unique_name;
390 /* The GUID returned by the other side if we authenticed as a client or
391 * the GUID to use if authenticating as a server.
392 * Read-only after initable_init(), so it may be read if you either
393 * hold @init_lock or check for initialization first.
397 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
398 * Inspect @initialization_error to see whether it succeeded or failed.
400 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
402 * FLAG_CLOSED is the closed property. It may be read at any time, but
403 * may only be written while holding @lock.
405 volatile gint atomic_flags;
407 /* If the connection could not be established during initable_init(),
408 * this GError will be set.
409 * Read-only after initable_init(), so it may be read if you either
410 * hold @init_lock or check for initialization first.
412 GError *initialization_error;
414 /* The result of g_main_context_ref_thread_default() when the object
415 * was created (the GObject _init() function) - this is used for delivery
416 * of the :closed GObject signal.
418 * Only set in the GObject init function, so no locks are needed.
420 GMainContext *main_context_at_construction;
422 /* Read-only construct properties, no locks needed */
424 GDBusConnectionFlags flags;
426 /* Map used for managing method replies, protected by @lock */
427 GHashTable *map_method_serial_to_task; /* guint32 -> GTask* */
429 /* Maps used for managing signal subscription, protected by @lock */
430 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
431 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
432 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
434 /* Maps used for managing exported objects and subtrees,
437 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
438 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
439 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
440 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
442 /* Map used for storing last used serials for each thread, protected by @lock */
443 GHashTable *map_thread_to_last_serial;
445 /* Structure used for message filters, protected by @lock */
448 /* Capabilities negotiated during authentication
449 * Read-only after initable_init(), so it may be read without holding a
450 * lock, if you check for initialization first.
452 GDBusCapabilityFlags capabilities;
454 /* Protected by @init_lock */
455 GDBusAuthObserver *authentication_observer;
457 /* Read-only after initable_init(), so it may be read if you either
458 * hold @init_lock or check for initialization first.
460 GCredentials *credentials;
462 /* set to TRUE when finalizing */
466 typedef struct ExportedObject ExportedObject;
467 static void exported_object_free (ExportedObject *eo);
469 typedef struct ExportedSubtree ExportedSubtree;
470 static void exported_subtree_free (ExportedSubtree *es);
488 PROP_CAPABILITY_FLAGS,
489 PROP_AUTHENTICATION_OBSERVER,
492 static void distribute_signals (GDBusConnection *connection,
493 GDBusMessage *message);
495 static void distribute_method_call (GDBusConnection *connection,
496 GDBusMessage *message);
498 static gboolean handle_generic_unlocked (GDBusConnection *connection,
499 GDBusMessage *message);
502 static void purge_all_signal_subscriptions (GDBusConnection *connection);
503 static void purge_all_filters (GDBusConnection *connection);
505 static void schedule_method_call (GDBusConnection *connection,
506 GDBusMessage *message,
507 guint registration_id,
508 guint subtree_registration_id,
509 const GDBusInterfaceInfo *interface_info,
510 const GDBusMethodInfo *method_info,
511 const GDBusPropertyInfo *property_info,
512 GVariant *parameters,
513 const GDBusInterfaceVTable *vtable,
514 GMainContext *main_context,
517 #define _G_ENSURE_LOCK(name) do { \
518 if (G_UNLIKELY (G_TRYLOCK(name))) \
520 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
521 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
525 static guint signals[LAST_SIGNAL] = { 0 };
527 static void initable_iface_init (GInitableIface *initable_iface);
528 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
530 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
531 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
532 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
536 * Check that all members of @connection that can only be accessed after
537 * the connection is initialized can safely be accessed. If not,
538 * log a critical warning. This function is a memory barrier.
540 * Returns: %TRUE if initialized
543 check_initialized (GDBusConnection *connection)
545 /* The access to @atomic_flags isn't conditional, so that this function
546 * provides a memory barrier for thread-safety even if checks are disabled.
547 * (If you don't want this stricter guarantee, you can call
548 * g_return_if_fail (check_initialized (c)).)
550 * This isn't strictly necessary now that we've decided use of an
551 * uninitialized GDBusConnection is undefined behaviour, but it seems
552 * better to be as deterministic as is feasible.
554 * (Anything that could suffer a crash from seeing undefined values
555 * must have a race condition - thread A initializes the connection while
556 * thread B calls a method without initialization, hoping that thread A will
557 * win the race - so its behaviour is undefined anyway.)
559 gint flags = g_atomic_int_get (&connection->atomic_flags);
561 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
563 /* We can safely access this, due to the memory barrier above */
564 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
570 MAY_BE_UNINITIALIZED = (1<<1)
571 } CheckUnclosedFlags;
574 * Check the same thing as check_initialized(), and also that the
575 * connection is not closed. If the connection is uninitialized,
576 * raise a critical warning (it's programmer error); if it's closed,
577 * raise a recoverable GError (it's a runtime error).
579 * This function is a memory barrier.
581 * Returns: %TRUE if initialized and not closed
584 check_unclosed (GDBusConnection *connection,
585 CheckUnclosedFlags check,
588 /* check_initialized() is effectively inlined, so we don't waste time
589 * doing two memory barriers
591 gint flags = g_atomic_int_get (&connection->atomic_flags);
593 if (!(check & MAY_BE_UNINITIALIZED))
595 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
596 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
599 if (flags & FLAG_CLOSED)
601 g_set_error_literal (error,
604 _("The connection is closed"));
611 static GHashTable *alive_connections = NULL;
614 g_dbus_connection_dispose (GObject *object)
616 GDBusConnection *connection = G_DBUS_CONNECTION (object);
618 G_LOCK (message_bus_lock);
619 CONNECTION_LOCK (connection);
620 if (connection->worker != NULL)
622 _g_dbus_worker_stop (connection->worker);
623 connection->worker = NULL;
624 if (alive_connections != NULL)
625 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
629 if (alive_connections != NULL)
630 g_warn_if_fail (!g_hash_table_contains (alive_connections, connection));
632 CONNECTION_UNLOCK (connection);
633 G_UNLOCK (message_bus_lock);
635 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
636 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
640 g_dbus_connection_finalize (GObject *object)
642 GDBusConnection *connection = G_DBUS_CONNECTION (object);
644 connection->finalizing = TRUE;
646 purge_all_signal_subscriptions (connection);
648 purge_all_filters (connection);
649 g_ptr_array_unref (connection->filters);
651 if (connection->authentication_observer != NULL)
652 g_object_unref (connection->authentication_observer);
654 if (connection->auth != NULL)
655 g_object_unref (connection->auth);
657 if (connection->credentials)
658 g_object_unref (connection->credentials);
660 if (connection->stream != NULL)
662 g_object_unref (connection->stream);
663 connection->stream = NULL;
666 g_free (connection->address);
668 g_free (connection->guid);
669 g_free (connection->bus_unique_name);
671 if (connection->initialization_error != NULL)
672 g_error_free (connection->initialization_error);
674 g_hash_table_unref (connection->map_method_serial_to_task);
676 g_hash_table_unref (connection->map_rule_to_signal_data);
677 g_hash_table_unref (connection->map_id_to_signal_data);
678 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
680 g_hash_table_unref (connection->map_id_to_ei);
681 g_hash_table_unref (connection->map_object_path_to_eo);
682 g_hash_table_unref (connection->map_id_to_es);
683 g_hash_table_unref (connection->map_object_path_to_es);
685 g_hash_table_unref (connection->map_thread_to_last_serial);
687 g_main_context_unref (connection->main_context_at_construction);
689 g_free (connection->machine_id);
691 g_mutex_clear (&connection->init_lock);
692 g_mutex_clear (&connection->lock);
694 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
697 /* called in any user thread, with the connection's lock not held */
699 g_dbus_connection_get_property (GObject *object,
704 GDBusConnection *connection = G_DBUS_CONNECTION (object);
709 g_value_set_object (value, g_dbus_connection_get_stream (connection));
713 g_value_set_string (value, g_dbus_connection_get_guid (connection));
716 case PROP_UNIQUE_NAME:
717 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
721 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
724 case PROP_EXIT_ON_CLOSE:
725 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
728 case PROP_CAPABILITY_FLAGS:
729 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
733 g_value_set_flags (value, g_dbus_connection_get_flags (connection));
737 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
742 /* called in any user thread, with the connection's lock not held */
744 g_dbus_connection_set_property (GObject *object,
749 GDBusConnection *connection = G_DBUS_CONNECTION (object);
754 connection->stream = g_value_dup_object (value);
758 connection->guid = g_value_dup_string (value);
762 connection->address = g_value_dup_string (value);
766 connection->flags = g_value_get_flags (value);
769 case PROP_EXIT_ON_CLOSE:
770 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
773 case PROP_AUTHENTICATION_OBSERVER:
774 connection->authentication_observer = g_value_dup_object (value);
778 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
783 /* Base-class implementation of GDBusConnection::closed.
785 * Called in a user thread, by the main context that was thread-default when
786 * the object was constructed.
789 g_dbus_connection_real_closed (GDBusConnection *connection,
790 gboolean remote_peer_vanished,
793 gint flags = g_atomic_int_get (&connection->atomic_flags);
795 /* Because atomic int access is a memory barrier, we can safely read
796 * initialization_error without a lock, as long as we do it afterwards.
798 if (remote_peer_vanished &&
799 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
800 (flags & FLAG_INITIALIZED) != 0 &&
801 connection->initialization_error == NULL)
808 g_dbus_connection_class_init (GDBusConnectionClass *klass)
810 GObjectClass *gobject_class;
812 gobject_class = G_OBJECT_CLASS (klass);
814 gobject_class->finalize = g_dbus_connection_finalize;
815 gobject_class->dispose = g_dbus_connection_dispose;
816 gobject_class->set_property = g_dbus_connection_set_property;
817 gobject_class->get_property = g_dbus_connection_get_property;
819 klass->closed = g_dbus_connection_real_closed;
822 * GDBusConnection:stream:
824 * The underlying #GIOStream used for I/O.
826 * If this is passed on construction and is a #GSocketConnection,
827 * then the corresponding #GSocket will be put into non-blocking mode.
829 * While the #GDBusConnection is active, it will interact with this
830 * stream from a worker thread, so it is not safe to interact with
831 * the stream directly.
835 g_object_class_install_property (gobject_class,
837 g_param_spec_object ("stream",
839 P_("The underlying streams used for I/O"),
843 G_PARAM_CONSTRUCT_ONLY |
844 G_PARAM_STATIC_NAME |
845 G_PARAM_STATIC_BLURB |
846 G_PARAM_STATIC_NICK));
849 * GDBusConnection:address:
851 * A D-Bus address specifying potential endpoints that can be used
852 * when establishing the connection.
856 g_object_class_install_property (gobject_class,
858 g_param_spec_string ("address",
860 P_("D-Bus address specifying potential socket endpoints"),
863 G_PARAM_CONSTRUCT_ONLY |
864 G_PARAM_STATIC_NAME |
865 G_PARAM_STATIC_BLURB |
866 G_PARAM_STATIC_NICK));
869 * GDBusConnection:flags:
871 * Flags from the #GDBusConnectionFlags enumeration.
875 g_object_class_install_property (gobject_class,
877 g_param_spec_flags ("flags",
880 G_TYPE_DBUS_CONNECTION_FLAGS,
881 G_DBUS_CONNECTION_FLAGS_NONE,
884 G_PARAM_CONSTRUCT_ONLY |
885 G_PARAM_STATIC_NAME |
886 G_PARAM_STATIC_BLURB |
887 G_PARAM_STATIC_NICK));
890 * GDBusConnection:guid:
892 * The GUID of the peer performing the role of server when
895 * If you are constructing a #GDBusConnection and pass
896 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
897 * #GDBusConnection:flags property then you MUST also set this
898 * property to a valid guid.
900 * If you are constructing a #GDBusConnection and pass
901 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
902 * #GDBusConnection:flags property you will be able to read the GUID
903 * of the other peer here after the connection has been successfully
908 g_object_class_install_property (gobject_class,
910 g_param_spec_string ("guid",
912 P_("GUID of the server peer"),
916 G_PARAM_CONSTRUCT_ONLY |
917 G_PARAM_STATIC_NAME |
918 G_PARAM_STATIC_BLURB |
919 G_PARAM_STATIC_NICK));
922 * GDBusConnection:unique-name:
924 * The unique name as assigned by the message bus or %NULL if the
925 * connection is not open or not a message bus connection.
929 g_object_class_install_property (gobject_class,
931 g_param_spec_string ("unique-name",
933 P_("Unique name of bus connection"),
936 G_PARAM_STATIC_NAME |
937 G_PARAM_STATIC_BLURB |
938 G_PARAM_STATIC_NICK));
941 * GDBusConnection:closed:
943 * A boolean specifying whether the connection has been closed.
947 g_object_class_install_property (gobject_class,
949 g_param_spec_boolean ("closed",
951 P_("Whether the connection is closed"),
954 G_PARAM_STATIC_NAME |
955 G_PARAM_STATIC_BLURB |
956 G_PARAM_STATIC_NICK));
959 * GDBusConnection:exit-on-close:
961 * A boolean specifying whether the process will be terminated (by
962 * calling `raise(SIGTERM)`) if the connection is closed by the
965 * Note that #GDBusConnection objects returned by g_bus_get_finish()
966 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
970 g_object_class_install_property (gobject_class,
972 g_param_spec_boolean ("exit-on-close",
974 P_("Whether the process is terminated when the connection is closed"),
978 G_PARAM_STATIC_NAME |
979 G_PARAM_STATIC_BLURB |
980 G_PARAM_STATIC_NICK));
983 * GDBusConnection:capabilities:
985 * Flags from the #GDBusCapabilityFlags enumeration
986 * representing connection features negotiated with the other peer.
990 g_object_class_install_property (gobject_class,
991 PROP_CAPABILITY_FLAGS,
992 g_param_spec_flags ("capabilities",
995 G_TYPE_DBUS_CAPABILITY_FLAGS,
996 G_DBUS_CAPABILITY_FLAGS_NONE,
998 G_PARAM_STATIC_NAME |
999 G_PARAM_STATIC_BLURB |
1000 G_PARAM_STATIC_NICK));
1003 * GDBusConnection:authentication-observer:
1005 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1009 g_object_class_install_property (gobject_class,
1010 PROP_AUTHENTICATION_OBSERVER,
1011 g_param_spec_object ("authentication-observer",
1012 P_("Authentication Observer"),
1013 P_("Object used to assist in the authentication process"),
1014 G_TYPE_DBUS_AUTH_OBSERVER,
1016 G_PARAM_CONSTRUCT_ONLY |
1017 G_PARAM_STATIC_NAME |
1018 G_PARAM_STATIC_BLURB |
1019 G_PARAM_STATIC_NICK));
1022 * GDBusConnection::closed:
1023 * @connection: the #GDBusConnection emitting the signal
1024 * @remote_peer_vanished: %TRUE if @connection is closed because the
1025 * remote peer closed its end of the connection
1026 * @error: (nullable): a #GError with more details about the event or %NULL
1028 * Emitted when the connection is closed.
1030 * The cause of this event can be
1032 * - If g_dbus_connection_close() is called. In this case
1033 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1035 * - If the remote peer closes the connection. In this case
1036 * @remote_peer_vanished is set to %TRUE and @error is set.
1038 * - If the remote peer sends invalid or malformed data. In this
1039 * case @remote_peer_vanished is set to %FALSE and @error is set.
1041 * Upon receiving this signal, you should give up your reference to
1042 * @connection. You are guaranteed that this signal is emitted only
1047 signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1048 G_TYPE_DBUS_CONNECTION,
1050 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1053 _g_cclosure_marshal_VOID__BOOLEAN_BOXED,
1058 g_signal_set_va_marshaller (signals[CLOSED_SIGNAL],
1059 G_TYPE_FROM_CLASS (klass),
1060 _g_cclosure_marshal_VOID__BOOLEAN_BOXEDv);
1064 g_dbus_connection_init (GDBusConnection *connection)
1066 g_mutex_init (&connection->lock);
1067 g_mutex_init (&connection->init_lock);
1069 connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1071 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1073 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1075 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1078 (GDestroyNotify) g_ptr_array_unref);
1080 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1083 (GDestroyNotify) exported_object_free);
1085 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1088 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1091 (GDestroyNotify) exported_subtree_free);
1093 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1096 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1099 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1101 connection->filters = g_ptr_array_new ();
1105 * g_dbus_connection_get_stream:
1106 * @connection: a #GDBusConnection
1108 * Gets the underlying stream used for IO.
1110 * While the #GDBusConnection is active, it will interact with this
1111 * stream from a worker thread, so it is not safe to interact with
1112 * the stream directly.
1114 * Returns: (transfer none): the stream used for IO
1119 g_dbus_connection_get_stream (GDBusConnection *connection)
1121 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1123 /* do not use g_return_val_if_fail(), we want the memory barrier */
1124 if (!check_initialized (connection))
1127 return connection->stream;
1131 * g_dbus_connection_start_message_processing:
1132 * @connection: a #GDBusConnection
1134 * If @connection was created with
1135 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1136 * starts processing messages. Does nothing on if @connection wasn't
1137 * created with this flag or if the method has already been called.
1142 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1144 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1146 /* do not use g_return_val_if_fail(), we want the memory barrier */
1147 if (!check_initialized (connection))
1150 g_assert (connection->worker != NULL);
1151 _g_dbus_worker_unfreeze (connection->worker);
1155 * g_dbus_connection_is_closed:
1156 * @connection: a #GDBusConnection
1158 * Gets whether @connection is closed.
1160 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1165 g_dbus_connection_is_closed (GDBusConnection *connection)
1169 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1171 flags = g_atomic_int_get (&connection->atomic_flags);
1173 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1177 * g_dbus_connection_get_capabilities:
1178 * @connection: a #GDBusConnection
1180 * Gets the capabilities negotiated with the remote peer
1182 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1186 GDBusCapabilityFlags
1187 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1189 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1191 /* do not use g_return_val_if_fail(), we want the memory barrier */
1192 if (!check_initialized (connection))
1193 return G_DBUS_CAPABILITY_FLAGS_NONE;
1195 return connection->capabilities;
1199 * g_dbus_connection_get_flags:
1200 * @connection: a #GDBusConnection
1202 * Gets the flags used to construct this connection
1204 * Returns: zero or more flags from the #GDBusConnectionFlags enumeration
1208 GDBusConnectionFlags
1209 g_dbus_connection_get_flags (GDBusConnection *connection)
1211 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CONNECTION_FLAGS_NONE);
1213 /* do not use g_return_val_if_fail(), we want the memory barrier */
1214 if (!check_initialized (connection))
1215 return G_DBUS_CONNECTION_FLAGS_NONE;
1217 return connection->flags;
1220 /* ---------------------------------------------------------------------------------------------------- */
1222 /* Called in a temporary thread without holding locks. */
1224 flush_in_thread_func (GTask *task,
1225 gpointer source_object,
1227 GCancellable *cancellable)
1229 GError *error = NULL;
1231 if (g_dbus_connection_flush_sync (source_object,
1234 g_task_return_boolean (task, TRUE);
1236 g_task_return_error (task, error);
1240 * g_dbus_connection_flush:
1241 * @connection: a #GDBusConnection
1242 * @cancellable: (nullable): a #GCancellable or %NULL
1243 * @callback: (nullable): a #GAsyncReadyCallback to call when the
1244 * request is satisfied or %NULL if you don't care about the result
1245 * @user_data: The data to pass to @callback
1247 * Asynchronously flushes @connection, that is, writes all queued
1248 * outgoing message to the transport and then flushes the transport
1249 * (using g_output_stream_flush_async()). This is useful in programs
1250 * that wants to emit a D-Bus signal and then exit immediately. Without
1251 * flushing the connection, there is no guaranteed that the message has
1252 * been sent to the networking buffers in the OS kernel.
1254 * This is an asynchronous method. When the operation is finished,
1255 * @callback will be invoked in the
1256 * [thread-default main context][g-main-context-push-thread-default]
1257 * of the thread you are calling this method from. You can
1258 * then call g_dbus_connection_flush_finish() to get the result of the
1259 * operation. See g_dbus_connection_flush_sync() for the synchronous
1265 g_dbus_connection_flush (GDBusConnection *connection,
1266 GCancellable *cancellable,
1267 GAsyncReadyCallback callback,
1272 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1274 task = g_task_new (connection, cancellable, callback, user_data);
1275 g_task_set_source_tag (task, g_dbus_connection_flush);
1276 g_task_run_in_thread (task, flush_in_thread_func);
1277 g_object_unref (task);
1281 * g_dbus_connection_flush_finish:
1282 * @connection: a #GDBusConnection
1283 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1284 * to g_dbus_connection_flush()
1285 * @error: return location for error or %NULL
1287 * Finishes an operation started with g_dbus_connection_flush().
1289 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1294 g_dbus_connection_flush_finish (GDBusConnection *connection,
1298 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1299 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1300 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1302 return g_task_propagate_boolean (G_TASK (res), error);
1306 * g_dbus_connection_flush_sync:
1307 * @connection: a #GDBusConnection
1308 * @cancellable: (nullable): a #GCancellable or %NULL
1309 * @error: return location for error or %NULL
1311 * Synchronously flushes @connection. The calling thread is blocked
1312 * until this is done. See g_dbus_connection_flush() for the
1313 * asynchronous version of this method and more details about what it
1316 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1321 g_dbus_connection_flush_sync (GDBusConnection *connection,
1322 GCancellable *cancellable,
1327 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1328 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1332 /* This is only a best-effort attempt to see whether the connection is
1333 * closed, so it doesn't need the lock. If the connection closes just
1334 * after this check, but before scheduling the flush operation, the
1335 * result will be more or less the same as if the connection closed while
1336 * the flush operation was pending - it'll fail with either CLOSED or
1339 if (!check_unclosed (connection, 0, error))
1342 g_assert (connection->worker != NULL);
1344 ret = _g_dbus_worker_flush_sync (connection->worker,
1352 /* ---------------------------------------------------------------------------------------------------- */
1356 GDBusConnection *connection;
1358 gboolean remote_peer_vanished;
1362 emit_closed_data_free (EmitClosedData *data)
1364 g_object_unref (data->connection);
1365 if (data->error != NULL)
1366 g_error_free (data->error);
1370 /* Called in a user thread that has acquired the main context that was
1371 * thread-default when the object was constructed
1374 emit_closed_in_idle (gpointer user_data)
1376 EmitClosedData *data = user_data;
1379 g_object_notify (G_OBJECT (data->connection), "closed");
1380 g_signal_emit (data->connection,
1381 signals[CLOSED_SIGNAL],
1383 data->remote_peer_vanished,
1389 /* Can be called from any thread, must hold lock.
1390 * FLAG_CLOSED must already have been set.
1393 schedule_closed_unlocked (GDBusConnection *connection,
1394 gboolean remote_peer_vanished,
1397 GSource *idle_source;
1398 EmitClosedData *data;
1400 CONNECTION_ENSURE_LOCK (connection);
1402 data = g_new0 (EmitClosedData, 1);
1403 data->connection = g_object_ref (connection);
1404 data->remote_peer_vanished = remote_peer_vanished;
1405 data->error = error != NULL ? g_error_copy (error) : NULL;
1407 idle_source = g_idle_source_new ();
1408 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1409 g_source_set_callback (idle_source,
1410 emit_closed_in_idle,
1412 (GDestroyNotify) emit_closed_data_free);
1413 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1414 g_source_attach (idle_source, connection->main_context_at_construction);
1415 g_source_unref (idle_source);
1418 /* ---------------------------------------------------------------------------------------------------- */
1421 * g_dbus_connection_close:
1422 * @connection: a #GDBusConnection
1423 * @cancellable: (nullable): a #GCancellable or %NULL
1424 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1425 * satisfied or %NULL if you don't care about the result
1426 * @user_data: The data to pass to @callback
1428 * Closes @connection. Note that this never causes the process to
1429 * exit (this might only happen if the other end of a shared message
1430 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1432 * Once the connection is closed, operations such as sending a message
1433 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1434 * will not automatically flush the connection so queued messages may
1435 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1437 * If @connection is already closed, this method fails with
1438 * %G_IO_ERROR_CLOSED.
1440 * When @connection has been closed, the #GDBusConnection::closed
1441 * signal is emitted in the
1442 * [thread-default main context][g-main-context-push-thread-default]
1443 * of the thread that @connection was constructed in.
1445 * This is an asynchronous method. When the operation is finished,
1446 * @callback will be invoked in the
1447 * [thread-default main context][g-main-context-push-thread-default]
1448 * of the thread you are calling this method from. You can
1449 * then call g_dbus_connection_close_finish() to get the result of the
1450 * operation. See g_dbus_connection_close_sync() for the synchronous
1456 g_dbus_connection_close (GDBusConnection *connection,
1457 GCancellable *cancellable,
1458 GAsyncReadyCallback callback,
1463 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1465 /* do not use g_return_val_if_fail(), we want the memory barrier */
1466 if (!check_initialized (connection))
1469 g_assert (connection->worker != NULL);
1471 task = g_task_new (connection, cancellable, callback, user_data);
1472 g_task_set_source_tag (task, g_dbus_connection_close);
1473 _g_dbus_worker_close (connection->worker, task);
1474 g_object_unref (task);
1478 * g_dbus_connection_close_finish:
1479 * @connection: a #GDBusConnection
1480 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1481 * to g_dbus_connection_close()
1482 * @error: return location for error or %NULL
1484 * Finishes an operation started with g_dbus_connection_close().
1486 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1491 g_dbus_connection_close_finish (GDBusConnection *connection,
1495 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1496 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1497 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1499 return g_task_propagate_boolean (G_TASK (res), error);
1504 GAsyncResult *result;
1507 /* Can be called by any thread, without the connection lock */
1509 sync_close_cb (GObject *source_object,
1513 SyncCloseData *data = user_data;
1515 data->result = g_object_ref (res);
1516 g_main_loop_quit (data->loop);
1520 * g_dbus_connection_close_sync:
1521 * @connection: a #GDBusConnection
1522 * @cancellable: (nullable): a #GCancellable or %NULL
1523 * @error: return location for error or %NULL
1525 * Synchronously closes @connection. The calling thread is blocked
1526 * until this is done. See g_dbus_connection_close() for the
1527 * asynchronous version of this method and more details about what it
1530 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1535 g_dbus_connection_close_sync (GDBusConnection *connection,
1536 GCancellable *cancellable,
1541 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1542 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1546 if (check_unclosed (connection, 0, error))
1548 GMainContext *context;
1551 context = g_main_context_new ();
1552 g_main_context_push_thread_default (context);
1553 data.loop = g_main_loop_new (context, TRUE);
1556 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1557 g_main_loop_run (data.loop);
1558 ret = g_dbus_connection_close_finish (connection, data.result, error);
1560 g_object_unref (data.result);
1561 g_main_loop_unref (data.loop);
1562 g_main_context_pop_thread_default (context);
1563 g_main_context_unref (context);
1569 /* ---------------------------------------------------------------------------------------------------- */
1572 * g_dbus_connection_get_last_serial:
1573 * @connection: a #GDBusConnection
1575 * Retrieves the last serial number assigned to a #GDBusMessage on
1576 * the current thread. This includes messages sent via both low-level
1577 * API such as g_dbus_connection_send_message() as well as
1578 * high-level API such as g_dbus_connection_emit_signal(),
1579 * g_dbus_connection_call() or g_dbus_proxy_call().
1581 * Returns: the last used serial or zero when no message has been sent
1582 * within the current thread
1587 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1591 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1593 CONNECTION_LOCK (connection);
1594 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1596 CONNECTION_UNLOCK (connection);
1601 /* ---------------------------------------------------------------------------------------------------- */
1603 /* Can be called by any thread, with the connection lock held */
1605 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1606 GDBusMessage *message,
1607 GDBusSendMessageFlags flags,
1608 volatile guint32 *out_serial,
1613 guint32 serial_to_use;
1616 CONNECTION_ENSURE_LOCK (connection);
1618 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1619 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1621 /* TODO: check all necessary headers are present */
1626 if (out_serial != NULL)
1629 /* If we're in initable_init(), don't check for being initialized, to avoid
1630 * chicken-and-egg problems. initable_init() is responsible for setting up
1631 * our prerequisites (mainly connection->worker), and only calling us
1632 * from its own thread (so no memory barrier is needed).
1634 if (!check_unclosed (connection,
1635 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1639 blob = g_dbus_message_to_blob (message,
1641 connection->capabilities,
1646 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1647 serial_to_use = g_dbus_message_get_serial (message);
1649 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1654 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1657 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1660 g_assert_not_reached ();
1665 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1666 blob_size, serial_to_use, connection);
1667 g_printerr ("----\n");
1668 hexdump (blob, blob_size);
1669 g_printerr ("----\n");
1672 /* TODO: use connection->auth to encode the blob */
1674 if (out_serial != NULL)
1675 *out_serial = serial_to_use;
1677 /* store used serial for the current thread */
1678 /* TODO: watch the thread disposal and remove associated record
1680 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1682 g_hash_table_replace (connection->map_thread_to_last_serial,
1684 GUINT_TO_POINTER (serial_to_use));
1686 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1687 g_dbus_message_set_serial (message, serial_to_use);
1689 g_dbus_message_lock (message);
1690 _g_dbus_worker_send_message (connection->worker,
1694 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1705 * g_dbus_connection_send_message:
1706 * @connection: a #GDBusConnection
1707 * @message: a #GDBusMessage
1708 * @flags: flags affecting how the message is sent
1709 * @out_serial: (out) (optional): return location for serial number assigned
1710 * to @message when sending it or %NULL
1711 * @error: Return location for error or %NULL
1713 * Asynchronously sends @message to the peer represented by @connection.
1715 * Unless @flags contain the
1716 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1717 * will be assigned by @connection and set on @message via
1718 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1719 * serial number used will be written to this location prior to
1720 * submitting the message to the underlying transport.
1722 * If @connection is closed then the operation will fail with
1723 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1724 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1726 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1727 * for an example of how to use this low-level API to send and receive
1728 * UNIX file descriptors.
1730 * Note that @message must be unlocked, unless @flags contain the
1731 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1733 * Returns: %TRUE if the message was well-formed and queued for
1734 * transmission, %FALSE if @error is set
1739 g_dbus_connection_send_message (GDBusConnection *connection,
1740 GDBusMessage *message,
1741 GDBusSendMessageFlags flags,
1742 volatile guint32 *out_serial,
1747 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1748 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1749 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1750 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1752 CONNECTION_LOCK (connection);
1753 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1754 CONNECTION_UNLOCK (connection);
1758 /* ---------------------------------------------------------------------------------------------------- */
1764 gulong cancellable_handler_id;
1766 GSource *timeout_source;
1771 /* Can be called from any thread with or without lock held */
1773 send_message_data_free (SendMessageData *data)
1775 g_assert (data->timeout_source == NULL);
1776 g_assert (data->cancellable_handler_id == 0);
1778 g_slice_free (SendMessageData, data);
1781 /* ---------------------------------------------------------------------------------------------------- */
1783 /* can be called from any thread with lock held; @task is (transfer full) */
1785 send_message_with_reply_cleanup (GTask *task, gboolean remove)
1787 GDBusConnection *connection = g_task_get_source_object (task);
1788 SendMessageData *data = g_task_get_task_data (task);
1790 CONNECTION_ENSURE_LOCK (connection);
1792 g_assert (!data->delivered);
1794 data->delivered = TRUE;
1796 if (data->timeout_source != NULL)
1798 g_source_destroy (data->timeout_source);
1799 data->timeout_source = NULL;
1801 if (data->cancellable_handler_id > 0)
1803 g_cancellable_disconnect (g_task_get_cancellable (task), data->cancellable_handler_id);
1804 data->cancellable_handler_id = 0;
1809 gboolean removed = g_hash_table_remove (connection->map_method_serial_to_task,
1810 GUINT_TO_POINTER (data->serial));
1811 g_warn_if_fail (removed);
1814 g_object_unref (task);
1817 /* ---------------------------------------------------------------------------------------------------- */
1819 /* Called from GDBus worker thread with lock held; @task is (transfer full). */
1821 send_message_data_deliver_reply_unlocked (GTask *task,
1822 GDBusMessage *reply)
1824 SendMessageData *data = g_task_get_task_data (task);
1826 if (data->delivered)
1829 g_task_return_pointer (task, g_object_ref (reply), g_object_unref);
1831 send_message_with_reply_cleanup (task, TRUE);
1837 /* Called from a user thread, lock is not held */
1839 send_message_data_deliver_error (GTask *task,
1842 const char *message)
1844 GDBusConnection *connection = g_task_get_source_object (task);
1845 SendMessageData *data = g_task_get_task_data (task);
1847 CONNECTION_LOCK (connection);
1848 if (data->delivered)
1850 CONNECTION_UNLOCK (connection);
1854 g_object_ref (task);
1855 send_message_with_reply_cleanup (task, TRUE);
1856 CONNECTION_UNLOCK (connection);
1858 g_task_return_new_error (task, domain, code, "%s", message);
1859 g_object_unref (task);
1862 /* ---------------------------------------------------------------------------------------------------- */
1864 /* Called from a user thread, lock is not held; @task is (transfer full) */
1866 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1868 GTask *task = user_data;
1870 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_CANCELLED,
1871 _("Operation was cancelled"));
1875 /* Can be called from any thread with or without lock held */
1877 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1880 GTask *task = user_data;
1881 GSource *idle_source;
1883 /* postpone cancellation to idle handler since we may be called directly
1884 * via g_cancellable_connect() (e.g. holding lock)
1886 idle_source = g_idle_source_new ();
1887 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
1888 g_task_attach_source (task, idle_source, send_message_with_reply_cancelled_idle_cb);
1889 g_source_unref (idle_source);
1892 /* ---------------------------------------------------------------------------------------------------- */
1894 /* Called from a user thread, lock is not held; @task is (transfer full) */
1896 send_message_with_reply_timeout_cb (gpointer user_data)
1898 GTask *task = user_data;
1900 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
1901 _("Timeout was reached"));
1905 /* ---------------------------------------------------------------------------------------------------- */
1907 /* Called from a user thread, connection's lock is held */
1909 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1910 GDBusMessage *message,
1911 GDBusSendMessageFlags flags,
1913 volatile guint32 *out_serial,
1914 GCancellable *cancellable,
1915 GAsyncReadyCallback callback,
1919 SendMessageData *data;
1920 GError *error = NULL;
1921 volatile guint32 serial;
1923 if (out_serial == NULL)
1924 out_serial = &serial;
1926 if (timeout_msec == -1)
1927 timeout_msec = 25 * 1000;
1929 data = g_slice_new0 (SendMessageData);
1930 task = g_task_new (connection, cancellable, callback, user_data);
1931 g_task_set_source_tag (task,
1932 g_dbus_connection_send_message_with_reply_unlocked);
1933 g_task_set_task_data (task, data, (GDestroyNotify) send_message_data_free);
1935 if (g_task_return_error_if_cancelled (task))
1937 g_object_unref (task);
1941 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1943 g_task_return_error (task, error);
1944 g_object_unref (task);
1947 data->serial = *out_serial;
1949 if (cancellable != NULL)
1951 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1952 G_CALLBACK (send_message_with_reply_cancelled_cb),
1953 g_object_ref (task),
1957 if (timeout_msec != G_MAXINT)
1959 data->timeout_source = g_timeout_source_new (timeout_msec);
1960 g_task_attach_source (task, data->timeout_source,
1961 (GSourceFunc) send_message_with_reply_timeout_cb);
1962 g_source_unref (data->timeout_source);
1965 g_hash_table_insert (connection->map_method_serial_to_task,
1966 GUINT_TO_POINTER (*out_serial),
1967 g_steal_pointer (&task));
1971 * g_dbus_connection_send_message_with_reply:
1972 * @connection: a #GDBusConnection
1973 * @message: a #GDBusMessage
1974 * @flags: flags affecting how the message is sent
1975 * @timeout_msec: the timeout in milliseconds, -1 to use the default
1976 * timeout or %G_MAXINT for no timeout
1977 * @out_serial: (out) (optional): return location for serial number assigned
1978 * to @message when sending it or %NULL
1979 * @cancellable: (nullable): a #GCancellable or %NULL
1980 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
1981 * is satisfied or %NULL if you don't care about the result
1982 * @user_data: The data to pass to @callback
1984 * Asynchronously sends @message to the peer represented by @connection.
1986 * Unless @flags contain the
1987 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1988 * will be assigned by @connection and set on @message via
1989 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1990 * serial number used will be written to this location prior to
1991 * submitting the message to the underlying transport.
1993 * If @connection is closed then the operation will fail with
1994 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1995 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1996 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1998 * This is an asynchronous method. When the operation is finished, @callback
1999 * will be invoked in the
2000 * [thread-default main context][g-main-context-push-thread-default]
2001 * of the thread you are calling this method from. You can then call
2002 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2003 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2005 * Note that @message must be unlocked, unless @flags contain the
2006 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2008 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2009 * for an example of how to use this low-level API to send and receive
2010 * UNIX file descriptors.
2015 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2016 GDBusMessage *message,
2017 GDBusSendMessageFlags flags,
2019 volatile guint32 *out_serial,
2020 GCancellable *cancellable,
2021 GAsyncReadyCallback callback,
2024 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2025 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2026 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2027 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2029 CONNECTION_LOCK (connection);
2030 g_dbus_connection_send_message_with_reply_unlocked (connection,
2038 CONNECTION_UNLOCK (connection);
2042 * g_dbus_connection_send_message_with_reply_finish:
2043 * @connection: a #GDBusConnection
2044 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2045 * g_dbus_connection_send_message_with_reply()
2046 * @error: teturn location for error or %NULL
2048 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2050 * Note that @error is only set if a local in-process error
2051 * occurred. That is to say that the returned #GDBusMessage object may
2052 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2053 * g_dbus_message_to_gerror() to transcode this to a #GError.
2055 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2056 * for an example of how to use this low-level API to send and receive
2057 * UNIX file descriptors.
2059 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2064 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2068 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2069 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
2070 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2072 return g_task_propagate_pointer (G_TASK (res), error);
2075 /* ---------------------------------------------------------------------------------------------------- */
2080 GMainContext *context;
2082 } SendMessageSyncData;
2084 /* Called from a user thread, lock is not held */
2086 send_message_with_reply_sync_cb (GDBusConnection *connection,
2090 SendMessageSyncData *data = user_data;
2091 data->res = g_object_ref (res);
2092 g_main_loop_quit (data->loop);
2096 * g_dbus_connection_send_message_with_reply_sync:
2097 * @connection: a #GDBusConnection
2098 * @message: a #GDBusMessage
2099 * @flags: flags affecting how the message is sent.
2100 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2101 * timeout or %G_MAXINT for no timeout
2102 * @out_serial: (out) (optional): return location for serial number
2103 * assigned to @message when sending it or %NULL
2104 * @cancellable: (nullable): a #GCancellable or %NULL
2105 * @error: return location for error or %NULL
2107 * Synchronously sends @message to the peer represented by @connection
2108 * and blocks the calling thread until a reply is received or the
2109 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2110 * for the asynchronous version of this method.
2112 * Unless @flags contain the
2113 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2114 * will be assigned by @connection and set on @message via
2115 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2116 * serial number used will be written to this location prior to
2117 * submitting the message to the underlying transport.
2119 * If @connection is closed then the operation will fail with
2120 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2121 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2122 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2124 * Note that @error is only set if a local in-process error
2125 * occurred. That is to say that the returned #GDBusMessage object may
2126 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2127 * g_dbus_message_to_gerror() to transcode this to a #GError.
2129 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2130 * for an example of how to use this low-level API to send and receive
2131 * UNIX file descriptors.
2133 * Note that @message must be unlocked, unless @flags contain the
2134 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2136 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2137 * to @message or %NULL if @error is set
2142 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2143 GDBusMessage *message,
2144 GDBusSendMessageFlags flags,
2146 volatile guint32 *out_serial,
2147 GCancellable *cancellable,
2150 SendMessageSyncData data;
2151 GDBusMessage *reply;
2153 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2154 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2155 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2156 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2157 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2160 data.context = g_main_context_new ();
2161 data.loop = g_main_loop_new (data.context, FALSE);
2163 g_main_context_push_thread_default (data.context);
2165 g_dbus_connection_send_message_with_reply (connection,
2171 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2173 g_main_loop_run (data.loop);
2174 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2178 g_main_context_pop_thread_default (data.context);
2180 g_main_context_unref (data.context);
2181 g_main_loop_unref (data.loop);
2183 g_object_unref (data.res);
2188 /* ---------------------------------------------------------------------------------------------------- */
2194 GDBusMessageFilterFunction filter_function;
2196 GDestroyNotify user_data_free_func;
2197 GMainContext *context;
2200 /* requires CONNECTION_LOCK */
2201 static FilterData **
2202 copy_filter_list (GPtrArray *filters)
2207 copy = g_new (FilterData *, filters->len + 1);
2208 for (n = 0; n < filters->len; n++)
2210 copy[n] = filters->pdata[n];
2211 copy[n]->ref_count++;
2218 /* requires CONNECTION_LOCK */
2220 free_filter_list (FilterData **filters)
2224 for (n = 0; filters[n]; n++)
2226 filters[n]->ref_count--;
2227 if (filters[n]->ref_count == 0)
2229 call_destroy_notify (filters[n]->context,
2230 filters[n]->user_data_free_func,
2231 filters[n]->user_data);
2232 g_main_context_unref (filters[n]->context);
2233 g_free (filters[n]);
2239 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2241 on_worker_message_received (GDBusWorker *worker,
2242 GDBusMessage *message,
2245 GDBusConnection *connection;
2246 FilterData **filters;
2250 G_LOCK (message_bus_lock);
2251 alive = g_hash_table_contains (alive_connections, user_data);
2254 G_UNLOCK (message_bus_lock);
2257 connection = G_DBUS_CONNECTION (user_data);
2258 g_object_ref (connection);
2259 G_UNLOCK (message_bus_lock);
2261 //g_debug ("in on_worker_message_received");
2263 g_object_ref (message);
2264 g_dbus_message_lock (message);
2266 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2268 /* First collect the set of callback functions */
2269 CONNECTION_LOCK (connection);
2270 filters = copy_filter_list (connection->filters);
2271 CONNECTION_UNLOCK (connection);
2273 /* then call the filters in order (without holding the lock) */
2274 for (n = 0; filters[n]; n++)
2276 message = filters[n]->filter_function (connection,
2279 filters[n]->user_data);
2280 if (message == NULL)
2282 g_dbus_message_lock (message);
2285 CONNECTION_LOCK (connection);
2286 free_filter_list (filters);
2287 CONNECTION_UNLOCK (connection);
2289 /* Standard dispatch unless the filter ate the message - no need to
2290 * do anything if the message was altered
2292 if (message != NULL)
2294 GDBusMessageType message_type;
2296 message_type = g_dbus_message_get_message_type (message);
2297 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2299 guint32 reply_serial;
2302 reply_serial = g_dbus_message_get_reply_serial (message);
2303 CONNECTION_LOCK (connection);
2304 task = g_hash_table_lookup (connection->map_method_serial_to_task,
2305 GUINT_TO_POINTER (reply_serial));
2308 /* This removes @task from @map_method_serial_to_task. */
2309 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2310 send_message_data_deliver_reply_unlocked (task, message);
2314 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2316 CONNECTION_UNLOCK (connection);
2318 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2320 CONNECTION_LOCK (connection);
2321 distribute_signals (connection, message);
2322 CONNECTION_UNLOCK (connection);
2324 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2326 CONNECTION_LOCK (connection);
2327 distribute_method_call (connection, message);
2328 CONNECTION_UNLOCK (connection);
2332 if (message != NULL)
2333 g_object_unref (message);
2334 g_object_unref (connection);
2337 /* Called in GDBusWorker's thread, lock is not held */
2338 static GDBusMessage *
2339 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2340 GDBusMessage *message,
2343 GDBusConnection *connection;
2344 FilterData **filters;
2348 G_LOCK (message_bus_lock);
2349 alive = g_hash_table_contains (alive_connections, user_data);
2352 G_UNLOCK (message_bus_lock);
2355 connection = G_DBUS_CONNECTION (user_data);
2356 g_object_ref (connection);
2357 G_UNLOCK (message_bus_lock);
2359 //g_debug ("in on_worker_message_about_to_be_sent");
2361 /* First collect the set of callback functions */
2362 CONNECTION_LOCK (connection);
2363 filters = copy_filter_list (connection->filters);
2364 CONNECTION_UNLOCK (connection);
2366 /* then call the filters in order (without holding the lock) */
2367 for (n = 0; filters[n]; n++)
2369 g_dbus_message_lock (message);
2370 message = filters[n]->filter_function (connection,
2373 filters[n]->user_data);
2374 if (message == NULL)
2378 CONNECTION_LOCK (connection);
2379 free_filter_list (filters);
2380 CONNECTION_UNLOCK (connection);
2382 g_object_unref (connection);
2387 /* called with connection lock held, in GDBusWorker thread */
2389 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2391 GTask *task = value;
2392 SendMessageData *data = g_task_get_task_data (task);
2394 if (data->delivered)
2397 g_task_return_new_error (task,
2400 _("The connection is closed"));
2402 /* Ask send_message_with_reply_cleanup not to remove the element from the
2403 * hash table - we're in the middle of a foreach; that would be unsafe.
2404 * Instead, return TRUE from this function so that it gets removed safely.
2406 send_message_with_reply_cleanup (task, FALSE);
2410 /* Called in GDBusWorker's thread - we must not block - without lock held */
2412 on_worker_closed (GDBusWorker *worker,
2413 gboolean remote_peer_vanished,
2417 GDBusConnection *connection;
2419 guint old_atomic_flags;
2421 G_LOCK (message_bus_lock);
2422 alive = g_hash_table_contains (alive_connections, user_data);
2425 G_UNLOCK (message_bus_lock);
2428 connection = G_DBUS_CONNECTION (user_data);
2429 g_object_ref (connection);
2430 G_UNLOCK (message_bus_lock);
2432 //g_debug ("in on_worker_closed: %s", error->message);
2434 CONNECTION_LOCK (connection);
2435 /* Even though this is atomic, we do it inside the lock to avoid breaking
2436 * assumptions in remove_match_rule(). We'd need the lock in a moment
2437 * anyway, so, no loss.
2439 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2441 if (!(old_atomic_flags & FLAG_CLOSED))
2443 g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2444 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2446 CONNECTION_UNLOCK (connection);
2448 g_object_unref (connection);
2451 /* ---------------------------------------------------------------------------------------------------- */
2453 /* Determines the biggest set of capabilities we can support on this
2456 * Called with the init_lock held.
2458 static GDBusCapabilityFlags
2459 get_offered_capabilities_max (GDBusConnection *connection)
2461 GDBusCapabilityFlags ret;
2462 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2464 if (G_IS_UNIX_CONNECTION (connection->stream))
2465 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2470 /* Called in a user thread, lock is not held */
2472 initable_init (GInitable *initable,
2473 GCancellable *cancellable,
2476 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2479 /* This method needs to be idempotent to work with the singleton
2480 * pattern. See the docs for g_initable_init(). We implement this by
2483 * Unfortunately we can't use the main lock since the on_worker_*()
2484 * callbacks above needs the lock during initialization (for message
2485 * bus connections we do a synchronous Hello() call on the bus).
2487 g_mutex_lock (&connection->init_lock);
2491 /* Make this a no-op if we're already initialized (successfully or
2494 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2496 ret = (connection->initialization_error == NULL);
2500 /* Because of init_lock, we can't get here twice in different threads */
2501 g_assert (connection->initialization_error == NULL);
2503 /* The user can pass multiple (but mutally exclusive) construct
2506 * - stream (of type GIOStream)
2507 * - address (of type gchar*)
2509 * At the end of the day we end up with a non-NULL GIOStream
2510 * object in connection->stream.
2512 if (connection->address != NULL)
2514 g_assert (connection->stream == NULL);
2516 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2517 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2519 g_set_error_literal (&connection->initialization_error,
2521 G_IO_ERROR_INVALID_ARGUMENT,
2522 _("Unsupported flags encountered when constructing a client-side connection"));
2526 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2527 NULL, /* TODO: out_guid */
2529 &connection->initialization_error);
2530 if (connection->stream == NULL)
2533 else if (connection->stream != NULL)
2539 g_assert_not_reached ();
2542 /* Authenticate the connection */
2543 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2545 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2546 g_assert (connection->guid != NULL);
2547 connection->auth = _g_dbus_auth_new (connection->stream);
2548 if (!_g_dbus_auth_run_server (connection->auth,
2549 connection->authentication_observer,
2551 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2552 get_offered_capabilities_max (connection),
2553 &connection->capabilities,
2554 &connection->credentials,
2556 &connection->initialization_error))
2559 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2561 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2562 g_assert (connection->guid == NULL);
2563 connection->auth = _g_dbus_auth_new (connection->stream);
2564 connection->guid = _g_dbus_auth_run_client (connection->auth,
2565 connection->authentication_observer,
2566 get_offered_capabilities_max (connection),
2567 &connection->capabilities,
2569 &connection->initialization_error);
2570 if (connection->guid == NULL)
2574 if (connection->authentication_observer != NULL)
2576 g_object_unref (connection->authentication_observer);
2577 connection->authentication_observer = NULL;
2580 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2582 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2585 /* We want all IO operations to be non-blocking since they happen in
2586 * the worker thread which is shared by _all_ connections.
2588 if (G_IS_SOCKET_CONNECTION (connection->stream))
2590 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2594 G_LOCK (message_bus_lock);
2595 if (alive_connections == NULL)
2596 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2597 g_hash_table_add (alive_connections, connection);
2598 G_UNLOCK (message_bus_lock);
2600 connection->worker = _g_dbus_worker_new (connection->stream,
2601 connection->capabilities,
2602 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2603 on_worker_message_received,
2604 on_worker_message_about_to_be_sent,
2608 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2609 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2611 GVariant *hello_result;
2613 /* we could lift this restriction by adding code in gdbusprivate.c */
2614 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2616 g_set_error_literal (&connection->initialization_error,
2619 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2623 hello_result = g_dbus_connection_call_sync (connection,
2624 "org.freedesktop.DBus", /* name */
2625 "/org/freedesktop/DBus", /* path */
2626 "org.freedesktop.DBus", /* interface */
2628 NULL, /* parameters */
2629 G_VARIANT_TYPE ("(s)"),
2630 CALL_FLAGS_INITIALIZING,
2632 NULL, /* TODO: cancellable */
2633 &connection->initialization_error);
2634 if (hello_result == NULL)
2637 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2638 g_variant_unref (hello_result);
2639 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2646 g_assert (connection->initialization_error != NULL);
2647 g_propagate_error (error, g_error_copy (connection->initialization_error));
2650 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2651 g_mutex_unlock (&connection->init_lock);
2657 initable_iface_init (GInitableIface *initable_iface)
2659 initable_iface->init = initable_init;
2662 /* ---------------------------------------------------------------------------------------------------- */
2665 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2670 /* ---------------------------------------------------------------------------------------------------- */
2673 * g_dbus_connection_new:
2674 * @stream: a #GIOStream
2675 * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2676 * @flags: flags describing how to make the connection
2677 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2678 * @cancellable: (nullable): a #GCancellable or %NULL
2679 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2680 * @user_data: the data to pass to @callback
2682 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2683 * with the end represented by @stream.
2685 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2686 * will be put into non-blocking mode.
2688 * The D-Bus connection will interact with @stream from a worker thread.
2689 * As a result, the caller should not interact with @stream after this
2690 * method has been called, except by calling g_object_unref() on it.
2692 * If @observer is not %NULL it may be used to control the
2693 * authentication process.
2695 * When the operation is finished, @callback will be invoked. You can
2696 * then call g_dbus_connection_new_finish() to get the result of the
2699 * This is an asynchronous failable constructor. See
2700 * g_dbus_connection_new_sync() for the synchronous
2706 g_dbus_connection_new (GIOStream *stream,
2708 GDBusConnectionFlags flags,
2709 GDBusAuthObserver *observer,
2710 GCancellable *cancellable,
2711 GAsyncReadyCallback callback,
2714 _g_dbus_initialize ();
2716 g_return_if_fail (G_IS_IO_STREAM (stream));
2718 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2726 "authentication-observer", observer,
2731 * g_dbus_connection_new_finish:
2732 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2733 * passed to g_dbus_connection_new().
2734 * @error: return location for error or %NULL
2736 * Finishes an operation started with g_dbus_connection_new().
2738 * Returns: a #GDBusConnection or %NULL if @error is set. Free
2739 * with g_object_unref().
2744 g_dbus_connection_new_finish (GAsyncResult *res,
2748 GObject *source_object;
2750 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2751 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2753 source_object = g_async_result_get_source_object (res);
2754 g_assert (source_object != NULL);
2755 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2758 g_object_unref (source_object);
2760 return G_DBUS_CONNECTION (object);
2766 * g_dbus_connection_new_sync:
2767 * @stream: a #GIOStream
2768 * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2769 * @flags: flags describing how to make the connection
2770 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2771 * @cancellable: (nullable): a #GCancellable or %NULL
2772 * @error: return location for error or %NULL
2774 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2775 * with the end represented by @stream.
2777 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2778 * will be put into non-blocking mode.
2780 * The D-Bus connection will interact with @stream from a worker thread.
2781 * As a result, the caller should not interact with @stream after this
2782 * method has been called, except by calling g_object_unref() on it.
2784 * If @observer is not %NULL it may be used to control the
2785 * authentication process.
2787 * This is a synchronous failable constructor. See
2788 * g_dbus_connection_new() for the asynchronous version.
2790 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2795 g_dbus_connection_new_sync (GIOStream *stream,
2797 GDBusConnectionFlags flags,
2798 GDBusAuthObserver *observer,
2799 GCancellable *cancellable,
2802 _g_dbus_initialize ();
2803 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2804 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2805 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2811 "authentication-observer", observer,
2815 /* ---------------------------------------------------------------------------------------------------- */
2818 * g_dbus_connection_new_for_address:
2819 * @address: a D-Bus address
2820 * @flags: flags describing how to make the connection
2821 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2822 * @cancellable: (nullable): a #GCancellable or %NULL
2823 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2824 * @user_data: the data to pass to @callback
2826 * Asynchronously connects and sets up a D-Bus client connection for
2827 * exchanging D-Bus messages with an endpoint specified by @address
2828 * which must be in the
2829 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2831 * This constructor can only be used to initiate client-side
2832 * connections - use g_dbus_connection_new() if you need to act as the
2833 * server. In particular, @flags cannot contain the
2834 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2835 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2837 * When the operation is finished, @callback will be invoked. You can
2838 * then call g_dbus_connection_new_for_address_finish() to get the result of
2841 * If @observer is not %NULL it may be used to control the
2842 * authentication process.
2844 * This is an asynchronous failable constructor. See
2845 * g_dbus_connection_new_for_address_sync() for the synchronous
2851 g_dbus_connection_new_for_address (const gchar *address,
2852 GDBusConnectionFlags flags,
2853 GDBusAuthObserver *observer,
2854 GCancellable *cancellable,
2855 GAsyncReadyCallback callback,
2858 _g_dbus_initialize ();
2860 g_return_if_fail (address != NULL);
2862 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2869 "authentication-observer", observer,
2874 * g_dbus_connection_new_for_address_finish:
2875 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2876 * to g_dbus_connection_new()
2877 * @error: return location for error or %NULL
2879 * Finishes an operation started with g_dbus_connection_new_for_address().
2881 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2887 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2891 GObject *source_object;
2893 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2894 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2896 source_object = g_async_result_get_source_object (res);
2897 g_assert (source_object != NULL);
2898 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2901 g_object_unref (source_object);
2903 return G_DBUS_CONNECTION (object);
2909 * g_dbus_connection_new_for_address_sync:
2910 * @address: a D-Bus address
2911 * @flags: flags describing how to make the connection
2912 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2913 * @cancellable: (nullable): a #GCancellable or %NULL
2914 * @error: return location for error or %NULL
2916 * Synchronously connects and sets up a D-Bus client connection for
2917 * exchanging D-Bus messages with an endpoint specified by @address
2918 * which must be in the
2919 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2921 * This constructor can only be used to initiate client-side
2922 * connections - use g_dbus_connection_new_sync() if you need to act
2923 * as the server. In particular, @flags cannot contain the
2924 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2925 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2927 * This is a synchronous failable constructor. See
2928 * g_dbus_connection_new_for_address() for the asynchronous version.
2930 * If @observer is not %NULL it may be used to control the
2931 * authentication process.
2933 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2939 g_dbus_connection_new_for_address_sync (const gchar *address,
2940 GDBusConnectionFlags flags,
2941 GDBusAuthObserver *observer,
2942 GCancellable *cancellable,
2945 _g_dbus_initialize ();
2947 g_return_val_if_fail (address != NULL, NULL);
2948 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2949 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2954 "authentication-observer", observer,
2958 /* ---------------------------------------------------------------------------------------------------- */
2961 * g_dbus_connection_set_exit_on_close:
2962 * @connection: a #GDBusConnection
2963 * @exit_on_close: whether the process should be terminated
2964 * when @connection is closed by the remote peer
2966 * Sets whether the process should be terminated when @connection is
2967 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2970 * Note that this function should be used with care. Most modern UNIX
2971 * desktops tie the notion of a user session with the session bus, and expect
2972 * all of a user's applications to quit when their bus connection goes away.
2973 * If you are setting @exit_on_close to %FALSE for the shared session
2974 * bus connection, you should make sure that your application exits
2975 * when the user session ends.
2980 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2981 gboolean exit_on_close)
2983 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2986 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2988 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2993 * g_dbus_connection_get_exit_on_close:
2994 * @connection: a #GDBusConnection
2996 * Gets whether the process is terminated when @connection is
2997 * closed by the remote peer. See
2998 * #GDBusConnection:exit-on-close for more details.
3000 * Returns: whether the process is terminated when @connection is
3001 * closed by the remote peer
3006 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3008 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3010 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3017 * g_dbus_connection_get_guid:
3018 * @connection: a #GDBusConnection
3020 * The GUID of the peer performing the role of server when
3021 * authenticating. See #GDBusConnection:guid for more details.
3023 * Returns: The GUID. Do not free this string, it is owned by
3029 g_dbus_connection_get_guid (GDBusConnection *connection)
3031 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3032 return connection->guid;
3036 * g_dbus_connection_get_unique_name:
3037 * @connection: a #GDBusConnection
3039 * Gets the unique name of @connection as assigned by the message
3040 * bus. This can also be used to figure out if @connection is a
3041 * message bus connection.
3043 * Returns: (nullable): the unique name or %NULL if @connection is not a message
3044 * bus connection. Do not free this string, it is owned by
3050 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3052 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3054 /* do not use g_return_val_if_fail(), we want the memory barrier */
3055 if (!check_initialized (connection))
3058 return connection->bus_unique_name;
3062 * g_dbus_connection_get_peer_credentials:
3063 * @connection: a #GDBusConnection
3065 * Gets the credentials of the authenticated peer. This will always
3066 * return %NULL unless @connection acted as a server
3067 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3068 * when set up and the client passed credentials as part of the
3069 * authentication process.
3071 * In a message bus setup, the message bus is always the server and
3072 * each application is a client. So this method will always return
3073 * %NULL for message bus clients.
3075 * Returns: (transfer none) (nullable): a #GCredentials or %NULL if not
3076 * available. Do not free this object, it is owned by @connection.
3081 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3083 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3085 /* do not use g_return_val_if_fail(), we want the memory barrier */
3086 if (!check_initialized (connection))
3089 return connection->credentials;
3092 /* ---------------------------------------------------------------------------------------------------- */
3094 static volatile guint _global_filter_id = 1;
3097 * g_dbus_connection_add_filter:
3098 * @connection: a #GDBusConnection
3099 * @filter_function: a filter function
3100 * @user_data: user data to pass to @filter_function
3101 * @user_data_free_func: function to free @user_data with when filter
3102 * is removed or %NULL
3104 * Adds a message filter. Filters are handlers that are run on all
3105 * incoming and outgoing messages, prior to standard dispatch. Filters
3106 * are run in the order that they were added. The same handler can be
3107 * added as a filter more than once, in which case it will be run more
3108 * than once. Filters added during a filter callback won't be run on
3109 * the message being processed. Filter functions are allowed to modify
3110 * and even drop messages.
3112 * Note that filters are run in a dedicated message handling thread so
3113 * they can't block and, generally, can't do anything but signal a
3114 * worker thread. Also note that filters are rarely needed - use API
3115 * such as g_dbus_connection_send_message_with_reply(),
3116 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3118 * If a filter consumes an incoming message the message is not
3119 * dispatched anywhere else - not even the standard dispatch machinery
3120 * (that API such as g_dbus_connection_signal_subscribe() and
3121 * g_dbus_connection_send_message_with_reply() relies on) will see the
3122 * message. Similarly, if a filter consumes an outgoing message, the
3123 * message will not be sent to the other peer.
3125 * If @user_data_free_func is non-%NULL, it will be called (in the
3126 * thread-default main context of the thread you are calling this
3127 * method from) at some point after @user_data is no longer
3128 * needed. (It is not guaranteed to be called synchronously when the
3129 * filter is removed, and may be called after @connection has been
3132 * Returns: a filter identifier that can be used with
3133 * g_dbus_connection_remove_filter()
3138 g_dbus_connection_add_filter (GDBusConnection *connection,
3139 GDBusMessageFilterFunction filter_function,
3141 GDestroyNotify user_data_free_func)
3145 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3146 g_return_val_if_fail (filter_function != NULL, 0);
3147 g_return_val_if_fail (check_initialized (connection), 0);
3149 CONNECTION_LOCK (connection);
3150 data = g_new0 (FilterData, 1);
3151 data->id = g_atomic_int_add (&_global_filter_id, 1); /* TODO: overflow etc. */
3152 data->ref_count = 1;
3153 data->filter_function = filter_function;
3154 data->user_data = user_data;
3155 data->user_data_free_func = user_data_free_func;
3156 data->context = g_main_context_ref_thread_default ();
3157 g_ptr_array_add (connection->filters, data);
3158 CONNECTION_UNLOCK (connection);
3163 /* only called from finalize(), removes all filters */
3165 purge_all_filters (GDBusConnection *connection)
3168 for (n = 0; n < connection->filters->len; n++)
3170 FilterData *data = connection->filters->pdata[n];
3172 call_destroy_notify (data->context,
3173 data->user_data_free_func,
3175 g_main_context_unref (data->context);
3181 * g_dbus_connection_remove_filter:
3182 * @connection: a #GDBusConnection
3183 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3187 * Note that since filters run in a different thread, there is a race
3188 * condition where it is possible that the filter will be running even
3189 * after calling g_dbus_connection_remove_filter(), so you cannot just
3190 * free data that the filter might be using. Instead, you should pass
3191 * a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
3192 * called when it is guaranteed that the data is no longer needed.
3197 g_dbus_connection_remove_filter (GDBusConnection *connection,
3202 FilterData *to_destroy;
3204 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3205 g_return_if_fail (check_initialized (connection));
3207 CONNECTION_LOCK (connection);
3210 for (n = 0; n < connection->filters->len; n++)
3212 FilterData *data = connection->filters->pdata[n];
3213 if (data->id == filter_id)
3216 g_ptr_array_remove_index (connection->filters, n);
3218 if (data->ref_count == 0)
3223 CONNECTION_UNLOCK (connection);
3225 /* do free without holding lock */
3226 if (to_destroy != NULL)
3228 if (to_destroy->user_data_free_func != NULL)
3229 to_destroy->user_data_free_func (to_destroy->user_data);
3230 g_main_context_unref (to_destroy->context);
3231 g_free (to_destroy);
3235 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3239 /* ---------------------------------------------------------------------------------------------------- */
3245 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3246 gchar *interface_name;
3250 GDBusSignalFlags flags;
3251 GArray *subscribers;
3256 GDBusSignalCallback callback;
3258 GDestroyNotify user_data_free_func;
3260 GMainContext *context;
3264 signal_data_free (SignalData *signal_data)
3266 g_free (signal_data->rule);
3267 g_free (signal_data->sender);
3268 g_free (signal_data->sender_unique_name);
3269 g_free (signal_data->interface_name);
3270 g_free (signal_data->member);
3271 g_free (signal_data->object_path);
3272 g_free (signal_data->arg0);
3273 g_array_free (signal_data->subscribers, TRUE);
3274 g_free (signal_data);
3278 args_to_rule (const gchar *sender,
3279 const gchar *interface_name,
3280 const gchar *member,
3281 const gchar *object_path,
3283 GDBusSignalFlags flags)
3287 rule = g_string_new ("type='signal'");
3288 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3289 g_string_prepend_c (rule, '-');
3291 g_string_append_printf (rule, ",sender='%s'", sender);
3292 if (interface_name != NULL)
3293 g_string_append_printf (rule, ",interface='%s'", interface_name);
3295 g_string_append_printf (rule, ",member='%s'", member);
3296 if (object_path != NULL)
3297 g_string_append_printf (rule, ",path='%s'", object_path);
3301 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3302 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3303 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3304 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3306 g_string_append_printf (rule, ",arg0='%s'", arg0);
3309 return g_string_free (rule, FALSE);
3312 static volatile guint _global_subscriber_id = 1;
3313 static volatile guint _global_registration_id = 1;
3314 static volatile guint _global_subtree_registration_id = 1;
3316 /* ---------------------------------------------------------------------------------------------------- */
3318 /* Called in a user thread, lock is held */
3320 add_match_rule (GDBusConnection *connection,
3321 const gchar *match_rule)
3324 GDBusMessage *message;
3326 if (match_rule[0] == '-')
3329 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3330 "/org/freedesktop/DBus", /* path */
3331 "org.freedesktop.DBus", /* interface */
3333 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3335 if (!g_dbus_connection_send_message_unlocked (connection,
3337 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3341 g_critical ("Error while sending AddMatch() message: %s", error->message);
3342 g_error_free (error);
3344 g_object_unref (message);
3347 /* ---------------------------------------------------------------------------------------------------- */
3349 /* Called in a user thread, lock is held */
3351 remove_match_rule (GDBusConnection *connection,
3352 const gchar *match_rule)
3355 GDBusMessage *message;
3357 if (match_rule[0] == '-')
3360 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3361 "/org/freedesktop/DBus", /* path */
3362 "org.freedesktop.DBus", /* interface */
3364 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3367 if (!g_dbus_connection_send_message_unlocked (connection,
3369 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3373 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3374 * critical; but we're holding the lock, and our caller checked whether
3375 * we were already closed, so we can't get that error.
3377 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3378 g_error_free (error);
3380 g_object_unref (message);
3383 /* ---------------------------------------------------------------------------------------------------- */
3386 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3388 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3389 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3390 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3391 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3392 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3395 /* ---------------------------------------------------------------------------------------------------- */
3398 * g_dbus_connection_signal_subscribe:
3399 * @connection: a #GDBusConnection
3400 * @sender: (nullable): sender name to match on (unique or well-known name)
3401 * or %NULL to listen from all senders
3402 * @interface_name: (nullable): D-Bus interface name to match on or %NULL to
3403 * match on all interfaces
3404 * @member: (nullable): D-Bus signal name to match on or %NULL to match on
3406 * @object_path: (nullable): object path to match on or %NULL to match on
3408 * @arg0: (nullable): contents of first string argument to match on or %NULL
3409 * to match on all kinds of arguments
3410 * @flags: #GDBusSignalFlags describing how arg0 is used in subscribing to the
3412 * @callback: callback to invoke when there is a signal matching the requested data
3413 * @user_data: user data to pass to @callback
3414 * @user_data_free_func: (nullable): function to free @user_data with when
3415 * subscription is removed or %NULL
3417 * Subscribes to signals on @connection and invokes @callback with a whenever
3418 * the signal is received. Note that @callback will be invoked in the
3419 * [thread-default main context][g-main-context-push-thread-default]
3420 * of the thread you are calling this method from.
3422 * If @connection is not a message bus connection, @sender must be
3425 * If @sender is a well-known name note that @callback is invoked with
3426 * the unique name for the owner of @sender, not the well-known name
3427 * as one would expect. This is because the message bus rewrites the
3428 * name. As such, to avoid certain race conditions, users should be
3429 * tracking the name owner of the well-known name and use that when
3430 * processing the received signal.
3432 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3433 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3434 * interpreted as part of a namespace or path. The first argument
3435 * of a signal is matched against that part as specified by D-Bus.
3437 * If @user_data_free_func is non-%NULL, it will be called (in the
3438 * thread-default main context of the thread you are calling this
3439 * method from) at some point after @user_data is no longer
3440 * needed. (It is not guaranteed to be called synchronously when the
3441 * signal is unsubscribed from, and may be called after @connection
3442 * has been destroyed.)
3444 * The returned subscription identifier is an opaque value which is guaranteed
3447 * This function can never fail.
3449 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3454 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3455 const gchar *sender,
3456 const gchar *interface_name,
3457 const gchar *member,
3458 const gchar *object_path,
3460 GDBusSignalFlags flags,
3461 GDBusSignalCallback callback,
3463 GDestroyNotify user_data_free_func)
3466 SignalData *signal_data;
3467 SignalSubscriber subscriber;
3468 GPtrArray *signal_data_array;
3469 const gchar *sender_unique_name;
3471 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3472 * an OOM condition. We might want to change that but that would involve making
3473 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3474 * handle that. And there's really no sensible way of handling this short of retrying
3475 * to add the match rule... and then there's the little thing that, hey, maybe there's
3476 * a reason the bus in an OOM condition.
3478 * Doable, but not really sure it's worth it...
3481 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3482 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3483 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3484 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3485 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3486 g_return_val_if_fail (callback != NULL, 0);
3487 g_return_val_if_fail (check_initialized (connection), 0);
3488 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3489 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3491 CONNECTION_LOCK (connection);
3493 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3494 * with a '-' character to prefix the rule (which will otherwise be
3497 * This allows us to hash the rule and do our lifecycle tracking in
3498 * the usual way, but the '-' prevents the match rule from ever
3499 * actually being send to the bus (either for add or remove).
3501 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3503 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3504 sender_unique_name = sender;
3506 sender_unique_name = "";
3508 subscriber.callback = callback;
3509 subscriber.user_data = user_data;
3510 subscriber.user_data_free_func = user_data_free_func;
3511 subscriber.id = g_atomic_int_add (&_global_subscriber_id, 1); /* TODO: overflow etc. */
3512 subscriber.context = g_main_context_ref_thread_default ();
3514 /* see if we've already have this rule */
3515 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3516 if (signal_data != NULL)
3518 g_array_append_val (signal_data->subscribers, subscriber);
3523 signal_data = g_new0 (SignalData, 1);
3524 signal_data->rule = rule;
3525 signal_data->sender = g_strdup (sender);
3526 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3527 signal_data->interface_name = g_strdup (interface_name);
3528 signal_data->member = g_strdup (member);
3529 signal_data->object_path = g_strdup (object_path);
3530 signal_data->arg0 = g_strdup (arg0);
3531 signal_data->flags = flags;
3532 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3533 g_array_append_val (signal_data->subscribers, subscriber);
3535 g_hash_table_insert (connection->map_rule_to_signal_data,
3539 /* Add the match rule to the bus...
3541 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3542 * always send such messages to us.
3544 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3546 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3547 add_match_rule (connection, signal_data->rule);
3550 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3551 signal_data->sender_unique_name);
3552 if (signal_data_array == NULL)
3554 signal_data_array = g_ptr_array_new ();
3555 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3556 g_strdup (signal_data->sender_unique_name),
3559 g_ptr_array_add (signal_data_array, signal_data);
3562 g_hash_table_insert (connection->map_id_to_signal_data,
3563 GUINT_TO_POINTER (subscriber.id),
3566 CONNECTION_UNLOCK (connection);
3568 return subscriber.id;
3571 /* ---------------------------------------------------------------------------------------------------- */
3573 /* called in any thread */
3574 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3576 unsubscribe_id_internal (GDBusConnection *connection,
3577 guint subscription_id,
3578 GArray *out_removed_subscribers)
3580 SignalData *signal_data;
3581 GPtrArray *signal_data_array;
3584 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3585 GUINT_TO_POINTER (subscription_id));
3586 if (signal_data == NULL)
3588 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3592 for (n = 0; n < signal_data->subscribers->len; n++)
3594 SignalSubscriber *subscriber;
3596 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3597 if (subscriber->id != subscription_id)
3600 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3601 GUINT_TO_POINTER (subscription_id)));
3602 g_array_append_val (out_removed_subscribers, *subscriber);
3603 g_array_remove_index (signal_data->subscribers, n);
3605 if (signal_data->subscribers->len == 0)
3607 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3609 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3610 signal_data->sender_unique_name);
3611 g_warn_if_fail (signal_data_array != NULL);
3612 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3614 if (signal_data_array->len == 0)
3616 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3617 signal_data->sender_unique_name));
3620 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3621 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3622 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3623 !g_dbus_connection_is_closed (connection) &&
3624 !connection->finalizing)
3626 /* The check for g_dbus_connection_is_closed() means that
3627 * sending the RemoveMatch message can't fail with
3628 * G_IO_ERROR_CLOSED, because we're holding the lock,
3629 * so on_worker_closed() can't happen between the check we just
3630 * did, and releasing the lock later.
3632 remove_match_rule (connection, signal_data->rule);
3635 signal_data_free (signal_data);
3641 g_assert_not_reached ();
3648 * g_dbus_connection_signal_unsubscribe:
3649 * @connection: a #GDBusConnection
3650 * @subscription_id: a subscription id obtained from
3651 * g_dbus_connection_signal_subscribe()
3653 * Unsubscribes from signals.
3658 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3659 guint subscription_id)
3661 GArray *subscribers;
3664 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3665 g_return_if_fail (check_initialized (connection));
3667 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3669 CONNECTION_LOCK (connection);
3670 unsubscribe_id_internal (connection,
3673 CONNECTION_UNLOCK (connection);
3676 g_assert (subscribers->len == 0 || subscribers->len == 1);
3678 /* call GDestroyNotify without lock held */
3679 for (n = 0; n < subscribers->len; n++)
3681 SignalSubscriber *subscriber;
3682 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3683 call_destroy_notify (subscriber->context,
3684 subscriber->user_data_free_func,
3685 subscriber->user_data);
3686 g_main_context_unref (subscriber->context);
3689 g_array_free (subscribers, TRUE);
3692 /* ---------------------------------------------------------------------------------------------------- */
3696 guint subscription_id;
3697 GDBusSignalCallback callback;
3699 GDBusMessage *message;
3700 GDBusConnection *connection;
3701 const gchar *sender;
3703 const gchar *interface;
3704 const gchar *member;
3707 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3711 emit_signal_instance_in_idle_cb (gpointer data)
3713 SignalInstance *signal_instance = data;
3714 GVariant *parameters;
3715 gboolean has_subscription;
3717 parameters = g_dbus_message_get_body (signal_instance->message);
3718 if (parameters == NULL)
3720 parameters = g_variant_new ("()");
3721 g_variant_ref_sink (parameters);
3725 g_variant_ref_sink (parameters);
3729 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3730 signal_instance->subscription_id,
3731 signal_instance->sender,
3732 signal_instance->path,
3733 signal_instance->interface,
3734 signal_instance->member,
3735 g_variant_print (parameters, TRUE));
3738 /* Careful here, don't do the callback if we no longer has the subscription */
3739 CONNECTION_LOCK (signal_instance->connection);
3740 has_subscription = FALSE;
3741 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3742 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3743 has_subscription = TRUE;
3744 CONNECTION_UNLOCK (signal_instance->connection);
3746 if (has_subscription)
3747 signal_instance->callback (signal_instance->connection,
3748 signal_instance->sender,
3749 signal_instance->path,
3750 signal_instance->interface,
3751 signal_instance->member,
3753 signal_instance->user_data);
3755 g_variant_unref (parameters);
3761 signal_instance_free (SignalInstance *signal_instance)
3763 g_object_unref (signal_instance->message);
3764 g_object_unref (signal_instance->connection);
3765 g_free (signal_instance);
3769 namespace_rule_matches (const gchar *namespace,
3775 len_namespace = strlen (namespace);
3776 len_name = strlen (name);
3778 if (len_name < len_namespace)
3781 if (memcmp (namespace, name, len_namespace) != 0)
3784 return len_namespace == len_name || name[len_namespace] == '.';
3788 path_rule_matches (const gchar *path_a,
3789 const gchar *path_b)
3793 len_a = strlen (path_a);
3794 len_b = strlen (path_b);
3796 if (len_a < len_b && (len_a == 0 || path_a[len_a - 1] != '/'))
3799 if (len_b < len_a && (len_b == 0 || path_b[len_b - 1] != '/'))
3802 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3805 /* called in GDBusWorker thread WITH lock held */
3807 schedule_callbacks (GDBusConnection *connection,
3808 GPtrArray *signal_data_array,
3809 GDBusMessage *message,
3810 const gchar *sender)
3813 const gchar *interface;
3814 const gchar *member;
3823 interface = g_dbus_message_get_interface (message);
3824 member = g_dbus_message_get_member (message);
3825 path = g_dbus_message_get_path (message);
3826 arg0 = g_dbus_message_get_arg0 (message);
3829 g_print ("In schedule_callbacks:\n"
3831 " interface = '%s'\n"
3842 /* TODO: if this is slow, then we can change signal_data_array into
3843 * map_object_path_to_signal_data_array or something.
3845 for (n = 0; n < signal_data_array->len; n++)
3847 SignalData *signal_data = signal_data_array->pdata[n];
3849 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3852 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3855 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3858 if (signal_data->arg0 != NULL)
3863 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3865 if (!namespace_rule_matches (signal_data->arg0, arg0))
3868 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3870 if (!path_rule_matches (signal_data->arg0, arg0))
3873 else if (!g_str_equal (signal_data->arg0, arg0))
3877 for (m = 0; m < signal_data->subscribers->len; m++)
3879 SignalSubscriber *subscriber;
3880 GSource *idle_source;
3881 SignalInstance *signal_instance;
3883 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3885 signal_instance = g_new0 (SignalInstance, 1);
3886 signal_instance->subscription_id = subscriber->id;
3887 signal_instance->callback = subscriber->callback;
3888 signal_instance->user_data = subscriber->user_data;
3889 signal_instance->message = g_object_ref (message);
3890 signal_instance->connection = g_object_ref (connection);
3891 signal_instance->sender = sender;
3892 signal_instance->path = path;
3893 signal_instance->interface = interface;
3894 signal_instance->member = member;
3896 idle_source = g_idle_source_new ();
3897 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3898 g_source_set_callback (idle_source,
3899 emit_signal_instance_in_idle_cb,
3901 (GDestroyNotify) signal_instance_free);
3902 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3903 g_source_attach (idle_source, subscriber->context);
3904 g_source_unref (idle_source);
3909 /* called in GDBusWorker thread with lock held */
3911 distribute_signals (GDBusConnection *connection,
3912 GDBusMessage *message)
3914 GPtrArray *signal_data_array;
3915 const gchar *sender;
3917 sender = g_dbus_message_get_sender (message);
3919 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3921 _g_dbus_debug_print_lock ();
3922 g_print ("========================================================================\n"
3923 "GDBus-debug:Signal:\n"
3924 " <<<< RECEIVED SIGNAL %s.%s\n"
3926 " sent by name %s\n",
3927 g_dbus_message_get_interface (message),
3928 g_dbus_message_get_member (message),
3929 g_dbus_message_get_path (message),
3930 sender != NULL ? sender : "(none)");
3931 _g_dbus_debug_print_unlock ();
3934 /* collect subscribers that match on sender */
3937 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3938 if (signal_data_array != NULL)
3939 schedule_callbacks (connection, signal_data_array, message, sender);
3942 /* collect subscribers not matching on sender */
3943 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3944 if (signal_data_array != NULL)
3945 schedule_callbacks (connection, signal_data_array, message, sender);
3948 /* ---------------------------------------------------------------------------------------------------- */
3950 /* only called from finalize(), removes all subscriptions */
3952 purge_all_signal_subscriptions (GDBusConnection *connection)
3954 GHashTableIter iter;
3957 GArray *subscribers;
3960 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3961 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3962 while (g_hash_table_iter_next (&iter, &key, NULL))
3964 guint subscription_id = GPOINTER_TO_UINT (key);
3965 g_array_append_val (ids, subscription_id);
3968 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3969 for (n = 0; n < ids->len; n++)
3971 guint subscription_id = g_array_index (ids, guint, n);
3972 unsubscribe_id_internal (connection,
3976 g_array_free (ids, TRUE);
3978 /* call GDestroyNotify without lock held */
3979 for (n = 0; n < subscribers->len; n++)
3981 SignalSubscriber *subscriber;
3982 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3983 call_destroy_notify (subscriber->context,
3984 subscriber->user_data_free_func,
3985 subscriber->user_data);
3986 g_main_context_unref (subscriber->context);
3989 g_array_free (subscribers, TRUE);
3992 /* ---------------------------------------------------------------------------------------------------- */
3994 static GDBusInterfaceVTable *
3995 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3997 /* Don't waste memory by copying padding - remember to update this
3998 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4000 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4004 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4009 /* ---------------------------------------------------------------------------------------------------- */
4011 static GDBusSubtreeVTable *
4012 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4014 /* Don't waste memory by copying padding - remember to update this
4015 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4017 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4021 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4026 /* ---------------------------------------------------------------------------------------------------- */
4028 struct ExportedObject
4031 GDBusConnection *connection;
4033 /* maps gchar* -> ExportedInterface* */
4034 GHashTable *map_if_name_to_ei;
4037 /* only called with lock held */
4039 exported_object_free (ExportedObject *eo)
4041 g_free (eo->object_path);
4042 g_hash_table_unref (eo->map_if_name_to_ei);
4051 gchar *interface_name;
4052 GDBusInterfaceVTable *vtable;
4053 GDBusInterfaceInfo *interface_info;
4055 GMainContext *context;
4057 GDestroyNotify user_data_free_func;
4058 } ExportedInterface;
4060 /* called with lock held */
4062 exported_interface_free (ExportedInterface *ei)
4064 g_dbus_interface_info_cache_release (ei->interface_info);
4065 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4067 call_destroy_notify (ei->context,
4068 ei->user_data_free_func,
4071 g_main_context_unref (ei->context);
4073 g_free (ei->interface_name);
4074 _g_dbus_interface_vtable_free (ei->vtable);
4078 /* ---------------------------------------------------------------------------------------------------- */
4080 /* Convenience function to check if @registration_id (if not zero) or
4081 * @subtree_registration_id (if not zero) has been unregistered. If
4082 * so, returns %TRUE.
4084 * May be called by any thread. Caller must *not* hold lock.
4087 has_object_been_unregistered (GDBusConnection *connection,
4088 guint registration_id,
4089 guint subtree_registration_id)
4093 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4097 CONNECTION_LOCK (connection);
4098 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4099 GUINT_TO_POINTER (registration_id)) == NULL)
4103 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4104 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4108 CONNECTION_UNLOCK (connection);
4113 /* ---------------------------------------------------------------------------------------------------- */
4117 GDBusConnection *connection;
4118 GDBusMessage *message;
4120 const gchar *property_name;
4121 const GDBusInterfaceVTable *vtable;
4122 GDBusInterfaceInfo *interface_info;
4123 const GDBusPropertyInfo *property_info;
4124 guint registration_id;
4125 guint subtree_registration_id;
4129 property_data_free (PropertyData *data)
4131 g_object_unref (data->connection);
4132 g_object_unref (data->message);
4136 /* called in thread where object was registered - no locks held */
4138 invoke_get_property_in_idle_cb (gpointer _data)
4140 PropertyData *data = _data;
4143 GDBusMessage *reply;
4145 if (has_object_been_unregistered (data->connection,
4146 data->registration_id,
4147 data->subtree_registration_id))
4149 reply = g_dbus_message_new_method_error (data->message,
4150 "org.freedesktop.DBus.Error.UnknownMethod",
4151 _("No such interface āorg.freedesktop.DBus.Propertiesā on object at path %s"),
4152 g_dbus_message_get_path (data->message));
4153 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4154 g_object_unref (reply);
4159 value = data->vtable->get_property (data->connection,
4160 g_dbus_message_get_sender (data->message),
4161 g_dbus_message_get_path (data->message),
4162 data->interface_info->name,
4163 data->property_name,
4170 g_assert_no_error (error);
4172 g_variant_take_ref (value);
4173 reply = g_dbus_message_new_method_reply (data->message);
4174 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4175 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4176 g_variant_unref (value);
4177 g_object_unref (reply);
4181 gchar *dbus_error_name;
4182 g_assert (error != NULL);
4183 dbus_error_name = g_dbus_error_encode_gerror (error);
4184 reply = g_dbus_message_new_method_error_literal (data->message,
4187 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4188 g_free (dbus_error_name);
4189 g_error_free (error);
4190 g_object_unref (reply);
4197 /* called in thread where object was registered - no locks held */
4199 invoke_set_property_in_idle_cb (gpointer _data)
4201 PropertyData *data = _data;
4203 GDBusMessage *reply;
4209 g_variant_get (g_dbus_message_get_body (data->message),
4215 if (!data->vtable->set_property (data->connection,
4216 g_dbus_message_get_sender (data->message),
4217 g_dbus_message_get_path (data->message),
4218 data->interface_info->name,
4219 data->property_name,
4224 gchar *dbus_error_name;
4225 g_assert (error != NULL);
4226 dbus_error_name = g_dbus_error_encode_gerror (error);
4227 reply = g_dbus_message_new_method_error_literal (data->message,
4230 g_free (dbus_error_name);
4231 g_error_free (error);
4235 reply = g_dbus_message_new_method_reply (data->message);
4238 g_assert (reply != NULL);
4239 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4240 g_object_unref (reply);
4241 g_variant_unref (value);
4246 /* called in any thread with connection's lock held */
4248 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4249 GDBusMessage *message,
4250 guint registration_id,
4251 guint subtree_registration_id,
4253 GDBusInterfaceInfo *interface_info,
4254 const GDBusInterfaceVTable *vtable,
4255 GMainContext *main_context,
4259 const char *interface_name;
4260 const char *property_name;
4261 const GDBusPropertyInfo *property_info;
4262 GSource *idle_source;
4263 PropertyData *property_data;
4264 GDBusMessage *reply;
4269 g_variant_get (g_dbus_message_get_body (message),
4274 g_variant_get (g_dbus_message_get_body (message),
4283 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4285 property_info = NULL;
4287 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4288 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4289 if (property_info == NULL)
4291 reply = g_dbus_message_new_method_error (message,
4292 "org.freedesktop.DBus.Error.InvalidArgs",
4293 _("No such property ā%sā"),
4295 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4296 g_object_unref (reply);
4301 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4303 reply = g_dbus_message_new_method_error (message,
4304 "org.freedesktop.DBus.Error.InvalidArgs",
4305 _("Property ā%sā is not readable"),
4307 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4308 g_object_unref (reply);
4312 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4314 reply = g_dbus_message_new_method_error (message,
4315 "org.freedesktop.DBus.Error.InvalidArgs",
4316 _("Property ā%sā is not writable"),
4318 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4319 g_object_unref (reply);
4328 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4329 * of the given value is wrong
4331 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4332 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4334 reply = g_dbus_message_new_method_error (message,
4335 "org.freedesktop.DBus.Error.InvalidArgs",
4336 _("Error setting property ā%sā: Expected type ā%sā but got ā%sā"),
4337 property_name, property_info->signature,
4338 g_variant_get_type_string (value));
4339 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4340 g_variant_unref (value);
4341 g_object_unref (reply);
4346 g_variant_unref (value);
4349 /* If the vtable pointer for get_property() resp. set_property() is
4350 * NULL then dispatch the call via the method_call() handler.
4354 if (vtable->get_property == NULL)
4356 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4357 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4358 vtable, main_context, user_data);
4365 if (vtable->set_property == NULL)
4367 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4368 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4369 vtable, main_context, user_data);
4375 /* ok, got the property info - call user code in an idle handler */
4376 property_data = g_new0 (PropertyData, 1);
4377 property_data->connection = g_object_ref (connection);
4378 property_data->message = g_object_ref (message);
4379 property_data->user_data = user_data;
4380 property_data->property_name = property_name;
4381 property_data->vtable = vtable;
4382 property_data->interface_info = interface_info;
4383 property_data->property_info = property_info;
4384 property_data->registration_id = registration_id;
4385 property_data->subtree_registration_id = subtree_registration_id;
4387 idle_source = g_idle_source_new ();
4388 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4389 g_source_set_callback (idle_source,
4390 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4392 (GDestroyNotify) property_data_free);
4394 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4396 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4397 g_source_attach (idle_source, main_context);
4398 g_source_unref (idle_source);
4406 /* called in GDBusWorker thread with connection's lock held */
4408 handle_getset_property (GDBusConnection *connection,
4410 GDBusMessage *message,
4413 ExportedInterface *ei;
4415 const char *interface_name;
4416 const char *property_name;
4421 g_variant_get (g_dbus_message_get_body (message),
4426 g_variant_get (g_dbus_message_get_body (message),
4432 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4433 * no such interface registered
4435 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4438 GDBusMessage *reply;
4439 reply = g_dbus_message_new_method_error (message,
4440 "org.freedesktop.DBus.Error.InvalidArgs",
4441 _("No such interface ā%sā"),
4443 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4444 g_object_unref (reply);
4449 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4462 /* ---------------------------------------------------------------------------------------------------- */
4466 GDBusConnection *connection;
4467 GDBusMessage *message;
4469 const GDBusInterfaceVTable *vtable;
4470 GDBusInterfaceInfo *interface_info;
4471 guint registration_id;
4472 guint subtree_registration_id;
4473 } PropertyGetAllData;
4476 property_get_all_data_free (PropertyData *data)
4478 g_object_unref (data->connection);
4479 g_object_unref (data->message);
4483 /* called in thread where object was registered - no locks held */
4485 invoke_get_all_properties_in_idle_cb (gpointer _data)
4487 PropertyGetAllData *data = _data;
4488 GVariantBuilder builder;
4489 GDBusMessage *reply;
4492 if (has_object_been_unregistered (data->connection,
4493 data->registration_id,
4494 data->subtree_registration_id))
4496 reply = g_dbus_message_new_method_error (data->message,
4497 "org.freedesktop.DBus.Error.UnknownMethod",
4498 _("No such interface āorg.freedesktop.DBus.Propertiesā on object at path %s"),
4499 g_dbus_message_get_path (data->message));
4500 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4501 g_object_unref (reply);
4505 /* TODO: Right now we never fail this call - we just omit values if
4506 * a get_property() call is failing.
4508 * We could fail the whole call if just a single get_property() call
4509 * returns an error. We need clarification in the D-Bus spec about this.
4511 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4512 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4513 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4515 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4518 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4521 value = data->vtable->get_property (data->connection,
4522 g_dbus_message_get_sender (data->message),
4523 g_dbus_message_get_path (data->message),
4524 data->interface_info->name,
4525 property_info->name,
4532 g_variant_take_ref (value);
4533 g_variant_builder_add (&builder,
4535 property_info->name,
4537 g_variant_unref (value);
4539 g_variant_builder_close (&builder);
4541 reply = g_dbus_message_new_method_reply (data->message);
4542 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4543 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4544 g_object_unref (reply);
4551 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4555 if (!interface_info->properties)
4558 for (i = 0; interface_info->properties[i]; i++)
4559 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4565 /* called in any thread with connection's lock held */
4567 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4568 GDBusMessage *message,
4569 guint registration_id,
4570 guint subtree_registration_id,
4571 GDBusInterfaceInfo *interface_info,
4572 const GDBusInterfaceVTable *vtable,
4573 GMainContext *main_context,
4577 GSource *idle_source;
4578 PropertyGetAllData *property_get_all_data;
4585 /* If the vtable pointer for get_property() is NULL but we have a
4586 * non-zero number of readable properties, then dispatch the call via
4587 * the method_call() handler.
4589 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4591 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4592 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4593 vtable, main_context, user_data);
4598 /* ok, got the property info - call user in an idle handler */
4599 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4600 property_get_all_data->connection = g_object_ref (connection);
4601 property_get_all_data->message = g_object_ref (message);
4602 property_get_all_data->user_data = user_data;
4603 property_get_all_data->vtable = vtable;
4604 property_get_all_data->interface_info = interface_info;
4605 property_get_all_data->registration_id = registration_id;
4606 property_get_all_data->subtree_registration_id = subtree_registration_id;
4608 idle_source = g_idle_source_new ();
4609 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4610 g_source_set_callback (idle_source,
4611 invoke_get_all_properties_in_idle_cb,
4612 property_get_all_data,
4613 (GDestroyNotify) property_get_all_data_free);
4614 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4615 g_source_attach (idle_source, main_context);
4616 g_source_unref (idle_source);
4624 /* called in GDBusWorker thread with connection's lock held */
4626 handle_get_all_properties (GDBusConnection *connection,
4628 GDBusMessage *message)
4630 ExportedInterface *ei;
4632 const char *interface_name;
4636 g_variant_get (g_dbus_message_get_body (message),
4640 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4641 * no such interface registered
4643 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4646 GDBusMessage *reply;
4647 reply = g_dbus_message_new_method_error (message,
4648 "org.freedesktop.DBus.Error.InvalidArgs",
4649 _("No such interface ā%sā"),
4651 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4652 g_object_unref (reply);
4657 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4669 /* ---------------------------------------------------------------------------------------------------- */
4671 static const gchar introspect_header[] =
4672 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4673 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4674 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4677 static const gchar introspect_tail[] =
4680 static const gchar introspect_properties_interface[] =
4681 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4682 " <method name=\"Get\">\n"
4683 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4684 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4685 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4687 " <method name=\"GetAll\">\n"
4688 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4689 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4691 " <method name=\"Set\">\n"
4692 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4693 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4694 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4696 " <signal name=\"PropertiesChanged\">\n"
4697 " <arg type=\"s\" name=\"interface_name\"/>\n"
4698 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4699 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4703 static const gchar introspect_introspectable_interface[] =
4704 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4705 " <method name=\"Introspect\">\n"
4706 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4709 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4710 " <method name=\"Ping\"/>\n"
4711 " <method name=\"GetMachineId\">\n"
4712 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4717 introspect_append_header (GString *s)
4719 g_string_append (s, introspect_header);
4723 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4725 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4731 begin = object_path + path_len;
4732 end = strchr (begin, '/');
4734 s = g_strndup (begin, end - begin);
4736 s = g_strdup (begin);
4738 if (!g_hash_table_contains (set, s))
4739 g_hash_table_add (set, s);
4745 /* TODO: we want a nicer public interface for this */
4746 /* called in any thread with connection's lock held */
4748 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4753 GHashTableIter hash_iter;
4754 const gchar *object_path;
4760 CONNECTION_ENSURE_LOCK (connection);
4762 path_len = strlen (path);
4766 set = g_hash_table_new (g_str_hash, g_str_equal);
4768 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4769 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4770 maybe_add_path (path, path_len, object_path, set);
4772 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4773 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4774 maybe_add_path (path, path_len, object_path, set);
4776 p = g_ptr_array_new ();
4777 keys = g_hash_table_get_keys (set);
4778 for (l = keys; l != NULL; l = l->next)
4779 g_ptr_array_add (p, l->data);
4780 g_hash_table_unref (set);
4783 g_ptr_array_add (p, NULL);
4784 ret = (gchar **) g_ptr_array_free (p, FALSE);
4788 /* called in any thread with connection's lock not held */
4790 g_dbus_connection_list_registered (GDBusConnection *connection,
4794 CONNECTION_LOCK (connection);
4795 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4796 CONNECTION_UNLOCK (connection);
4800 /* called in GDBusWorker thread with connection's lock held */
4802 handle_introspect (GDBusConnection *connection,
4804 GDBusMessage *message)
4808 GDBusMessage *reply;
4809 GHashTableIter hash_iter;
4810 ExportedInterface *ei;
4813 /* first the header with the standard interfaces */
4814 s = g_string_sized_new (sizeof (introspect_header) +
4815 sizeof (introspect_properties_interface) +
4816 sizeof (introspect_introspectable_interface) +
4817 sizeof (introspect_tail));
4818 introspect_append_header (s);
4819 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4820 "org.freedesktop.DBus.Properties"))
4821 g_string_append (s, introspect_properties_interface);
4823 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4824 "org.freedesktop.DBus.Introspectable"))
4825 g_string_append (s, introspect_introspectable_interface);
4827 /* then include the registered interfaces */
4828 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4829 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4830 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4832 /* finally include nodes registered below us */
4833 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4834 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4835 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4836 g_strfreev (registered);
4837 g_string_append (s, introspect_tail);
4839 reply = g_dbus_message_new_method_reply (message);
4840 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4841 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4842 g_object_unref (reply);
4843 g_string_free (s, TRUE);
4848 /* called in thread where object was registered - no locks held */
4850 call_in_idle_cb (gpointer user_data)
4852 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4853 GDBusInterfaceVTable *vtable;
4854 guint registration_id;
4855 guint subtree_registration_id;
4857 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4858 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4860 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4862 subtree_registration_id))
4864 GDBusMessage *reply;
4865 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4866 "org.freedesktop.DBus.Error.UnknownMethod",
4867 _("No such interface ā%sā on object at path %s"),
4868 g_dbus_method_invocation_get_interface_name (invocation),
4869 g_dbus_method_invocation_get_object_path (invocation));
4870 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4871 g_object_unref (reply);
4875 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4876 g_assert (vtable != NULL && vtable->method_call != NULL);
4878 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4879 g_dbus_method_invocation_get_sender (invocation),
4880 g_dbus_method_invocation_get_object_path (invocation),
4881 g_dbus_method_invocation_get_interface_name (invocation),
4882 g_dbus_method_invocation_get_method_name (invocation),
4883 g_dbus_method_invocation_get_parameters (invocation),
4884 g_object_ref (invocation),
4885 g_dbus_method_invocation_get_user_data (invocation));
4891 /* called in GDBusWorker thread with connection's lock held */
4893 schedule_method_call (GDBusConnection *connection,
4894 GDBusMessage *message,
4895 guint registration_id,
4896 guint subtree_registration_id,
4897 const GDBusInterfaceInfo *interface_info,
4898 const GDBusMethodInfo *method_info,
4899 const GDBusPropertyInfo *property_info,
4900 GVariant *parameters,
4901 const GDBusInterfaceVTable *vtable,
4902 GMainContext *main_context,
4905 GDBusMethodInvocation *invocation;
4906 GSource *idle_source;
4908 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4909 g_dbus_message_get_path (message),
4910 g_dbus_message_get_interface (message),
4911 g_dbus_message_get_member (message),
4919 /* TODO: would be nicer with a real MethodData like we already
4920 * have PropertyData and PropertyGetAllData... */
4921 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4922 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4923 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4925 idle_source = g_idle_source_new ();
4926 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4927 g_source_set_callback (idle_source,
4931 g_source_set_name (idle_source, "[gio, " __FILE__ "] call_in_idle_cb");
4932 g_source_attach (idle_source, main_context);
4933 g_source_unref (idle_source);
4936 /* called in GDBusWorker thread with connection's lock held */
4938 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4939 GDBusMessage *message,
4940 guint registration_id,
4941 guint subtree_registration_id,
4942 GDBusInterfaceInfo *interface_info,
4943 const GDBusInterfaceVTable *vtable,
4944 GMainContext *main_context,
4947 GDBusMethodInfo *method_info;
4948 GDBusMessage *reply;
4949 GVariant *parameters;
4951 GVariantType *in_type;
4955 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4956 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4958 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4959 * error to the caller
4961 if (method_info == NULL)
4963 reply = g_dbus_message_new_method_error (message,
4964 "org.freedesktop.DBus.Error.UnknownMethod",
4965 _("No such method ā%sā"),
4966 g_dbus_message_get_member (message));
4967 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4968 g_object_unref (reply);
4973 parameters = g_dbus_message_get_body (message);
4974 if (parameters == NULL)
4976 parameters = g_variant_new ("()");
4977 g_variant_ref_sink (parameters);
4981 g_variant_ref (parameters);
4984 /* Check that the incoming args are of the right type - if they are not, return
4985 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4987 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4988 if (!g_variant_is_of_type (parameters, in_type))
4992 type_string = g_variant_type_dup_string (in_type);
4994 reply = g_dbus_message_new_method_error (message,
4995 "org.freedesktop.DBus.Error.InvalidArgs",
4996 _("Type of message, ā%sā, does not match expected type ā%sā"),
4997 g_variant_get_type_string (parameters),
4999 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5000 g_variant_type_free (in_type);
5001 g_variant_unref (parameters);
5002 g_object_unref (reply);
5003 g_free (type_string);
5007 g_variant_type_free (in_type);
5009 /* schedule the call in idle */
5010 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5011 interface_info, method_info, NULL, parameters,
5012 vtable, main_context, user_data);
5013 g_variant_unref (parameters);
5020 /* ---------------------------------------------------------------------------------------------------- */
5022 /* called in GDBusWorker thread with connection's lock held */
5024 obj_message_func (GDBusConnection *connection,
5026 GDBusMessage *message)
5028 const gchar *interface_name;
5029 const gchar *member;
5030 const gchar *signature;
5035 interface_name = g_dbus_message_get_interface (message);
5036 member = g_dbus_message_get_member (message);
5037 signature = g_dbus_message_get_signature (message);
5039 /* see if we have an interface for handling this call */
5040 if (interface_name != NULL)
5042 ExportedInterface *ei;
5043 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5046 /* we do - invoke the handler in idle in the right thread */
5048 /* handle no vtable or handler being present */
5049 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5052 handled = validate_and_maybe_schedule_method_call (connection,
5064 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5065 g_strcmp0 (member, "Introspect") == 0 &&
5066 g_strcmp0 (signature, "") == 0)
5068 handled = handle_introspect (connection, eo, message);
5071 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5072 g_strcmp0 (member, "Get") == 0 &&
5073 g_strcmp0 (signature, "ss") == 0)
5075 handled = handle_getset_property (connection, eo, message, TRUE);
5078 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5079 g_strcmp0 (member, "Set") == 0 &&
5080 g_strcmp0 (signature, "ssv") == 0)
5082 handled = handle_getset_property (connection, eo, message, FALSE);
5085 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5086 g_strcmp0 (member, "GetAll") == 0 &&
5087 g_strcmp0 (signature, "s") == 0)
5089 handled = handle_get_all_properties (connection, eo, message);
5098 * g_dbus_connection_register_object:
5099 * @connection: a #GDBusConnection
5100 * @object_path: the object path to register at
5101 * @interface_info: introspection data for the interface
5102 * @vtable: (nullable): a #GDBusInterfaceVTable to call into or %NULL
5103 * @user_data: (nullable): data to pass to functions in @vtable
5104 * @user_data_free_func: function to call when the object path is unregistered
5105 * @error: return location for error or %NULL
5107 * Registers callbacks for exported objects at @object_path with the
5108 * D-Bus interface that is described in @interface_info.
5110 * Calls to functions in @vtable (and @user_data_free_func) will happen
5112 * [thread-default main context][g-main-context-push-thread-default]
5113 * of the thread you are calling this method from.
5115 * Note that all #GVariant values passed to functions in @vtable will match
5116 * the signature given in @interface_info - if a remote caller passes
5117 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5118 * is returned to the remote caller.
5120 * Additionally, if the remote caller attempts to invoke methods or
5121 * access properties not mentioned in @interface_info the
5122 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5123 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5124 * are returned to the caller.
5126 * It is considered a programming error if the
5127 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5128 * #GVariant of incorrect type.
5130 * If an existing callback is already registered at @object_path and
5131 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5133 * GDBus automatically implements the standard D-Bus interfaces
5134 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5135 * and org.freedesktop.Peer, so you don't have to implement those for the
5136 * objects you export. You can implement org.freedesktop.DBus.Properties
5137 * yourself, e.g. to handle getting and setting of properties asynchronously.
5139 * Note that the reference count on @interface_info will be
5140 * incremented by 1 (unless allocated statically, e.g. if the
5141 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5142 * as the object is exported. Also note that @vtable will be copied.
5144 * See this [server][gdbus-server] for an example of how to use this method.
5146 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5147 * that can be used with g_dbus_connection_unregister_object()
5152 g_dbus_connection_register_object (GDBusConnection *connection,
5153 const gchar *object_path,
5154 GDBusInterfaceInfo *interface_info,
5155 const GDBusInterfaceVTable *vtable,
5157 GDestroyNotify user_data_free_func,
5161 ExportedInterface *ei;
5164 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5165 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5166 g_return_val_if_fail (interface_info != NULL, 0);
5167 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5168 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5169 g_return_val_if_fail (check_initialized (connection), 0);
5173 CONNECTION_LOCK (connection);
5175 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5178 eo = g_new0 (ExportedObject, 1);
5179 eo->object_path = g_strdup (object_path);
5180 eo->connection = connection;
5181 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5184 (GDestroyNotify) exported_interface_free);
5185 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5188 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5194 _("An object is already exported for the interface %s at %s"),
5195 interface_info->name,
5200 ei = g_new0 (ExportedInterface, 1);
5201 ei->id = g_atomic_int_add (&_global_registration_id, 1); /* TODO: overflow etc. */
5203 ei->user_data = user_data;
5204 ei->user_data_free_func = user_data_free_func;
5205 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5206 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5207 g_dbus_interface_info_cache_build (ei->interface_info);
5208 ei->interface_name = g_strdup (interface_info->name);
5209 ei->context = g_main_context_ref_thread_default ();
5211 g_hash_table_insert (eo->map_if_name_to_ei,
5212 (gpointer) ei->interface_name,
5214 g_hash_table_insert (connection->map_id_to_ei,
5215 GUINT_TO_POINTER (ei->id),
5221 CONNECTION_UNLOCK (connection);
5227 * g_dbus_connection_unregister_object:
5228 * @connection: a #GDBusConnection
5229 * @registration_id: a registration id obtained from
5230 * g_dbus_connection_register_object()
5232 * Unregisters an object.
5234 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5239 g_dbus_connection_unregister_object (GDBusConnection *connection,
5240 guint registration_id)
5242 ExportedInterface *ei;
5246 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5247 g_return_val_if_fail (check_initialized (connection), FALSE);
5251 CONNECTION_LOCK (connection);
5253 ei = g_hash_table_lookup (connection->map_id_to_ei,
5254 GUINT_TO_POINTER (registration_id));
5260 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5261 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5262 /* unregister object path if we have no more exported interfaces */
5263 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5264 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5270 CONNECTION_UNLOCK (connection);
5276 GClosure *method_call_closure;
5277 GClosure *get_property_closure;
5278 GClosure *set_property_closure;
5279 } RegisterObjectData;
5281 static RegisterObjectData *
5282 register_object_data_new (GClosure *method_call_closure,
5283 GClosure *get_property_closure,
5284 GClosure *set_property_closure)
5286 RegisterObjectData *data;
5288 data = g_new0 (RegisterObjectData, 1);
5290 if (method_call_closure != NULL)
5292 data->method_call_closure = g_closure_ref (method_call_closure);
5293 g_closure_sink (method_call_closure);
5294 if (G_CLOSURE_NEEDS_MARSHAL (method_call_closure))
5295 g_closure_set_marshal (method_call_closure, g_cclosure_marshal_generic);
5298 if (get_property_closure != NULL)
5300 data->get_property_closure = g_closure_ref (get_property_closure);
5301 g_closure_sink (get_property_closure);
5302 if (G_CLOSURE_NEEDS_MARSHAL (get_property_closure))
5303 g_closure_set_marshal (get_property_closure, g_cclosure_marshal_generic);
5306 if (set_property_closure != NULL)
5308 data->set_property_closure = g_closure_ref (set_property_closure);
5309 g_closure_sink (set_property_closure);
5310 if (G_CLOSURE_NEEDS_MARSHAL (set_property_closure))
5311 g_closure_set_marshal (set_property_closure, g_cclosure_marshal_generic);
5318 register_object_free_func (gpointer user_data)
5320 RegisterObjectData *data = user_data;
5322 g_clear_pointer (&data->method_call_closure, g_closure_unref);
5323 g_clear_pointer (&data->get_property_closure, g_closure_unref);
5324 g_clear_pointer (&data->set_property_closure, g_closure_unref);
5330 register_with_closures_on_method_call (GDBusConnection *connection,
5331 const gchar *sender,
5332 const gchar *object_path,
5333 const gchar *interface_name,
5334 const gchar *method_name,
5335 GVariant *parameters,
5336 GDBusMethodInvocation *invocation,
5339 RegisterObjectData *data = user_data;
5340 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5342 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5343 g_value_set_object (¶ms[0], connection);
5345 g_value_init (¶ms[1], G_TYPE_STRING);
5346 g_value_set_string (¶ms[1], sender);
5348 g_value_init (¶ms[2], G_TYPE_STRING);
5349 g_value_set_string (¶ms[2], object_path);
5351 g_value_init (¶ms[3], G_TYPE_STRING);
5352 g_value_set_string (¶ms[3], interface_name);
5354 g_value_init (¶ms[4], G_TYPE_STRING);
5355 g_value_set_string (¶ms[4], method_name);
5357 g_value_init (¶ms[5], G_TYPE_VARIANT);
5358 g_value_set_variant (¶ms[5], parameters);
5360 g_value_init (¶ms[6], G_TYPE_DBUS_METHOD_INVOCATION);
5361 g_value_set_object (¶ms[6], invocation);
5363 g_closure_invoke (data->method_call_closure, NULL, G_N_ELEMENTS (params), params, NULL);
5365 g_value_unset (params + 0);
5366 g_value_unset (params + 1);
5367 g_value_unset (params + 2);
5368 g_value_unset (params + 3);
5369 g_value_unset (params + 4);
5370 g_value_unset (params + 5);
5371 g_value_unset (params + 6);
5375 register_with_closures_on_get_property (GDBusConnection *connection,
5376 const gchar *sender,
5377 const gchar *object_path,
5378 const gchar *interface_name,
5379 const gchar *property_name,
5383 RegisterObjectData *data = user_data;
5384 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5385 GValue result_value = G_VALUE_INIT;
5388 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5389 g_value_set_object (¶ms[0], connection);
5391 g_value_init (¶ms[1], G_TYPE_STRING);
5392 g_value_set_string (¶ms[1], sender);
5394 g_value_init (¶ms[2], G_TYPE_STRING);
5395 g_value_set_string (¶ms[2], object_path);
5397 g_value_init (¶ms[3], G_TYPE_STRING);
5398 g_value_set_string (¶ms[3], interface_name);
5400 g_value_init (¶ms[4], G_TYPE_STRING);
5401 g_value_set_string (¶ms[4], property_name);
5403 g_value_init (&result_value, G_TYPE_VARIANT);
5405 g_closure_invoke (data->get_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5407 result = g_value_get_variant (&result_value);
5409 g_variant_ref (result);
5411 g_value_unset (params + 0);
5412 g_value_unset (params + 1);
5413 g_value_unset (params + 2);
5414 g_value_unset (params + 3);
5415 g_value_unset (params + 4);
5416 g_value_unset (&result_value);
5419 g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5420 _("Unable to retrieve property %s.%s"),
5421 interface_name, property_name);
5427 register_with_closures_on_set_property (GDBusConnection *connection,
5428 const gchar *sender,
5429 const gchar *object_path,
5430 const gchar *interface_name,
5431 const gchar *property_name,
5436 RegisterObjectData *data = user_data;
5437 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5438 GValue result_value = G_VALUE_INIT;
5441 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5442 g_value_set_object (¶ms[0], connection);
5444 g_value_init (¶ms[1], G_TYPE_STRING);
5445 g_value_set_string (¶ms[1], sender);
5447 g_value_init (¶ms[2], G_TYPE_STRING);
5448 g_value_set_string (¶ms[2], object_path);
5450 g_value_init (¶ms[3], G_TYPE_STRING);
5451 g_value_set_string (¶ms[3], interface_name);
5453 g_value_init (¶ms[4], G_TYPE_STRING);
5454 g_value_set_string (¶ms[4], property_name);
5456 g_value_init (¶ms[5], G_TYPE_VARIANT);
5457 g_value_set_variant (¶ms[5], value);
5459 g_value_init (&result_value, G_TYPE_BOOLEAN);
5461 g_closure_invoke (data->set_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5463 result = g_value_get_boolean (&result_value);
5465 g_value_unset (params + 0);
5466 g_value_unset (params + 1);
5467 g_value_unset (params + 2);
5468 g_value_unset (params + 3);
5469 g_value_unset (params + 4);
5470 g_value_unset (params + 5);
5471 g_value_unset (&result_value);
5475 G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5476 _("Unable to set property %s.%s"),
5477 interface_name, property_name);
5483 * g_dbus_connection_register_object_with_closures: (rename-to g_dbus_connection_register_object)
5484 * @connection: A #GDBusConnection.
5485 * @object_path: The object path to register at.
5486 * @interface_info: Introspection data for the interface.
5487 * @method_call_closure: (nullable): #GClosure for handling incoming method calls.
5488 * @get_property_closure: (nullable): #GClosure for getting a property.
5489 * @set_property_closure: (nullable): #GClosure for setting a property.
5490 * @error: Return location for error or %NULL.
5492 * Version of g_dbus_connection_register_object() using closures instead of a
5493 * #GDBusInterfaceVTable for easier binding in other languages.
5495 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5496 * that can be used with g_dbus_connection_unregister_object() .
5501 g_dbus_connection_register_object_with_closures (GDBusConnection *connection,
5502 const gchar *object_path,
5503 GDBusInterfaceInfo *interface_info,
5504 GClosure *method_call_closure,
5505 GClosure *get_property_closure,
5506 GClosure *set_property_closure,
5509 RegisterObjectData *data;
5510 GDBusInterfaceVTable vtable =
5512 method_call_closure != NULL ? register_with_closures_on_method_call : NULL,
5513 get_property_closure != NULL ? register_with_closures_on_get_property : NULL,
5514 set_property_closure != NULL ? register_with_closures_on_set_property : NULL
5517 data = register_object_data_new (method_call_closure, get_property_closure, set_property_closure);
5519 return g_dbus_connection_register_object (connection,
5524 register_object_free_func,
5528 /* ---------------------------------------------------------------------------------------------------- */
5531 * g_dbus_connection_emit_signal:
5532 * @connection: a #GDBusConnection
5533 * @destination_bus_name: (nullable): the unique bus name for the destination
5534 * for the signal or %NULL to emit to all listeners
5535 * @object_path: path of remote object
5536 * @interface_name: D-Bus interface to emit a signal on
5537 * @signal_name: the name of the signal to emit
5538 * @parameters: (nullable): a #GVariant tuple with parameters for the signal
5539 * or %NULL if not passing parameters
5540 * @error: Return location for error or %NULL
5544 * If the parameters GVariant is floating, it is consumed.
5546 * This can only fail if @parameters is not compatible with the D-Bus protocol
5547 * (%G_IO_ERROR_INVALID_ARGUMENT), or if @connection has been closed
5548 * (%G_IO_ERROR_CLOSED).
5550 * Returns: %TRUE unless @error is set
5555 g_dbus_connection_emit_signal (GDBusConnection *connection,
5556 const gchar *destination_bus_name,
5557 const gchar *object_path,
5558 const gchar *interface_name,
5559 const gchar *signal_name,
5560 GVariant *parameters,
5563 GDBusMessage *message;
5569 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5570 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5571 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5572 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5573 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5574 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5575 g_return_val_if_fail (check_initialized (connection), FALSE);
5577 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5579 _g_dbus_debug_print_lock ();
5580 g_print ("========================================================================\n"
5581 "GDBus-debug:Emission:\n"
5582 " >>>> SIGNAL EMISSION %s.%s()\n"
5584 " destination %s\n",
5585 interface_name, signal_name,
5587 destination_bus_name != NULL ? destination_bus_name : "(none)");
5588 _g_dbus_debug_print_unlock ();
5591 message = g_dbus_message_new_signal (object_path,
5595 if (destination_bus_name != NULL)
5596 g_dbus_message_set_header (message,
5597 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5598 g_variant_new_string (destination_bus_name));
5600 if (parameters != NULL)
5601 g_dbus_message_set_body (message, parameters);
5603 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5604 g_object_unref (message);
5610 add_call_flags (GDBusMessage *message,
5611 GDBusCallFlags flags)
5613 GDBusMessageFlags msg_flags = 0;
5615 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5616 msg_flags |= G_DBUS_MESSAGE_FLAGS_NO_AUTO_START;
5617 if (flags & G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
5618 msg_flags |= G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION;
5620 g_dbus_message_set_flags (message, msg_flags);
5624 decode_method_reply (GDBusMessage *reply,
5625 const gchar *method_name,
5626 const GVariantType *reply_type,
5627 GUnixFDList **out_fd_list,
5633 switch (g_dbus_message_get_message_type (reply))
5635 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5636 result = g_dbus_message_get_body (reply);
5639 result = g_variant_new ("()");
5640 g_variant_ref_sink (result);
5644 g_variant_ref (result);
5647 if (!g_variant_is_of_type (result, reply_type))
5649 gchar *type_string = g_variant_type_dup_string (reply_type);
5653 G_IO_ERROR_INVALID_ARGUMENT,
5654 _("Method ā%sā returned type ā%sā, but expected ā%sā"),
5655 method_name, g_variant_get_type_string (result), type_string);
5657 g_variant_unref (result);
5658 g_free (type_string);
5665 if (out_fd_list != NULL)
5667 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5668 if (*out_fd_list != NULL)
5669 g_object_ref (*out_fd_list);
5675 case G_DBUS_MESSAGE_TYPE_ERROR:
5676 g_dbus_message_to_gerror (reply, error);
5680 g_assert_not_reached ();
5690 GVariantType *reply_type;
5691 gchar *method_name; /* for error message */
5693 GUnixFDList *fd_list;
5697 call_state_free (CallState *state)
5699 g_variant_type_free (state->reply_type);
5700 g_free (state->method_name);
5702 if (state->fd_list != NULL)
5703 g_object_unref (state->fd_list);
5704 g_slice_free (CallState, state);
5707 /* called in any thread, with the connection's lock not held */
5709 g_dbus_connection_call_done (GObject *source,
5710 GAsyncResult *result,
5713 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5714 GTask *task = user_data;
5715 CallState *state = g_task_get_task_data (task);
5716 GError *error = NULL;
5717 GDBusMessage *reply;
5718 GVariant *value = NULL;
5720 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5724 if (G_UNLIKELY (_g_dbus_debug_call ()))
5726 _g_dbus_debug_print_lock ();
5727 g_print ("========================================================================\n"
5728 "GDBus-debug:Call:\n"
5729 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5732 g_dbus_message_get_reply_serial (reply));
5735 g_print ("SUCCESS\n");
5739 g_print ("FAILED: %s\n",
5742 _g_dbus_debug_print_unlock ();
5746 value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5749 g_task_return_error (task, error);
5751 g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5753 g_clear_object (&reply);
5754 g_object_unref (task);
5757 /* called in any thread, with the connection's lock not held */
5759 g_dbus_connection_call_internal (GDBusConnection *connection,
5760 const gchar *bus_name,
5761 const gchar *object_path,
5762 const gchar *interface_name,
5763 const gchar *method_name,
5764 GVariant *parameters,
5765 const GVariantType *reply_type,
5766 GDBusCallFlags flags,
5768 GUnixFDList *fd_list,
5769 GCancellable *cancellable,
5770 GAsyncReadyCallback callback,
5773 GDBusMessage *message;
5776 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5777 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5778 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5779 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5780 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5781 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5782 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5783 g_return_if_fail (check_initialized (connection));
5785 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5787 g_return_if_fail (fd_list == NULL);
5790 message = g_dbus_message_new_method_call (bus_name,
5794 add_call_flags (message, flags);
5795 if (parameters != NULL)
5796 g_dbus_message_set_body (message, parameters);
5799 if (fd_list != NULL)
5800 g_dbus_message_set_unix_fd_list (message, fd_list);
5803 /* If the user has no callback then we can just send the message with
5804 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5805 * the logic for processing the reply. If the service sends the reply
5806 * anyway then it will just be ignored.
5808 if (callback != NULL)
5813 state = g_slice_new0 (CallState);
5814 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5816 if (reply_type == NULL)
5817 reply_type = G_VARIANT_TYPE_ANY;
5819 state->reply_type = g_variant_type_copy (reply_type);
5821 task = g_task_new (connection, cancellable, callback, user_data);
5822 g_task_set_source_tag (task, g_dbus_connection_call_internal);
5823 g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5825 g_dbus_connection_send_message_with_reply (connection,
5827 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5831 g_dbus_connection_call_done,
5836 GDBusMessageFlags flags;
5838 flags = g_dbus_message_get_flags (message);
5839 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5840 g_dbus_message_set_flags (message, flags);
5842 g_dbus_connection_send_message (connection,
5844 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5848 if (G_UNLIKELY (_g_dbus_debug_call ()))
5850 _g_dbus_debug_print_lock ();
5851 g_print ("========================================================================\n"
5852 "GDBus-debug:Call:\n"
5853 " >>>> ASYNC %s.%s()\n"
5855 " owned by name %s (serial %d)\n",
5859 bus_name != NULL ? bus_name : "(none)",
5861 _g_dbus_debug_print_unlock ();
5864 if (message != NULL)
5865 g_object_unref (message);
5868 /* called in any thread, with the connection's lock not held */
5870 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5871 GUnixFDList **out_fd_list,
5879 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5880 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5881 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5883 task = G_TASK (res);
5884 state = g_task_get_task_data (task);
5886 ret = g_task_propagate_pointer (task, error);
5890 if (out_fd_list != NULL)
5891 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5895 /* called in any user thread, with the connection's lock not held */
5897 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5898 const gchar *bus_name,
5899 const gchar *object_path,
5900 const gchar *interface_name,
5901 const gchar *method_name,
5902 GVariant *parameters,
5903 const GVariantType *reply_type,
5904 GDBusCallFlags flags,
5906 GUnixFDList *fd_list,
5907 GUnixFDList **out_fd_list,
5908 GCancellable *cancellable,
5911 GDBusMessage *message;
5912 GDBusMessage *reply;
5914 GError *local_error;
5915 GDBusSendMessageFlags send_flags;
5921 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5922 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5923 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5924 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5925 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5926 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5927 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5929 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5931 g_return_val_if_fail (fd_list == NULL, NULL);
5933 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5935 if (!(flags & CALL_FLAGS_INITIALIZING))
5936 g_return_val_if_fail (check_initialized (connection), FALSE);
5938 if (reply_type == NULL)
5939 reply_type = G_VARIANT_TYPE_ANY;
5941 message = g_dbus_message_new_method_call (bus_name,
5945 add_call_flags (message, flags);
5946 if (parameters != NULL)
5947 g_dbus_message_set_body (message, parameters);
5950 if (fd_list != NULL)
5951 g_dbus_message_set_unix_fd_list (message, fd_list);
5954 if (G_UNLIKELY (_g_dbus_debug_call ()))
5956 _g_dbus_debug_print_lock ();
5957 g_print ("========================================================================\n"
5958 "GDBus-debug:Call:\n"
5959 " >>>> SYNC %s.%s()\n"
5961 " owned by name %s\n",
5965 bus_name != NULL ? bus_name : "(none)");
5966 _g_dbus_debug_print_unlock ();
5971 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5973 /* translate from one flavour of flags to another... */
5974 if (flags & CALL_FLAGS_INITIALIZING)
5975 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5977 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5981 NULL, /* volatile guint32 *out_serial */
5985 if (G_UNLIKELY (_g_dbus_debug_call ()))
5987 _g_dbus_debug_print_lock ();
5988 g_print ("========================================================================\n"
5989 "GDBus-debug:Call:\n"
5990 " <<<< SYNC COMPLETE %s.%s()\n"
5996 g_print ("SUCCESS\n");
6000 g_print ("FAILED: %s\n",
6001 local_error->message);
6003 _g_dbus_debug_print_unlock ();
6009 *error = local_error;
6011 g_error_free (local_error);
6015 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6018 if (message != NULL)
6019 g_object_unref (message);
6021 g_object_unref (reply);
6026 /* ---------------------------------------------------------------------------------------------------- */
6029 * g_dbus_connection_call:
6030 * @connection: a #GDBusConnection
6031 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6032 * @connection is not a message bus connection
6033 * @object_path: path of remote object
6034 * @interface_name: D-Bus interface to invoke method on
6035 * @method_name: the name of the method to invoke
6036 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6037 * or %NULL if not passing parameters
6038 * @reply_type: (nullable): the expected type of the reply (which will be a
6040 * @flags: flags from the #GDBusCallFlags enumeration
6041 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6042 * timeout or %G_MAXINT for no timeout
6043 * @cancellable: (nullable): a #GCancellable or %NULL
6044 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
6045 * is satisfied or %NULL if you don't care about the result of the
6047 * @user_data: the data to pass to @callback
6049 * Asynchronously invokes the @method_name method on the
6050 * @interface_name D-Bus interface on the remote object at
6051 * @object_path owned by @bus_name.
6053 * If @connection is closed then the operation will fail with
6054 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6055 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6056 * not compatible with the D-Bus protocol, the operation fails with
6057 * %G_IO_ERROR_INVALID_ARGUMENT.
6059 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6060 * error will be raised if it does not match. Said another way, if you give a @reply_type
6061 * then any non-%NULL return value will be of this type. Unless itās
6062 * %G_VARIANT_TYPE_UNIT, the @reply_type will be a tuple containing one or more
6065 * If the @parameters #GVariant is floating, it is consumed. This allows
6066 * convenient 'inline' use of g_variant_new(), e.g.:
6067 * |[<!-- language="C" -->
6068 * g_dbus_connection_call (connection,
6069 * "org.freedesktop.StringThings",
6070 * "/org/freedesktop/StringThings",
6071 * "org.freedesktop.StringThings",
6073 * g_variant_new ("(ss)",
6077 * G_DBUS_CALL_FLAGS_NONE,
6080 * (GAsyncReadyCallback) two_strings_done,
6084 * This is an asynchronous method. When the operation is finished,
6085 * @callback will be invoked in the
6086 * [thread-default main context][g-main-context-push-thread-default]
6087 * of the thread you are calling this method from. You can then call
6088 * g_dbus_connection_call_finish() to get the result of the operation.
6089 * See g_dbus_connection_call_sync() for the synchronous version of this
6092 * If @callback is %NULL then the D-Bus method call message will be sent with
6093 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6098 g_dbus_connection_call (GDBusConnection *connection,
6099 const gchar *bus_name,
6100 const gchar *object_path,
6101 const gchar *interface_name,
6102 const gchar *method_name,
6103 GVariant *parameters,
6104 const GVariantType *reply_type,
6105 GDBusCallFlags flags,
6107 GCancellable *cancellable,
6108 GAsyncReadyCallback callback,
6111 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);
6115 * g_dbus_connection_call_finish:
6116 * @connection: a #GDBusConnection
6117 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6118 * @error: return location for error or %NULL
6120 * Finishes an operation started with g_dbus_connection_call().
6122 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6123 * return values. Free with g_variant_unref().
6128 g_dbus_connection_call_finish (GDBusConnection *connection,
6132 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6136 * g_dbus_connection_call_sync:
6137 * @connection: a #GDBusConnection
6138 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6139 * @connection is not a message bus connection
6140 * @object_path: path of remote object
6141 * @interface_name: D-Bus interface to invoke method on
6142 * @method_name: the name of the method to invoke
6143 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6144 * or %NULL if not passing parameters
6145 * @reply_type: (nullable): the expected type of the reply, or %NULL
6146 * @flags: flags from the #GDBusCallFlags enumeration
6147 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6148 * timeout or %G_MAXINT for no timeout
6149 * @cancellable: (nullable): a #GCancellable or %NULL
6150 * @error: return location for error or %NULL
6152 * Synchronously invokes the @method_name method on the
6153 * @interface_name D-Bus interface on the remote object at
6154 * @object_path owned by @bus_name.
6156 * If @connection is closed then the operation will fail with
6157 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6158 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6159 * contains a value not compatible with the D-Bus protocol, the operation
6160 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6162 * If @reply_type is non-%NULL then the reply will be checked for having
6163 * this type and an error will be raised if it does not match. Said
6164 * another way, if you give a @reply_type then any non-%NULL return
6165 * value will be of this type.
6167 * If the @parameters #GVariant is floating, it is consumed.
6168 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6169 * |[<!-- language="C" -->
6170 * g_dbus_connection_call_sync (connection,
6171 * "org.freedesktop.StringThings",
6172 * "/org/freedesktop/StringThings",
6173 * "org.freedesktop.StringThings",
6175 * g_variant_new ("(ss)",
6179 * G_DBUS_CALL_FLAGS_NONE,
6185 * The calling thread is blocked until a reply is received. See
6186 * g_dbus_connection_call() for the asynchronous version of
6189 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6190 * return values. Free with g_variant_unref().
6195 g_dbus_connection_call_sync (GDBusConnection *connection,
6196 const gchar *bus_name,
6197 const gchar *object_path,
6198 const gchar *interface_name,
6199 const gchar *method_name,
6200 GVariant *parameters,
6201 const GVariantType *reply_type,
6202 GDBusCallFlags flags,
6204 GCancellable *cancellable,
6207 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);
6210 /* ---------------------------------------------------------------------------------------------------- */
6215 * g_dbus_connection_call_with_unix_fd_list:
6216 * @connection: a #GDBusConnection
6217 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6218 * @connection is not a message bus connection
6219 * @object_path: path of remote object
6220 * @interface_name: D-Bus interface to invoke method on
6221 * @method_name: the name of the method to invoke
6222 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6223 * or %NULL if not passing parameters
6224 * @reply_type: (nullable): the expected type of the reply, or %NULL
6225 * @flags: flags from the #GDBusCallFlags enumeration
6226 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6227 * timeout or %G_MAXINT for no timeout
6228 * @fd_list: (nullable): a #GUnixFDList or %NULL
6229 * @cancellable: (nullable): a #GCancellable or %NULL
6230 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
6231 * satisfied or %NULL if you don't * care about the result of the
6233 * @user_data: The data to pass to @callback.
6235 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6237 * This method is only available on UNIX.
6242 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6243 const gchar *bus_name,
6244 const gchar *object_path,
6245 const gchar *interface_name,
6246 const gchar *method_name,
6247 GVariant *parameters,
6248 const GVariantType *reply_type,
6249 GDBusCallFlags flags,
6251 GUnixFDList *fd_list,
6252 GCancellable *cancellable,
6253 GAsyncReadyCallback callback,
6256 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);
6260 * g_dbus_connection_call_with_unix_fd_list_finish:
6261 * @connection: a #GDBusConnection
6262 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6263 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6264 * g_dbus_connection_call_with_unix_fd_list()
6265 * @error: return location for error or %NULL
6267 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6269 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6270 * return values. Free with g_variant_unref().
6275 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6276 GUnixFDList **out_fd_list,
6280 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6284 * g_dbus_connection_call_with_unix_fd_list_sync:
6285 * @connection: a #GDBusConnection
6286 * @bus_name: (nullable): a unique or well-known bus name or %NULL
6287 * if @connection is not a message bus connection
6288 * @object_path: path of remote object
6289 * @interface_name: D-Bus interface to invoke method on
6290 * @method_name: the name of the method to invoke
6291 * @parameters: (nullable): a #GVariant tuple with parameters for
6292 * the method or %NULL if not passing parameters
6293 * @reply_type: (nullable): the expected type of the reply, or %NULL
6294 * @flags: flags from the #GDBusCallFlags enumeration
6295 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6296 * timeout or %G_MAXINT for no timeout
6297 * @fd_list: (nullable): a #GUnixFDList or %NULL
6298 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6299 * @cancellable: (nullable): a #GCancellable or %NULL
6300 * @error: return location for error or %NULL
6302 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6304 * This method is only available on UNIX.
6306 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6307 * return values. Free with g_variant_unref().
6312 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6313 const gchar *bus_name,
6314 const gchar *object_path,
6315 const gchar *interface_name,
6316 const gchar *method_name,
6317 GVariant *parameters,
6318 const GVariantType *reply_type,
6319 GDBusCallFlags flags,
6321 GUnixFDList *fd_list,
6322 GUnixFDList **out_fd_list,
6323 GCancellable *cancellable,
6326 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);
6329 #endif /* G_OS_UNIX */
6331 /* ---------------------------------------------------------------------------------------------------- */
6333 struct ExportedSubtree
6337 GDBusConnection *connection;
6338 GDBusSubtreeVTable *vtable;
6339 GDBusSubtreeFlags flags;
6341 GMainContext *context;
6343 GDestroyNotify user_data_free_func;
6347 exported_subtree_free (ExportedSubtree *es)
6349 call_destroy_notify (es->context,
6350 es->user_data_free_func,
6353 g_main_context_unref (es->context);
6355 _g_dbus_subtree_vtable_free (es->vtable);
6356 g_free (es->object_path);
6360 /* called without lock held in the thread where the caller registered
6364 handle_subtree_introspect (GDBusConnection *connection,
6365 ExportedSubtree *es,
6366 GDBusMessage *message)
6370 GDBusMessage *reply;
6373 const gchar *sender;
6374 const gchar *requested_object_path;
6375 const gchar *requested_node;
6376 GDBusInterfaceInfo **interfaces;
6378 gchar **subnode_paths;
6379 gboolean has_properties_interface;
6380 gboolean has_introspectable_interface;
6384 requested_object_path = g_dbus_message_get_path (message);
6385 sender = g_dbus_message_get_sender (message);
6386 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6388 s = g_string_new (NULL);
6389 introspect_append_header (s);
6391 /* Strictly we don't need the children in dynamic mode, but we avoid the
6392 * conditionals to preserve code clarity
6394 children = es->vtable->enumerate (es->connection,
6401 requested_node = strrchr (requested_object_path, '/') + 1;
6403 /* Assert existence of object if we are not dynamic */
6404 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6405 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6410 requested_node = NULL;
6413 interfaces = es->vtable->introspect (es->connection,
6418 if (interfaces != NULL)
6420 has_properties_interface = FALSE;
6421 has_introspectable_interface = FALSE;
6423 for (n = 0; interfaces[n] != NULL; n++)
6425 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6426 has_properties_interface = TRUE;
6427 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6428 has_introspectable_interface = TRUE;
6430 if (!has_properties_interface)
6431 g_string_append (s, introspect_properties_interface);
6432 if (!has_introspectable_interface)
6433 g_string_append (s, introspect_introspectable_interface);
6435 for (n = 0; interfaces[n] != NULL; n++)
6437 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6438 g_dbus_interface_info_unref (interfaces[n]);
6440 g_free (interfaces);
6443 /* then include <node> entries from the Subtree for the root */
6446 for (n = 0; children != NULL && children[n] != NULL; n++)
6447 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6450 /* finally include nodes registered below us */
6451 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6452 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6453 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6454 g_strfreev (subnode_paths);
6456 g_string_append (s, "</node>\n");
6458 reply = g_dbus_message_new_method_reply (message);
6459 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6460 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6461 g_object_unref (reply);
6466 g_string_free (s, TRUE);
6467 g_strfreev (children);
6471 /* called without lock held in the thread where the caller registered
6475 handle_subtree_method_invocation (GDBusConnection *connection,
6476 ExportedSubtree *es,
6477 GDBusMessage *message)
6480 const gchar *sender;
6481 const gchar *interface_name;
6482 const gchar *member;
6483 const gchar *signature;
6484 const gchar *requested_object_path;
6485 const gchar *requested_node;
6487 GDBusInterfaceInfo *interface_info;
6488 const GDBusInterfaceVTable *interface_vtable;
6489 gpointer interface_user_data;
6491 GDBusInterfaceInfo **interfaces;
6492 gboolean is_property_get;
6493 gboolean is_property_set;
6494 gboolean is_property_get_all;
6499 requested_object_path = g_dbus_message_get_path (message);
6500 sender = g_dbus_message_get_sender (message);
6501 interface_name = g_dbus_message_get_interface (message);
6502 member = g_dbus_message_get_member (message);
6503 signature = g_dbus_message_get_signature (message);
6504 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6506 is_property_get = FALSE;
6507 is_property_set = FALSE;
6508 is_property_get_all = FALSE;
6509 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6511 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6512 is_property_get = TRUE;
6513 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6514 is_property_set = TRUE;
6515 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6516 is_property_get_all = TRUE;
6521 requested_node = strrchr (requested_object_path, '/') + 1;
6523 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6525 /* We don't want to dispatch to unenumerated
6526 * nodes, so ensure that the child exists.
6531 children = es->vtable->enumerate (es->connection,
6536 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6537 g_strfreev (children);
6545 requested_node = NULL;
6548 /* get introspection data for the node */
6549 interfaces = es->vtable->introspect (es->connection,
6551 requested_object_path,
6555 if (interfaces == NULL)
6558 interface_info = NULL;
6559 for (n = 0; interfaces[n] != NULL; n++)
6561 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6562 interface_info = interfaces[n];
6565 /* dispatch the call if the user wants to handle it */
6566 if (interface_info != NULL)
6568 /* figure out where to dispatch the method call */
6569 interface_user_data = NULL;
6570 interface_vtable = es->vtable->dispatch (es->connection,
6575 &interface_user_data,
6577 if (interface_vtable == NULL)
6580 CONNECTION_LOCK (connection);
6581 handled = validate_and_maybe_schedule_method_call (es->connection,
6588 interface_user_data);
6589 CONNECTION_UNLOCK (connection);
6591 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6592 else if (is_property_get || is_property_set || is_property_get_all)
6594 if (is_property_get)
6595 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6596 else if (is_property_set)
6597 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6598 else if (is_property_get_all)
6599 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6601 g_assert_not_reached ();
6603 /* see if the object supports this interface at all */
6604 for (n = 0; interfaces[n] != NULL; n++)
6606 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6607 interface_info = interfaces[n];
6610 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6611 * claims it won't support the interface
6613 if (interface_info == NULL)
6615 GDBusMessage *reply;
6616 reply = g_dbus_message_new_method_error (message,
6617 "org.freedesktop.DBus.Error.InvalidArgs",
6618 _("No such interface ā%sā"),
6620 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6621 g_object_unref (reply);
6626 /* figure out where to dispatch the property get/set/getall calls */
6627 interface_user_data = NULL;
6628 interface_vtable = es->vtable->dispatch (es->connection,
6633 &interface_user_data,
6635 if (interface_vtable == NULL)
6637 g_warning ("The subtree introspection function indicates that '%s' "
6638 "is a valid interface name, but calling the dispatch "
6639 "function on that interface gave us NULL", interface_name);
6643 if (is_property_get || is_property_set)
6645 CONNECTION_LOCK (connection);
6646 handled = validate_and_maybe_schedule_property_getset (es->connection,
6654 interface_user_data);
6655 CONNECTION_UNLOCK (connection);
6657 else if (is_property_get_all)
6659 CONNECTION_LOCK (connection);
6660 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6667 interface_user_data);
6668 CONNECTION_UNLOCK (connection);
6673 if (interfaces != NULL)
6675 for (n = 0; interfaces[n] != NULL; n++)
6676 g_dbus_interface_info_unref (interfaces[n]);
6677 g_free (interfaces);
6685 GDBusMessage *message;
6686 ExportedSubtree *es;
6687 } SubtreeDeferredData;
6690 subtree_deferred_data_free (SubtreeDeferredData *data)
6692 g_object_unref (data->message);
6696 /* called without lock held in the thread where the caller registered the subtree */
6698 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6700 SubtreeDeferredData *data = _data;
6705 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6706 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6707 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6708 handled = handle_subtree_introspect (data->es->connection,
6712 handled = handle_subtree_method_invocation (data->es->connection,
6718 CONNECTION_LOCK (data->es->connection);
6719 handled = handle_generic_unlocked (data->es->connection, data->message);
6720 CONNECTION_UNLOCK (data->es->connection);
6723 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6726 GDBusMessage *reply;
6727 reply = g_dbus_message_new_method_error (data->message,
6728 "org.freedesktop.DBus.Error.UnknownMethod",
6729 _("Method ā%sā on interface ā%sā with signature ā%sā does not exist"),
6730 g_dbus_message_get_member (data->message),
6731 g_dbus_message_get_interface (data->message),
6732 g_dbus_message_get_signature (data->message));
6733 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6734 g_object_unref (reply);
6740 /* called in GDBusWorker thread with connection's lock held */
6742 subtree_message_func (GDBusConnection *connection,
6743 ExportedSubtree *es,
6744 GDBusMessage *message)
6746 GSource *idle_source;
6747 SubtreeDeferredData *data;
6749 data = g_new0 (SubtreeDeferredData, 1);
6750 data->message = g_object_ref (message);
6753 /* defer this call to an idle handler in the right thread */
6754 idle_source = g_idle_source_new ();
6755 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6756 g_source_set_callback (idle_source,
6757 process_subtree_vtable_message_in_idle_cb,
6759 (GDestroyNotify) subtree_deferred_data_free);
6760 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6761 g_source_attach (idle_source, es->context);
6762 g_source_unref (idle_source);
6764 /* since we own the entire subtree, handlers for objects not in the subtree have been
6765 * tried already by libdbus-1 - so we just need to ensure that we're always going
6766 * to reply to the message
6772 * g_dbus_connection_register_subtree:
6773 * @connection: a #GDBusConnection
6774 * @object_path: the object path to register the subtree at
6775 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6776 * dispatch nodes in the subtree
6777 * @flags: flags used to fine tune the behavior of the subtree
6778 * @user_data: data to pass to functions in @vtable
6779 * @user_data_free_func: function to call when the subtree is unregistered
6780 * @error: return location for error or %NULL
6782 * Registers a whole subtree of dynamic objects.
6784 * The @enumerate and @introspection functions in @vtable are used to
6785 * convey, to remote callers, what nodes exist in the subtree rooted
6788 * When handling remote calls into any node in the subtree, first the
6789 * @enumerate function is used to check if the node exists. If the node exists
6790 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6791 * the @introspection function is used to check if the node supports the
6792 * requested method. If so, the @dispatch function is used to determine
6793 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6794 * #gpointer will be used to call into the interface vtable for processing
6797 * All calls into user-provided code will be invoked in the
6798 * [thread-default main context][g-main-context-push-thread-default]
6799 * of the thread you are calling this method from.
6801 * If an existing subtree is already registered at @object_path or
6802 * then @error is set to #G_IO_ERROR_EXISTS.
6804 * Note that it is valid to register regular objects (using
6805 * g_dbus_connection_register_object()) in a subtree registered with
6806 * g_dbus_connection_register_subtree() - if so, the subtree handler
6807 * is tried as the last resort. One way to think about a subtree
6808 * handler is to consider it a fallback handler for object paths not
6809 * registered via g_dbus_connection_register_object() or other bindings.
6811 * Note that @vtable will be copied so you cannot change it after
6814 * See this [server][gdbus-subtree-server] for an example of how to use
6817 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6818 * that can be used with g_dbus_connection_unregister_subtree() .
6823 g_dbus_connection_register_subtree (GDBusConnection *connection,
6824 const gchar *object_path,
6825 const GDBusSubtreeVTable *vtable,
6826 GDBusSubtreeFlags flags,
6828 GDestroyNotify user_data_free_func,
6832 ExportedSubtree *es;
6834 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6835 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6836 g_return_val_if_fail (vtable != NULL, 0);
6837 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6838 g_return_val_if_fail (check_initialized (connection), 0);
6842 CONNECTION_LOCK (connection);
6844 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6850 _("A subtree is already exported for %s"),
6855 es = g_new0 (ExportedSubtree, 1);
6856 es->object_path = g_strdup (object_path);
6857 es->connection = connection;
6859 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6861 es->id = g_atomic_int_add (&_global_subtree_registration_id, 1); /* TODO: overflow etc. */
6862 es->user_data = user_data;
6863 es->user_data_free_func = user_data_free_func;
6864 es->context = g_main_context_ref_thread_default ();
6866 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6867 g_hash_table_insert (connection->map_id_to_es,
6868 GUINT_TO_POINTER (es->id),
6874 CONNECTION_UNLOCK (connection);
6879 /* ---------------------------------------------------------------------------------------------------- */
6882 * g_dbus_connection_unregister_subtree:
6883 * @connection: a #GDBusConnection
6884 * @registration_id: a subtree registration id obtained from
6885 * g_dbus_connection_register_subtree()
6887 * Unregisters a subtree.
6889 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6894 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6895 guint registration_id)
6897 ExportedSubtree *es;
6900 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6901 g_return_val_if_fail (check_initialized (connection), FALSE);
6905 CONNECTION_LOCK (connection);
6907 es = g_hash_table_lookup (connection->map_id_to_es,
6908 GUINT_TO_POINTER (registration_id));
6912 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6913 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6918 CONNECTION_UNLOCK (connection);
6923 /* ---------------------------------------------------------------------------------------------------- */
6925 /* may be called in any thread, with connection's lock held */
6927 handle_generic_ping_unlocked (GDBusConnection *connection,
6928 const gchar *object_path,
6929 GDBusMessage *message)
6931 GDBusMessage *reply;
6932 reply = g_dbus_message_new_method_reply (message);
6933 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6934 g_object_unref (reply);
6937 /* may be called in any thread, with connection's lock held */
6939 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6940 const gchar *object_path,
6941 GDBusMessage *message)
6943 GDBusMessage *reply;
6946 if (connection->machine_id == NULL)
6951 connection->machine_id = _g_dbus_get_machine_id (&error);
6952 if (connection->machine_id == NULL)
6954 reply = g_dbus_message_new_method_error_literal (message,
6955 "org.freedesktop.DBus.Error.Failed",
6957 g_error_free (error);
6963 reply = g_dbus_message_new_method_reply (message);
6964 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6966 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6967 g_object_unref (reply);
6970 /* may be called in any thread, with connection's lock held */
6972 handle_generic_introspect_unlocked (GDBusConnection *connection,
6973 const gchar *object_path,
6974 GDBusMessage *message)
6979 GDBusMessage *reply;
6981 /* first the header */
6982 s = g_string_new (NULL);
6983 introspect_append_header (s);
6985 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6986 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6987 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6988 g_strfreev (registered);
6989 g_string_append (s, "</node>\n");
6991 reply = g_dbus_message_new_method_reply (message);
6992 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6993 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6994 g_object_unref (reply);
6995 g_string_free (s, TRUE);
6998 /* may be called in any thread, with connection's lock held */
7000 handle_generic_unlocked (GDBusConnection *connection,
7001 GDBusMessage *message)
7004 const gchar *interface_name;
7005 const gchar *member;
7006 const gchar *signature;
7009 CONNECTION_ENSURE_LOCK (connection);
7013 interface_name = g_dbus_message_get_interface (message);
7014 member = g_dbus_message_get_member (message);
7015 signature = g_dbus_message_get_signature (message);
7016 path = g_dbus_message_get_path (message);
7018 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7019 g_strcmp0 (member, "Introspect") == 0 &&
7020 g_strcmp0 (signature, "") == 0)
7022 handle_generic_introspect_unlocked (connection, path, message);
7025 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7026 g_strcmp0 (member, "Ping") == 0 &&
7027 g_strcmp0 (signature, "") == 0)
7029 handle_generic_ping_unlocked (connection, path, message);
7032 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7033 g_strcmp0 (member, "GetMachineId") == 0 &&
7034 g_strcmp0 (signature, "") == 0)
7036 handle_generic_get_machine_id_unlocked (connection, path, message);
7043 /* ---------------------------------------------------------------------------------------------------- */
7045 /* called in GDBusWorker thread with connection's lock held */
7047 distribute_method_call (GDBusConnection *connection,
7048 GDBusMessage *message)
7050 GDBusMessage *reply;
7052 ExportedSubtree *es;
7053 const gchar *object_path;
7054 const gchar *interface_name;
7055 const gchar *member;
7057 gchar *subtree_path;
7060 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7062 interface_name = g_dbus_message_get_interface (message);
7063 member = g_dbus_message_get_member (message);
7064 path = g_dbus_message_get_path (message);
7065 subtree_path = g_strdup (path);
7066 needle = strrchr (subtree_path, '/');
7067 if (needle != NULL && needle != subtree_path)
7073 g_free (subtree_path);
7074 subtree_path = NULL;
7078 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7080 _g_dbus_debug_print_lock ();
7081 g_print ("========================================================================\n"
7082 "GDBus-debug:Incoming:\n"
7083 " <<<< METHOD INVOCATION %s.%s()\n"
7085 " invoked by name %s\n"
7087 interface_name, member,
7089 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7090 g_dbus_message_get_serial (message));
7091 _g_dbus_debug_print_unlock ();
7094 object_path = g_dbus_message_get_path (message);
7095 g_assert (object_path != NULL);
7097 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7100 if (obj_message_func (connection, eo, message))
7104 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7107 if (subtree_message_func (connection, es, message))
7111 if (subtree_path != NULL)
7113 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7116 if (subtree_message_func (connection, es, message))
7121 if (handle_generic_unlocked (connection, message))
7124 /* if we end up here, the message has not been not handled - so return an error saying this */
7125 reply = g_dbus_message_new_method_error (message,
7126 "org.freedesktop.DBus.Error.UnknownMethod",
7127 _("No such interface ā%sā on object at path %s"),
7130 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7131 g_object_unref (reply);
7134 g_free (subtree_path);
7137 /* ---------------------------------------------------------------------------------------------------- */
7139 /* Called in any user thread, with the message_bus_lock held. */
7141 message_bus_get_singleton (GBusType bus_type,
7145 const gchar *starter_bus;
7151 case G_BUS_TYPE_SESSION:
7152 ret = &the_session_bus;
7155 case G_BUS_TYPE_SYSTEM:
7156 ret = &the_system_bus;
7159 case G_BUS_TYPE_STARTER:
7160 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7161 if (g_strcmp0 (starter_bus, "session") == 0)
7163 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7166 else if (g_strcmp0 (starter_bus, "system") == 0)
7168 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7173 if (starter_bus != NULL)
7177 G_IO_ERROR_INVALID_ARGUMENT,
7178 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7179 " ā unknown value ā%sā"),
7184 g_set_error_literal (error,
7186 G_IO_ERROR_INVALID_ARGUMENT,
7187 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7188 "variable is not set"));
7194 g_assert_not_reached ();
7202 /* Called in any user thread, without holding locks. */
7203 static GDBusConnection *
7204 get_uninitialized_connection (GBusType bus_type,
7205 GCancellable *cancellable,
7208 GWeakRef *singleton;
7209 GDBusConnection *ret;
7213 G_LOCK (message_bus_lock);
7214 singleton = message_bus_get_singleton (bus_type, error);
7215 if (singleton == NULL)
7218 ret = g_weak_ref_get (singleton);
7223 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7224 if (address == NULL)
7226 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7228 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7229 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7230 "exit-on-close", TRUE,
7233 g_weak_ref_set (singleton, ret);
7237 g_assert (ret != NULL);
7240 G_UNLOCK (message_bus_lock);
7244 /* May be called from any thread. Must not hold message_bus_lock. */
7246 _g_bus_get_singleton_if_exists (GBusType bus_type)
7248 GWeakRef *singleton;
7249 GDBusConnection *ret = NULL;
7251 G_LOCK (message_bus_lock);
7252 singleton = message_bus_get_singleton (bus_type, NULL);
7253 if (singleton == NULL)
7256 ret = g_weak_ref_get (singleton);
7259 G_UNLOCK (message_bus_lock);
7263 /* May be called from any thread. Must not hold message_bus_lock. */
7265 _g_bus_forget_singleton (GBusType bus_type)
7267 GWeakRef *singleton;
7269 G_LOCK (message_bus_lock);
7271 singleton = message_bus_get_singleton (bus_type, NULL);
7273 if (singleton != NULL)
7274 g_weak_ref_set (singleton, NULL);
7276 G_UNLOCK (message_bus_lock);
7281 * @bus_type: a #GBusType
7282 * @cancellable: (nullable): a #GCancellable or %NULL
7283 * @error: return location for error or %NULL
7285 * Synchronously connects to the message bus specified by @bus_type.
7286 * Note that the returned object may shared with other callers,
7287 * e.g. if two separate parts of a process calls this function with
7288 * the same @bus_type, they will share the same object.
7290 * This is a synchronous failable function. See g_bus_get() and
7291 * g_bus_get_finish() for the asynchronous version.
7293 * The returned object is a singleton, that is, shared with other
7294 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7295 * event that you need a private message bus connection, use
7296 * g_dbus_address_get_for_bus_sync() and
7297 * g_dbus_connection_new_for_address().
7299 * Note that the returned #GDBusConnection object will (usually) have
7300 * the #GDBusConnection:exit-on-close property set to %TRUE.
7302 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7303 * Free with g_object_unref().
7308 g_bus_get_sync (GBusType bus_type,
7309 GCancellable *cancellable,
7312 GDBusConnection *connection;
7314 _g_dbus_initialize ();
7316 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7318 connection = get_uninitialized_connection (bus_type, cancellable, error);
7319 if (connection == NULL)
7322 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7324 g_object_unref (connection);
7333 bus_get_async_initable_cb (GObject *source_object,
7337 GTask *task = user_data;
7338 GError *error = NULL;
7340 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7344 g_assert (error != NULL);
7345 g_task_return_error (task, error);
7346 g_object_unref (source_object);
7350 g_task_return_pointer (task, source_object, g_object_unref);
7352 g_object_unref (task);
7357 * @bus_type: a #GBusType
7358 * @cancellable: (nullable): a #GCancellable or %NULL
7359 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7360 * @user_data: the data to pass to @callback
7362 * Asynchronously connects to the message bus specified by @bus_type.
7364 * When the operation is finished, @callback will be invoked. You can
7365 * then call g_bus_get_finish() to get the result of the operation.
7367 * This is an asynchronous failable function. See g_bus_get_sync() for
7368 * the synchronous version.
7373 g_bus_get (GBusType bus_type,
7374 GCancellable *cancellable,
7375 GAsyncReadyCallback callback,
7378 GDBusConnection *connection;
7380 GError *error = NULL;
7382 _g_dbus_initialize ();
7384 task = g_task_new (NULL, cancellable, callback, user_data);
7385 g_task_set_source_tag (task, g_bus_get);
7387 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7388 if (connection == NULL)
7390 g_assert (error != NULL);
7391 g_task_return_error (task, error);
7392 g_object_unref (task);
7396 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7399 bus_get_async_initable_cb,
7406 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7408 * @error: return location for error or %NULL
7410 * Finishes an operation started with g_bus_get().
7412 * The returned object is a singleton, that is, shared with other
7413 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7414 * event that you need a private message bus connection, use
7415 * g_dbus_address_get_for_bus_sync() and
7416 * g_dbus_connection_new_for_address().
7418 * Note that the returned #GDBusConnection object will (usually) have
7419 * the #GDBusConnection:exit-on-close property set to %TRUE.
7421 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7422 * Free with g_object_unref().
7427 g_bus_get_finish (GAsyncResult *res,
7430 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7431 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7433 return g_task_propagate_pointer (G_TASK (res), error);
7436 /* ---------------------------------------------------------------------------------------------------- */