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"
116 #include "gunixconnection.h"
117 #include "gunixfdmessage.h"
120 #include "glibintl.h"
123 * SECTION:gdbusconnection
124 * @short_description: D-Bus Connections
125 * @include: gio/gio.h
127 * The #GDBusConnection type is used for D-Bus connections to remote
128 * peers such as a message buses. It is a low-level API that offers a
129 * lot of flexibility. For instance, it lets you establish a connection
130 * over any transport that can by represented as an #GIOStream.
132 * This class is rarely used directly in D-Bus clients. If you are writing
133 * a D-Bus client, it is often easier to use the g_bus_own_name(),
134 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
136 * As an exception to the usual GLib rule that a particular object must not
137 * be used by two threads at the same time, #GDBusConnection's methods may be
138 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
139 * can safely return the same #GDBusConnection when called from any thread.
141 * Most of the ways to obtain a #GDBusConnection automatically initialize it
142 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
143 * g_bus_get(), and the synchronous versions of those methods, give you an
144 * initialized connection. Language bindings for GIO should use
145 * g_initable_new() or g_async_initable_new_async(), which also initialize the
148 * If you construct an uninitialized #GDBusConnection, such as via
149 * g_object_new(), you must initialize it via g_initable_init() or
150 * g_async_initable_init_async() before using its methods or properties.
151 * Calling methods or accessing properties on a #GDBusConnection that has not
152 * completed initialization successfully is considered to be invalid, and leads
153 * to undefined behaviour. In particular, if initialization fails with a
154 * #GError, the only valid thing you can do with that #GDBusConnection is to
155 * free it with g_object_unref().
157 * ## An example D-Bus server # {#gdbus-server}
159 * Here is an example for a D-Bus server:
160 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
162 * ## An example for exporting a subtree # {#gdbus-subtree-server}
164 * Here is an example for exporting a subtree:
165 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
167 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
169 * Here is an example for passing UNIX file descriptors:
170 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-unix-fd-client.c)
172 * ## An example for exporting a GObject # {#gdbus-export}
174 * Here is an example for exporting a #GObject:
175 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
178 /* ---------------------------------------------------------------------------------------------------- */
180 typedef struct _GDBusConnectionClass GDBusConnectionClass;
183 * GDBusConnectionClass:
184 * @closed: Signal class handler for the #GDBusConnection::closed signal.
186 * Class structure for #GDBusConnection.
190 struct _GDBusConnectionClass
193 GObjectClass parent_class;
197 void (*closed) (GDBusConnection *connection,
198 gboolean remote_peer_vanished,
202 G_LOCK_DEFINE_STATIC (message_bus_lock);
204 static GWeakRef the_session_bus;
205 static GWeakRef the_system_bus;
207 /* Extra pseudo-member of GDBusSendMessageFlags.
208 * Set by initable_init() to indicate that despite not being initialized yet,
209 * enough of the only-valid-after-init members are set that we can send a
210 * message, and we're being called from its thread, so no memory barrier is
211 * required before accessing them.
213 #define SEND_MESSAGE_FLAGS_INITIALIZING (1u << 31)
215 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
216 #define CALL_FLAGS_INITIALIZING (1u << 31)
218 /* ---------------------------------------------------------------------------------------------------- */
222 GDestroyNotify callback;
224 GMainContext *context;
225 } CallDestroyNotifyData;
228 call_destroy_notify_data_in_idle (gpointer user_data)
230 CallDestroyNotifyData *data = user_data;
231 data->callback (data->user_data);
236 call_destroy_notify_data_free (CallDestroyNotifyData *data)
238 if (data->context != NULL)
239 g_main_context_unref (data->context);
244 * call_destroy_notify: <internal>
245 * @context: (nullable): A #GMainContext or %NULL.
246 * @callback: (nullable): A #GDestroyNotify or %NULL.
247 * @user_data: Data to pass to @callback.
249 * Schedules @callback to run in @context.
252 call_destroy_notify (GMainContext *context,
253 GDestroyNotify callback,
256 GSource *idle_source;
257 CallDestroyNotifyData *data;
259 if (callback == NULL)
262 data = g_new0 (CallDestroyNotifyData, 1);
263 data->callback = callback;
264 data->user_data = user_data;
265 data->context = context;
266 if (data->context != NULL)
267 g_main_context_ref (data->context);
269 idle_source = g_idle_source_new ();
270 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
271 g_source_set_callback (idle_source,
272 call_destroy_notify_data_in_idle,
274 (GDestroyNotify) call_destroy_notify_data_free);
275 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
276 g_source_attach (idle_source, data->context);
277 g_source_unref (idle_source);
283 /* ---------------------------------------------------------------------------------------------------- */
286 _g_strv_has_string (const gchar* const *haystack,
291 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
293 if (g_strcmp0 (haystack[n], needle) == 0)
299 /* ---------------------------------------------------------------------------------------------------- */
302 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
304 // TODO: for some reason this doesn't work on Windows
305 #define CONNECTION_ENSURE_LOCK(obj) do { \
306 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
308 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
309 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
314 #define CONNECTION_LOCK(obj) do { \
315 g_mutex_lock (&(obj)->lock); \
318 #define CONNECTION_UNLOCK(obj) do { \
319 g_mutex_unlock (&(obj)->lock); \
322 /* Flags in connection->atomic_flags */
324 FLAG_INITIALIZED = 1 << 0,
325 FLAG_EXIT_ON_CLOSE = 1 << 1,
332 * The #GDBusConnection structure contains only private data and
333 * should only be accessed using the provided API.
337 struct _GDBusConnection
340 GObject parent_instance;
342 /* ------------------------------------------------------------------------ */
343 /* -- General object state ------------------------------------------------ */
344 /* ------------------------------------------------------------------------ */
346 /* General-purpose lock for most fields */
349 /* A lock used in the init() method of the GInitable interface - see comments
350 * in initable_init() for why a separate lock is needed.
352 * If you need both @lock and @init_lock, you must take @init_lock first.
356 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
357 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
361 /* The underlying stream used for communication
362 * Read-only after initable_init(), so it may be read if you either
363 * hold @init_lock or check for initialization first.
367 /* The object used for authentication (if any).
368 * Read-only after initable_init(), so it may be read if you either
369 * hold @init_lock or check for initialization first.
373 /* Last serial used. Protected by @lock. */
376 /* The object used to send/receive messages.
377 * Read-only after initable_init(), so it may be read if you either
378 * hold @init_lock or check for initialization first.
382 /* If connected to a message bus, this contains the unique name assigned to
383 * us by the bus (e.g. ":1.42").
384 * Read-only after initable_init(), so it may be read if you either
385 * hold @init_lock or check for initialization first.
387 gchar *bus_unique_name;
389 /* The GUID returned by the other side if we authenticed as a client or
390 * the GUID to use if authenticating as a server.
391 * Read-only after initable_init(), so it may be read if you either
392 * hold @init_lock or check for initialization first.
396 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
397 * Inspect @initialization_error to see whether it succeeded or failed.
399 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
401 * FLAG_CLOSED is the closed property. It may be read at any time, but
402 * may only be written while holding @lock.
404 volatile gint atomic_flags;
406 /* If the connection could not be established during initable_init(),
407 * this GError will be set.
408 * Read-only after initable_init(), so it may be read if you either
409 * hold @init_lock or check for initialization first.
411 GError *initialization_error;
413 /* The result of g_main_context_ref_thread_default() when the object
414 * was created (the GObject _init() function) - this is used for delivery
415 * of the :closed GObject signal.
417 * Only set in the GObject init function, so no locks are needed.
419 GMainContext *main_context_at_construction;
421 /* Read-only construct properties, no locks needed */
423 GDBusConnectionFlags flags;
425 /* Map used for managing method replies, protected by @lock */
426 GHashTable *map_method_serial_to_task; /* guint32 -> GTask* */
428 /* Maps used for managing signal subscription, protected by @lock */
429 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
430 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
431 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
433 /* Maps used for managing exported objects and subtrees,
436 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
437 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
438 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
439 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
441 /* Map used for storing last used serials for each thread, protected by @lock */
442 GHashTable *map_thread_to_last_serial;
444 /* Structure used for message filters, protected by @lock */
447 /* Capabilities negotiated during authentication
448 * Read-only after initable_init(), so it may be read without holding a
449 * lock, if you check for initialization first.
451 GDBusCapabilityFlags capabilities;
453 /* Protected by @init_lock */
454 GDBusAuthObserver *authentication_observer;
456 /* Read-only after initable_init(), so it may be read if you either
457 * hold @init_lock or check for initialization first.
459 GCredentials *credentials;
461 /* set to TRUE when finalizing */
465 typedef struct ExportedObject ExportedObject;
466 static void exported_object_free (ExportedObject *eo);
468 typedef struct ExportedSubtree ExportedSubtree;
469 static void exported_subtree_free (ExportedSubtree *es);
487 PROP_CAPABILITY_FLAGS,
488 PROP_AUTHENTICATION_OBSERVER,
491 static void distribute_signals (GDBusConnection *connection,
492 GDBusMessage *message);
494 static void distribute_method_call (GDBusConnection *connection,
495 GDBusMessage *message);
497 static gboolean handle_generic_unlocked (GDBusConnection *connection,
498 GDBusMessage *message);
501 static void purge_all_signal_subscriptions (GDBusConnection *connection);
502 static void purge_all_filters (GDBusConnection *connection);
504 static void schedule_method_call (GDBusConnection *connection,
505 GDBusMessage *message,
506 guint registration_id,
507 guint subtree_registration_id,
508 const GDBusInterfaceInfo *interface_info,
509 const GDBusMethodInfo *method_info,
510 const GDBusPropertyInfo *property_info,
511 GVariant *parameters,
512 const GDBusInterfaceVTable *vtable,
513 GMainContext *main_context,
516 #define _G_ENSURE_LOCK(name) do { \
517 if (G_UNLIKELY (G_TRYLOCK(name))) \
519 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
520 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
524 static guint signals[LAST_SIGNAL] = { 0 };
526 static void initable_iface_init (GInitableIface *initable_iface);
527 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
529 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
530 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
531 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
535 * Check that all members of @connection that can only be accessed after
536 * the connection is initialized can safely be accessed. If not,
537 * log a critical warning. This function is a memory barrier.
539 * Returns: %TRUE if initialized
542 check_initialized (GDBusConnection *connection)
544 /* The access to @atomic_flags isn't conditional, so that this function
545 * provides a memory barrier for thread-safety even if checks are disabled.
546 * (If you don't want this stricter guarantee, you can call
547 * g_return_if_fail (check_initialized (c)).)
549 * This isn't strictly necessary now that we've decided use of an
550 * uninitialized GDBusConnection is undefined behaviour, but it seems
551 * better to be as deterministic as is feasible.
553 * (Anything that could suffer a crash from seeing undefined values
554 * must have a race condition - thread A initializes the connection while
555 * thread B calls a method without initialization, hoping that thread A will
556 * win the race - so its behaviour is undefined anyway.)
558 gint flags = g_atomic_int_get (&connection->atomic_flags);
560 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
562 /* We can safely access this, due to the memory barrier above */
563 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
569 MAY_BE_UNINITIALIZED = (1<<1)
570 } CheckUnclosedFlags;
573 * Check the same thing as check_initialized(), and also that the
574 * connection is not closed. If the connection is uninitialized,
575 * raise a critical warning (it's programmer error); if it's closed,
576 * raise a recoverable GError (it's a runtime error).
578 * This function is a memory barrier.
580 * Returns: %TRUE if initialized and not closed
583 check_unclosed (GDBusConnection *connection,
584 CheckUnclosedFlags check,
587 /* check_initialized() is effectively inlined, so we don't waste time
588 * doing two memory barriers
590 gint flags = g_atomic_int_get (&connection->atomic_flags);
592 if (!(check & MAY_BE_UNINITIALIZED))
594 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
595 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
598 if (flags & FLAG_CLOSED)
600 g_set_error_literal (error,
603 _("The connection is closed"));
610 static GHashTable *alive_connections = NULL;
613 g_dbus_connection_dispose (GObject *object)
615 GDBusConnection *connection = G_DBUS_CONNECTION (object);
617 G_LOCK (message_bus_lock);
618 CONNECTION_LOCK (connection);
619 if (connection->worker != NULL)
621 _g_dbus_worker_stop (connection->worker);
622 connection->worker = NULL;
623 if (alive_connections != NULL)
624 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
628 if (alive_connections != NULL)
629 g_warn_if_fail (!g_hash_table_contains (alive_connections, connection));
631 CONNECTION_UNLOCK (connection);
632 G_UNLOCK (message_bus_lock);
634 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
635 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
639 g_dbus_connection_finalize (GObject *object)
641 GDBusConnection *connection = G_DBUS_CONNECTION (object);
643 connection->finalizing = TRUE;
645 purge_all_signal_subscriptions (connection);
647 purge_all_filters (connection);
648 g_ptr_array_unref (connection->filters);
650 if (connection->authentication_observer != NULL)
651 g_object_unref (connection->authentication_observer);
653 if (connection->auth != NULL)
654 g_object_unref (connection->auth);
656 if (connection->credentials)
657 g_object_unref (connection->credentials);
659 if (connection->stream != NULL)
661 g_object_unref (connection->stream);
662 connection->stream = NULL;
665 g_free (connection->address);
667 g_free (connection->guid);
668 g_free (connection->bus_unique_name);
670 if (connection->initialization_error != NULL)
671 g_error_free (connection->initialization_error);
673 g_hash_table_unref (connection->map_method_serial_to_task);
675 g_hash_table_unref (connection->map_rule_to_signal_data);
676 g_hash_table_unref (connection->map_id_to_signal_data);
677 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
679 g_hash_table_unref (connection->map_id_to_ei);
680 g_hash_table_unref (connection->map_object_path_to_eo);
681 g_hash_table_unref (connection->map_id_to_es);
682 g_hash_table_unref (connection->map_object_path_to_es);
684 g_hash_table_unref (connection->map_thread_to_last_serial);
686 g_main_context_unref (connection->main_context_at_construction);
688 g_free (connection->machine_id);
690 g_mutex_clear (&connection->init_lock);
691 g_mutex_clear (&connection->lock);
693 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
696 /* called in any user thread, with the connection's lock not held */
698 g_dbus_connection_get_property (GObject *object,
703 GDBusConnection *connection = G_DBUS_CONNECTION (object);
708 g_value_set_object (value, g_dbus_connection_get_stream (connection));
712 g_value_set_string (value, g_dbus_connection_get_guid (connection));
715 case PROP_UNIQUE_NAME:
716 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
720 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
723 case PROP_EXIT_ON_CLOSE:
724 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
727 case PROP_CAPABILITY_FLAGS:
728 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
732 g_value_set_flags (value, g_dbus_connection_get_flags (connection));
736 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
741 /* called in any user thread, with the connection's lock not held */
743 g_dbus_connection_set_property (GObject *object,
748 GDBusConnection *connection = G_DBUS_CONNECTION (object);
753 connection->stream = g_value_dup_object (value);
757 connection->guid = g_value_dup_string (value);
761 connection->address = g_value_dup_string (value);
765 connection->flags = g_value_get_flags (value);
768 case PROP_EXIT_ON_CLOSE:
769 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
772 case PROP_AUTHENTICATION_OBSERVER:
773 connection->authentication_observer = g_value_dup_object (value);
777 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
782 /* Base-class implementation of GDBusConnection::closed.
784 * Called in a user thread, by the main context that was thread-default when
785 * the object was constructed.
788 g_dbus_connection_real_closed (GDBusConnection *connection,
789 gboolean remote_peer_vanished,
792 gint flags = g_atomic_int_get (&connection->atomic_flags);
794 /* Because atomic int access is a memory barrier, we can safely read
795 * initialization_error without a lock, as long as we do it afterwards.
797 if (remote_peer_vanished &&
798 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
799 (flags & FLAG_INITIALIZED) != 0 &&
800 connection->initialization_error == NULL)
807 g_dbus_connection_class_init (GDBusConnectionClass *klass)
809 GObjectClass *gobject_class;
811 gobject_class = G_OBJECT_CLASS (klass);
813 gobject_class->finalize = g_dbus_connection_finalize;
814 gobject_class->dispose = g_dbus_connection_dispose;
815 gobject_class->set_property = g_dbus_connection_set_property;
816 gobject_class->get_property = g_dbus_connection_get_property;
818 klass->closed = g_dbus_connection_real_closed;
821 * GDBusConnection:stream:
823 * The underlying #GIOStream used for I/O.
825 * If this is passed on construction and is a #GSocketConnection,
826 * then the corresponding #GSocket will be put into non-blocking mode.
828 * While the #GDBusConnection is active, it will interact with this
829 * stream from a worker thread, so it is not safe to interact with
830 * the stream directly.
834 g_object_class_install_property (gobject_class,
836 g_param_spec_object ("stream",
838 P_("The underlying streams used for I/O"),
842 G_PARAM_CONSTRUCT_ONLY |
843 G_PARAM_STATIC_NAME |
844 G_PARAM_STATIC_BLURB |
845 G_PARAM_STATIC_NICK));
848 * GDBusConnection:address:
850 * A D-Bus address specifying potential endpoints that can be used
851 * when establishing the connection.
855 g_object_class_install_property (gobject_class,
857 g_param_spec_string ("address",
859 P_("D-Bus address specifying potential socket endpoints"),
862 G_PARAM_CONSTRUCT_ONLY |
863 G_PARAM_STATIC_NAME |
864 G_PARAM_STATIC_BLURB |
865 G_PARAM_STATIC_NICK));
868 * GDBusConnection:flags:
870 * Flags from the #GDBusConnectionFlags enumeration.
874 g_object_class_install_property (gobject_class,
876 g_param_spec_flags ("flags",
879 G_TYPE_DBUS_CONNECTION_FLAGS,
880 G_DBUS_CONNECTION_FLAGS_NONE,
883 G_PARAM_CONSTRUCT_ONLY |
884 G_PARAM_STATIC_NAME |
885 G_PARAM_STATIC_BLURB |
886 G_PARAM_STATIC_NICK));
889 * GDBusConnection:guid:
891 * The GUID of the peer performing the role of server when
894 * If you are constructing a #GDBusConnection and pass
895 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
896 * #GDBusConnection:flags property then you MUST also set this
897 * property to a valid guid.
899 * If you are constructing a #GDBusConnection and pass
900 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
901 * #GDBusConnection:flags property you will be able to read the GUID
902 * of the other peer here after the connection has been successfully
907 g_object_class_install_property (gobject_class,
909 g_param_spec_string ("guid",
911 P_("GUID of the server peer"),
915 G_PARAM_CONSTRUCT_ONLY |
916 G_PARAM_STATIC_NAME |
917 G_PARAM_STATIC_BLURB |
918 G_PARAM_STATIC_NICK));
921 * GDBusConnection:unique-name:
923 * The unique name as assigned by the message bus or %NULL if the
924 * connection is not open or not a message bus connection.
928 g_object_class_install_property (gobject_class,
930 g_param_spec_string ("unique-name",
932 P_("Unique name of bus connection"),
935 G_PARAM_STATIC_NAME |
936 G_PARAM_STATIC_BLURB |
937 G_PARAM_STATIC_NICK));
940 * GDBusConnection:closed:
942 * A boolean specifying whether the connection has been closed.
946 g_object_class_install_property (gobject_class,
948 g_param_spec_boolean ("closed",
950 P_("Whether the connection is closed"),
953 G_PARAM_STATIC_NAME |
954 G_PARAM_STATIC_BLURB |
955 G_PARAM_STATIC_NICK));
958 * GDBusConnection:exit-on-close:
960 * A boolean specifying whether the process will be terminated (by
961 * calling `raise(SIGTERM)`) if the connection is closed by the
964 * Note that #GDBusConnection objects returned by g_bus_get_finish()
965 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
969 g_object_class_install_property (gobject_class,
971 g_param_spec_boolean ("exit-on-close",
973 P_("Whether the process is terminated when the connection is closed"),
977 G_PARAM_STATIC_NAME |
978 G_PARAM_STATIC_BLURB |
979 G_PARAM_STATIC_NICK));
982 * GDBusConnection:capabilities:
984 * Flags from the #GDBusCapabilityFlags enumeration
985 * representing connection features negotiated with the other peer.
989 g_object_class_install_property (gobject_class,
990 PROP_CAPABILITY_FLAGS,
991 g_param_spec_flags ("capabilities",
994 G_TYPE_DBUS_CAPABILITY_FLAGS,
995 G_DBUS_CAPABILITY_FLAGS_NONE,
997 G_PARAM_STATIC_NAME |
998 G_PARAM_STATIC_BLURB |
999 G_PARAM_STATIC_NICK));
1002 * GDBusConnection:authentication-observer:
1004 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1008 g_object_class_install_property (gobject_class,
1009 PROP_AUTHENTICATION_OBSERVER,
1010 g_param_spec_object ("authentication-observer",
1011 P_("Authentication Observer"),
1012 P_("Object used to assist in the authentication process"),
1013 G_TYPE_DBUS_AUTH_OBSERVER,
1015 G_PARAM_CONSTRUCT_ONLY |
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection::closed:
1022 * @connection: the #GDBusConnection emitting the signal
1023 * @remote_peer_vanished: %TRUE if @connection is closed because the
1024 * remote peer closed its end of the connection
1025 * @error: (nullable): a #GError with more details about the event or %NULL
1027 * Emitted when the connection is closed.
1029 * The cause of this event can be
1031 * - If g_dbus_connection_close() is called. In this case
1032 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1034 * - If the remote peer closes the connection. In this case
1035 * @remote_peer_vanished is set to %TRUE and @error is set.
1037 * - If the remote peer sends invalid or malformed data. In this
1038 * case @remote_peer_vanished is set to %FALSE and @error is set.
1040 * Upon receiving this signal, you should give up your reference to
1041 * @connection. You are guaranteed that this signal is emitted only
1046 signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1047 G_TYPE_DBUS_CONNECTION,
1049 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1060 g_dbus_connection_init (GDBusConnection *connection)
1062 g_mutex_init (&connection->lock);
1063 g_mutex_init (&connection->init_lock);
1065 connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1067 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1069 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1071 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1074 (GDestroyNotify) g_ptr_array_unref);
1076 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1079 (GDestroyNotify) exported_object_free);
1081 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1084 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1087 (GDestroyNotify) exported_subtree_free);
1089 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1092 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1095 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1097 connection->filters = g_ptr_array_new ();
1101 * g_dbus_connection_get_stream:
1102 * @connection: a #GDBusConnection
1104 * Gets the underlying stream used for IO.
1106 * While the #GDBusConnection is active, it will interact with this
1107 * stream from a worker thread, so it is not safe to interact with
1108 * the stream directly.
1110 * Returns: (transfer none): the stream used for IO
1115 g_dbus_connection_get_stream (GDBusConnection *connection)
1117 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1119 /* do not use g_return_val_if_fail(), we want the memory barrier */
1120 if (!check_initialized (connection))
1123 return connection->stream;
1127 * g_dbus_connection_start_message_processing:
1128 * @connection: a #GDBusConnection
1130 * If @connection was created with
1131 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1132 * starts processing messages. Does nothing on if @connection wasn't
1133 * created with this flag or if the method has already been called.
1138 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1140 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1142 /* do not use g_return_val_if_fail(), we want the memory barrier */
1143 if (!check_initialized (connection))
1146 g_assert (connection->worker != NULL);
1147 _g_dbus_worker_unfreeze (connection->worker);
1151 * g_dbus_connection_is_closed:
1152 * @connection: a #GDBusConnection
1154 * Gets whether @connection is closed.
1156 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1161 g_dbus_connection_is_closed (GDBusConnection *connection)
1165 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1167 flags = g_atomic_int_get (&connection->atomic_flags);
1169 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1173 * g_dbus_connection_get_capabilities:
1174 * @connection: a #GDBusConnection
1176 * Gets the capabilities negotiated with the remote peer
1178 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1182 GDBusCapabilityFlags
1183 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1185 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1187 /* do not use g_return_val_if_fail(), we want the memory barrier */
1188 if (!check_initialized (connection))
1189 return G_DBUS_CAPABILITY_FLAGS_NONE;
1191 return connection->capabilities;
1195 * g_dbus_connection_get_flags:
1196 * @connection: a #GDBusConnection
1198 * Gets the flags used to construct this connection
1200 * Returns: zero or more flags from the #GDBusConnectionFlags enumeration
1204 GDBusConnectionFlags
1205 g_dbus_connection_get_flags (GDBusConnection *connection)
1207 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CONNECTION_FLAGS_NONE);
1209 /* do not use g_return_val_if_fail(), we want the memory barrier */
1210 if (!check_initialized (connection))
1211 return G_DBUS_CONNECTION_FLAGS_NONE;
1213 return connection->flags;
1216 /* ---------------------------------------------------------------------------------------------------- */
1218 /* Called in a temporary thread without holding locks. */
1220 flush_in_thread_func (GTask *task,
1221 gpointer source_object,
1223 GCancellable *cancellable)
1225 GError *error = NULL;
1227 if (g_dbus_connection_flush_sync (source_object,
1230 g_task_return_boolean (task, TRUE);
1232 g_task_return_error (task, error);
1236 * g_dbus_connection_flush:
1237 * @connection: a #GDBusConnection
1238 * @cancellable: (nullable): a #GCancellable or %NULL
1239 * @callback: (nullable): a #GAsyncReadyCallback to call when the
1240 * request is satisfied or %NULL if you don't care about the result
1241 * @user_data: The data to pass to @callback
1243 * Asynchronously flushes @connection, that is, writes all queued
1244 * outgoing message to the transport and then flushes the transport
1245 * (using g_output_stream_flush_async()). This is useful in programs
1246 * that wants to emit a D-Bus signal and then exit immediately. Without
1247 * flushing the connection, there is no guaranteed that the message has
1248 * been sent to the networking buffers in the OS kernel.
1250 * This is an asynchronous method. When the operation is finished,
1251 * @callback will be invoked in the
1252 * [thread-default main context][g-main-context-push-thread-default]
1253 * of the thread you are calling this method from. You can
1254 * then call g_dbus_connection_flush_finish() to get the result of the
1255 * operation. See g_dbus_connection_flush_sync() for the synchronous
1261 g_dbus_connection_flush (GDBusConnection *connection,
1262 GCancellable *cancellable,
1263 GAsyncReadyCallback callback,
1268 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1270 task = g_task_new (connection, cancellable, callback, user_data);
1271 g_task_set_source_tag (task, g_dbus_connection_flush);
1272 g_task_run_in_thread (task, flush_in_thread_func);
1273 g_object_unref (task);
1277 * g_dbus_connection_flush_finish:
1278 * @connection: a #GDBusConnection
1279 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1280 * to g_dbus_connection_flush()
1281 * @error: return location for error or %NULL
1283 * Finishes an operation started with g_dbus_connection_flush().
1285 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1290 g_dbus_connection_flush_finish (GDBusConnection *connection,
1294 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1295 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1296 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1298 return g_task_propagate_boolean (G_TASK (res), error);
1302 * g_dbus_connection_flush_sync:
1303 * @connection: a #GDBusConnection
1304 * @cancellable: (nullable): a #GCancellable or %NULL
1305 * @error: return location for error or %NULL
1307 * Synchronously flushes @connection. The calling thread is blocked
1308 * until this is done. See g_dbus_connection_flush() for the
1309 * asynchronous version of this method and more details about what it
1312 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1317 g_dbus_connection_flush_sync (GDBusConnection *connection,
1318 GCancellable *cancellable,
1323 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1324 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1328 /* This is only a best-effort attempt to see whether the connection is
1329 * closed, so it doesn't need the lock. If the connection closes just
1330 * after this check, but before scheduling the flush operation, the
1331 * result will be more or less the same as if the connection closed while
1332 * the flush operation was pending - it'll fail with either CLOSED or
1335 if (!check_unclosed (connection, 0, error))
1338 g_assert (connection->worker != NULL);
1340 ret = _g_dbus_worker_flush_sync (connection->worker,
1348 /* ---------------------------------------------------------------------------------------------------- */
1352 GDBusConnection *connection;
1354 gboolean remote_peer_vanished;
1358 emit_closed_data_free (EmitClosedData *data)
1360 g_object_unref (data->connection);
1361 if (data->error != NULL)
1362 g_error_free (data->error);
1366 /* Called in a user thread that has acquired the main context that was
1367 * thread-default when the object was constructed
1370 emit_closed_in_idle (gpointer user_data)
1372 EmitClosedData *data = user_data;
1375 g_object_notify (G_OBJECT (data->connection), "closed");
1376 g_signal_emit (data->connection,
1377 signals[CLOSED_SIGNAL],
1379 data->remote_peer_vanished,
1385 /* Can be called from any thread, must hold lock.
1386 * FLAG_CLOSED must already have been set.
1389 schedule_closed_unlocked (GDBusConnection *connection,
1390 gboolean remote_peer_vanished,
1393 GSource *idle_source;
1394 EmitClosedData *data;
1396 CONNECTION_ENSURE_LOCK (connection);
1398 data = g_new0 (EmitClosedData, 1);
1399 data->connection = g_object_ref (connection);
1400 data->remote_peer_vanished = remote_peer_vanished;
1401 data->error = error != NULL ? g_error_copy (error) : NULL;
1403 idle_source = g_idle_source_new ();
1404 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1405 g_source_set_callback (idle_source,
1406 emit_closed_in_idle,
1408 (GDestroyNotify) emit_closed_data_free);
1409 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1410 g_source_attach (idle_source, connection->main_context_at_construction);
1411 g_source_unref (idle_source);
1414 /* ---------------------------------------------------------------------------------------------------- */
1417 * g_dbus_connection_close:
1418 * @connection: a #GDBusConnection
1419 * @cancellable: (nullable): a #GCancellable or %NULL
1420 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1421 * satisfied or %NULL if you don't care about the result
1422 * @user_data: The data to pass to @callback
1424 * Closes @connection. Note that this never causes the process to
1425 * exit (this might only happen if the other end of a shared message
1426 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1428 * Once the connection is closed, operations such as sending a message
1429 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1430 * will not automatically flush the connection so queued messages may
1431 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1433 * If @connection is already closed, this method fails with
1434 * %G_IO_ERROR_CLOSED.
1436 * When @connection has been closed, the #GDBusConnection::closed
1437 * signal is emitted in the
1438 * [thread-default main context][g-main-context-push-thread-default]
1439 * of the thread that @connection was constructed in.
1441 * This is an asynchronous method. When the operation is finished,
1442 * @callback will be invoked in the
1443 * [thread-default main context][g-main-context-push-thread-default]
1444 * of the thread you are calling this method from. You can
1445 * then call g_dbus_connection_close_finish() to get the result of the
1446 * operation. See g_dbus_connection_close_sync() for the synchronous
1452 g_dbus_connection_close (GDBusConnection *connection,
1453 GCancellable *cancellable,
1454 GAsyncReadyCallback callback,
1459 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1461 /* do not use g_return_val_if_fail(), we want the memory barrier */
1462 if (!check_initialized (connection))
1465 g_assert (connection->worker != NULL);
1467 task = g_task_new (connection, cancellable, callback, user_data);
1468 g_task_set_source_tag (task, g_dbus_connection_close);
1469 _g_dbus_worker_close (connection->worker, task);
1470 g_object_unref (task);
1474 * g_dbus_connection_close_finish:
1475 * @connection: a #GDBusConnection
1476 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1477 * to g_dbus_connection_close()
1478 * @error: return location for error or %NULL
1480 * Finishes an operation started with g_dbus_connection_close().
1482 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1487 g_dbus_connection_close_finish (GDBusConnection *connection,
1491 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1492 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1493 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1495 return g_task_propagate_boolean (G_TASK (res), error);
1500 GAsyncResult *result;
1503 /* Can be called by any thread, without the connection lock */
1505 sync_close_cb (GObject *source_object,
1509 SyncCloseData *data = user_data;
1511 data->result = g_object_ref (res);
1512 g_main_loop_quit (data->loop);
1516 * g_dbus_connection_close_sync:
1517 * @connection: a #GDBusConnection
1518 * @cancellable: (nullable): a #GCancellable or %NULL
1519 * @error: return location for error or %NULL
1521 * Synchronously closes @connection. The calling thread is blocked
1522 * until this is done. See g_dbus_connection_close() for the
1523 * asynchronous version of this method and more details about what it
1526 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1531 g_dbus_connection_close_sync (GDBusConnection *connection,
1532 GCancellable *cancellable,
1537 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1538 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1542 if (check_unclosed (connection, 0, error))
1544 GMainContext *context;
1547 context = g_main_context_new ();
1548 g_main_context_push_thread_default (context);
1549 data.loop = g_main_loop_new (context, TRUE);
1552 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1553 g_main_loop_run (data.loop);
1554 ret = g_dbus_connection_close_finish (connection, data.result, error);
1556 g_object_unref (data.result);
1557 g_main_loop_unref (data.loop);
1558 g_main_context_pop_thread_default (context);
1559 g_main_context_unref (context);
1565 /* ---------------------------------------------------------------------------------------------------- */
1568 * g_dbus_connection_get_last_serial:
1569 * @connection: a #GDBusConnection
1571 * Retrieves the last serial number assigned to a #GDBusMessage on
1572 * the current thread. This includes messages sent via both low-level
1573 * API such as g_dbus_connection_send_message() as well as
1574 * high-level API such as g_dbus_connection_emit_signal(),
1575 * g_dbus_connection_call() or g_dbus_proxy_call().
1577 * Returns: the last used serial or zero when no message has been sent
1578 * within the current thread
1583 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1587 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1589 CONNECTION_LOCK (connection);
1590 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1592 CONNECTION_UNLOCK (connection);
1597 /* ---------------------------------------------------------------------------------------------------- */
1599 /* Can be called by any thread, with the connection lock held */
1601 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1602 GDBusMessage *message,
1603 GDBusSendMessageFlags flags,
1604 volatile guint32 *out_serial,
1609 guint32 serial_to_use;
1612 CONNECTION_ENSURE_LOCK (connection);
1614 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1615 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1617 /* TODO: check all necessary headers are present */
1622 if (out_serial != NULL)
1625 /* If we're in initable_init(), don't check for being initialized, to avoid
1626 * chicken-and-egg problems. initable_init() is responsible for setting up
1627 * our prerequisites (mainly connection->worker), and only calling us
1628 * from its own thread (so no memory barrier is needed).
1630 if (!check_unclosed (connection,
1631 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1635 blob = g_dbus_message_to_blob (message,
1637 connection->capabilities,
1642 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1643 serial_to_use = g_dbus_message_get_serial (message);
1645 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1650 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1653 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1656 g_assert_not_reached ();
1661 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1662 blob_size, serial_to_use, connection);
1663 g_printerr ("----\n");
1664 hexdump (blob, blob_size);
1665 g_printerr ("----\n");
1668 /* TODO: use connection->auth to encode the blob */
1670 if (out_serial != NULL)
1671 *out_serial = serial_to_use;
1673 /* store used serial for the current thread */
1674 /* TODO: watch the thread disposal and remove associated record
1676 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1678 g_hash_table_replace (connection->map_thread_to_last_serial,
1680 GUINT_TO_POINTER (serial_to_use));
1682 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1683 g_dbus_message_set_serial (message, serial_to_use);
1685 g_dbus_message_lock (message);
1686 _g_dbus_worker_send_message (connection->worker,
1690 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1701 * g_dbus_connection_send_message:
1702 * @connection: a #GDBusConnection
1703 * @message: a #GDBusMessage
1704 * @flags: flags affecting how the message is sent
1705 * @out_serial: (out) (optional): return location for serial number assigned
1706 * to @message when sending it or %NULL
1707 * @error: Return location for error or %NULL
1709 * Asynchronously sends @message to the peer represented by @connection.
1711 * Unless @flags contain the
1712 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1713 * will be assigned by @connection and set on @message via
1714 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1715 * serial number used will be written to this location prior to
1716 * submitting the message to the underlying transport.
1718 * If @connection is closed then the operation will fail with
1719 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1720 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1722 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1723 * for an example of how to use this low-level API to send and receive
1724 * UNIX file descriptors.
1726 * Note that @message must be unlocked, unless @flags contain the
1727 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1729 * Returns: %TRUE if the message was well-formed and queued for
1730 * transmission, %FALSE if @error is set
1735 g_dbus_connection_send_message (GDBusConnection *connection,
1736 GDBusMessage *message,
1737 GDBusSendMessageFlags flags,
1738 volatile guint32 *out_serial,
1743 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1744 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1745 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1746 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1748 CONNECTION_LOCK (connection);
1749 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1750 CONNECTION_UNLOCK (connection);
1754 /* ---------------------------------------------------------------------------------------------------- */
1760 gulong cancellable_handler_id;
1762 GSource *timeout_source;
1767 /* Can be called from any thread with or without lock held */
1769 send_message_data_free (SendMessageData *data)
1771 g_assert (data->timeout_source == NULL);
1772 g_assert (data->cancellable_handler_id == 0);
1774 g_slice_free (SendMessageData, data);
1777 /* ---------------------------------------------------------------------------------------------------- */
1779 /* can be called from any thread with lock held; @task is (transfer full) */
1781 send_message_with_reply_cleanup (GTask *task, gboolean remove)
1783 GDBusConnection *connection = g_task_get_source_object (task);
1784 SendMessageData *data = g_task_get_task_data (task);
1786 CONNECTION_ENSURE_LOCK (connection);
1788 g_assert (!data->delivered);
1790 data->delivered = TRUE;
1792 if (data->timeout_source != NULL)
1794 g_source_destroy (data->timeout_source);
1795 data->timeout_source = NULL;
1797 if (data->cancellable_handler_id > 0)
1799 g_cancellable_disconnect (g_task_get_cancellable (task), data->cancellable_handler_id);
1800 data->cancellable_handler_id = 0;
1805 gboolean removed = g_hash_table_remove (connection->map_method_serial_to_task,
1806 GUINT_TO_POINTER (data->serial));
1807 g_warn_if_fail (removed);
1810 g_object_unref (task);
1813 /* ---------------------------------------------------------------------------------------------------- */
1815 /* Called from GDBus worker thread with lock held; @task is (transfer full). */
1817 send_message_data_deliver_reply_unlocked (GTask *task,
1818 GDBusMessage *reply)
1820 SendMessageData *data = g_task_get_task_data (task);
1822 if (data->delivered)
1825 g_task_return_pointer (task, g_object_ref (reply), g_object_unref);
1827 send_message_with_reply_cleanup (task, TRUE);
1833 /* Called from a user thread, lock is not held */
1835 send_message_data_deliver_error (GTask *task,
1838 const char *message)
1840 GDBusConnection *connection = g_task_get_source_object (task);
1841 SendMessageData *data = g_task_get_task_data (task);
1843 CONNECTION_LOCK (connection);
1844 if (data->delivered)
1846 CONNECTION_UNLOCK (connection);
1850 g_object_ref (task);
1851 send_message_with_reply_cleanup (task, TRUE);
1852 CONNECTION_UNLOCK (connection);
1854 g_task_return_new_error (task, domain, code, "%s", message);
1855 g_object_unref (task);
1858 /* ---------------------------------------------------------------------------------------------------- */
1860 /* Called from a user thread, lock is not held; @task is (transfer full) */
1862 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1864 GTask *task = user_data;
1866 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_CANCELLED,
1867 _("Operation was cancelled"));
1871 /* Can be called from any thread with or without lock held */
1873 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1876 GTask *task = user_data;
1877 GSource *idle_source;
1879 /* postpone cancellation to idle handler since we may be called directly
1880 * via g_cancellable_connect() (e.g. holding lock)
1882 idle_source = g_idle_source_new ();
1883 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
1884 g_task_attach_source (task, idle_source, send_message_with_reply_cancelled_idle_cb);
1885 g_source_unref (idle_source);
1888 /* ---------------------------------------------------------------------------------------------------- */
1890 /* Called from a user thread, lock is not held; @task is (transfer full) */
1892 send_message_with_reply_timeout_cb (gpointer user_data)
1894 GTask *task = user_data;
1896 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
1897 _("Timeout was reached"));
1901 /* ---------------------------------------------------------------------------------------------------- */
1903 /* Called from a user thread, connection's lock is held */
1905 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1906 GDBusMessage *message,
1907 GDBusSendMessageFlags flags,
1909 volatile guint32 *out_serial,
1910 GCancellable *cancellable,
1911 GAsyncReadyCallback callback,
1915 SendMessageData *data;
1916 GError *error = NULL;
1917 volatile guint32 serial;
1919 if (out_serial == NULL)
1920 out_serial = &serial;
1922 if (timeout_msec == -1)
1923 timeout_msec = 25 * 1000;
1925 data = g_slice_new0 (SendMessageData);
1926 task = g_task_new (connection, cancellable, callback, user_data);
1927 g_task_set_source_tag (task,
1928 g_dbus_connection_send_message_with_reply_unlocked);
1929 g_task_set_task_data (task, data, (GDestroyNotify) send_message_data_free);
1931 if (g_task_return_error_if_cancelled (task))
1933 g_object_unref (task);
1937 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1939 g_task_return_error (task, error);
1940 g_object_unref (task);
1943 data->serial = *out_serial;
1945 if (cancellable != NULL)
1947 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1948 G_CALLBACK (send_message_with_reply_cancelled_cb),
1949 g_object_ref (task),
1953 if (timeout_msec != G_MAXINT)
1955 data->timeout_source = g_timeout_source_new (timeout_msec);
1956 g_task_attach_source (task, data->timeout_source,
1957 (GSourceFunc) send_message_with_reply_timeout_cb);
1958 g_source_unref (data->timeout_source);
1961 g_hash_table_insert (connection->map_method_serial_to_task,
1962 GUINT_TO_POINTER (*out_serial),
1963 g_steal_pointer (&task));
1967 * g_dbus_connection_send_message_with_reply:
1968 * @connection: a #GDBusConnection
1969 * @message: a #GDBusMessage
1970 * @flags: flags affecting how the message is sent
1971 * @timeout_msec: the timeout in milliseconds, -1 to use the default
1972 * timeout or %G_MAXINT for no timeout
1973 * @out_serial: (out) (optional): return location for serial number assigned
1974 * to @message when sending it or %NULL
1975 * @cancellable: (nullable): a #GCancellable or %NULL
1976 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
1977 * is satisfied or %NULL if you don't care about the result
1978 * @user_data: The data to pass to @callback
1980 * Asynchronously sends @message to the peer represented by @connection.
1982 * Unless @flags contain the
1983 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1984 * will be assigned by @connection and set on @message via
1985 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1986 * serial number used will be written to this location prior to
1987 * submitting the message to the underlying transport.
1989 * If @connection is closed then the operation will fail with
1990 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1991 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1992 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1994 * This is an asynchronous method. When the operation is finished, @callback
1995 * will be invoked in the
1996 * [thread-default main context][g-main-context-push-thread-default]
1997 * of the thread you are calling this method from. You can then call
1998 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1999 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2001 * Note that @message must be unlocked, unless @flags contain the
2002 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2004 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2005 * for an example of how to use this low-level API to send and receive
2006 * UNIX file descriptors.
2011 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2012 GDBusMessage *message,
2013 GDBusSendMessageFlags flags,
2015 volatile guint32 *out_serial,
2016 GCancellable *cancellable,
2017 GAsyncReadyCallback callback,
2020 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2021 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2022 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2023 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2025 CONNECTION_LOCK (connection);
2026 g_dbus_connection_send_message_with_reply_unlocked (connection,
2034 CONNECTION_UNLOCK (connection);
2038 * g_dbus_connection_send_message_with_reply_finish:
2039 * @connection: a #GDBusConnection
2040 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2041 * g_dbus_connection_send_message_with_reply()
2042 * @error: teturn location for error or %NULL
2044 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2046 * Note that @error is only set if a local in-process error
2047 * occurred. That is to say that the returned #GDBusMessage object may
2048 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2049 * g_dbus_message_to_gerror() to transcode this to a #GError.
2051 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2052 * for an example of how to use this low-level API to send and receive
2053 * UNIX file descriptors.
2055 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2060 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2064 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2065 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
2066 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2068 return g_task_propagate_pointer (G_TASK (res), error);
2071 /* ---------------------------------------------------------------------------------------------------- */
2076 GMainContext *context;
2078 } SendMessageSyncData;
2080 /* Called from a user thread, lock is not held */
2082 send_message_with_reply_sync_cb (GDBusConnection *connection,
2086 SendMessageSyncData *data = user_data;
2087 data->res = g_object_ref (res);
2088 g_main_loop_quit (data->loop);
2092 * g_dbus_connection_send_message_with_reply_sync:
2093 * @connection: a #GDBusConnection
2094 * @message: a #GDBusMessage
2095 * @flags: flags affecting how the message is sent.
2096 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2097 * timeout or %G_MAXINT for no timeout
2098 * @out_serial: (out) (optional): return location for serial number
2099 * assigned to @message when sending it or %NULL
2100 * @cancellable: (nullable): a #GCancellable or %NULL
2101 * @error: return location for error or %NULL
2103 * Synchronously sends @message to the peer represented by @connection
2104 * and blocks the calling thread until a reply is received or the
2105 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2106 * for the asynchronous version of this method.
2108 * Unless @flags contain the
2109 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2110 * will be assigned by @connection and set on @message via
2111 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2112 * serial number used will be written to this location prior to
2113 * submitting the message to the underlying transport.
2115 * If @connection is closed then the operation will fail with
2116 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2117 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2118 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2120 * Note that @error is only set if a local in-process error
2121 * occurred. That is to say that the returned #GDBusMessage object may
2122 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2123 * g_dbus_message_to_gerror() to transcode this to a #GError.
2125 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2126 * for an example of how to use this low-level API to send and receive
2127 * UNIX file descriptors.
2129 * Note that @message must be unlocked, unless @flags contain the
2130 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2132 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2133 * to @message or %NULL if @error is set
2138 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2139 GDBusMessage *message,
2140 GDBusSendMessageFlags flags,
2142 volatile guint32 *out_serial,
2143 GCancellable *cancellable,
2146 SendMessageSyncData data;
2147 GDBusMessage *reply;
2149 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2150 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2151 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2152 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2153 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2156 data.context = g_main_context_new ();
2157 data.loop = g_main_loop_new (data.context, FALSE);
2159 g_main_context_push_thread_default (data.context);
2161 g_dbus_connection_send_message_with_reply (connection,
2167 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2169 g_main_loop_run (data.loop);
2170 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2174 g_main_context_pop_thread_default (data.context);
2176 g_main_context_unref (data.context);
2177 g_main_loop_unref (data.loop);
2179 g_object_unref (data.res);
2184 /* ---------------------------------------------------------------------------------------------------- */
2190 GDBusMessageFilterFunction filter_function;
2192 GDestroyNotify user_data_free_func;
2193 GMainContext *context;
2196 /* requires CONNECTION_LOCK */
2197 static FilterData **
2198 copy_filter_list (GPtrArray *filters)
2203 copy = g_new (FilterData *, filters->len + 1);
2204 for (n = 0; n < filters->len; n++)
2206 copy[n] = filters->pdata[n];
2207 copy[n]->ref_count++;
2214 /* requires CONNECTION_LOCK */
2216 free_filter_list (FilterData **filters)
2220 for (n = 0; filters[n]; n++)
2222 filters[n]->ref_count--;
2223 if (filters[n]->ref_count == 0)
2225 call_destroy_notify (filters[n]->context,
2226 filters[n]->user_data_free_func,
2227 filters[n]->user_data);
2228 g_main_context_unref (filters[n]->context);
2229 g_free (filters[n]);
2235 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2237 on_worker_message_received (GDBusWorker *worker,
2238 GDBusMessage *message,
2241 GDBusConnection *connection;
2242 FilterData **filters;
2246 G_LOCK (message_bus_lock);
2247 alive = g_hash_table_contains (alive_connections, user_data);
2250 G_UNLOCK (message_bus_lock);
2253 connection = G_DBUS_CONNECTION (user_data);
2254 g_object_ref (connection);
2255 G_UNLOCK (message_bus_lock);
2257 //g_debug ("in on_worker_message_received");
2259 g_object_ref (message);
2260 g_dbus_message_lock (message);
2262 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2264 /* First collect the set of callback functions */
2265 CONNECTION_LOCK (connection);
2266 filters = copy_filter_list (connection->filters);
2267 CONNECTION_UNLOCK (connection);
2269 /* then call the filters in order (without holding the lock) */
2270 for (n = 0; filters[n]; n++)
2272 message = filters[n]->filter_function (connection,
2275 filters[n]->user_data);
2276 if (message == NULL)
2278 g_dbus_message_lock (message);
2281 CONNECTION_LOCK (connection);
2282 free_filter_list (filters);
2283 CONNECTION_UNLOCK (connection);
2285 /* Standard dispatch unless the filter ate the message - no need to
2286 * do anything if the message was altered
2288 if (message != NULL)
2290 GDBusMessageType message_type;
2292 message_type = g_dbus_message_get_message_type (message);
2293 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2295 guint32 reply_serial;
2298 reply_serial = g_dbus_message_get_reply_serial (message);
2299 CONNECTION_LOCK (connection);
2300 task = g_hash_table_lookup (connection->map_method_serial_to_task,
2301 GUINT_TO_POINTER (reply_serial));
2304 /* This removes @task from @map_method_serial_to_task. */
2305 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2306 send_message_data_deliver_reply_unlocked (task, message);
2310 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2312 CONNECTION_UNLOCK (connection);
2314 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2316 CONNECTION_LOCK (connection);
2317 distribute_signals (connection, message);
2318 CONNECTION_UNLOCK (connection);
2320 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2322 CONNECTION_LOCK (connection);
2323 distribute_method_call (connection, message);
2324 CONNECTION_UNLOCK (connection);
2328 if (message != NULL)
2329 g_object_unref (message);
2330 g_object_unref (connection);
2333 /* Called in GDBusWorker's thread, lock is not held */
2334 static GDBusMessage *
2335 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2336 GDBusMessage *message,
2339 GDBusConnection *connection;
2340 FilterData **filters;
2344 G_LOCK (message_bus_lock);
2345 alive = g_hash_table_contains (alive_connections, user_data);
2348 G_UNLOCK (message_bus_lock);
2351 connection = G_DBUS_CONNECTION (user_data);
2352 g_object_ref (connection);
2353 G_UNLOCK (message_bus_lock);
2355 //g_debug ("in on_worker_message_about_to_be_sent");
2357 /* First collect the set of callback functions */
2358 CONNECTION_LOCK (connection);
2359 filters = copy_filter_list (connection->filters);
2360 CONNECTION_UNLOCK (connection);
2362 /* then call the filters in order (without holding the lock) */
2363 for (n = 0; filters[n]; n++)
2365 g_dbus_message_lock (message);
2366 message = filters[n]->filter_function (connection,
2369 filters[n]->user_data);
2370 if (message == NULL)
2374 CONNECTION_LOCK (connection);
2375 free_filter_list (filters);
2376 CONNECTION_UNLOCK (connection);
2378 g_object_unref (connection);
2383 /* called with connection lock held, in GDBusWorker thread */
2385 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2387 GTask *task = value;
2388 SendMessageData *data = g_task_get_task_data (task);
2390 if (data->delivered)
2393 g_task_return_new_error (task,
2396 _("The connection is closed"));
2398 /* Ask send_message_with_reply_cleanup not to remove the element from the
2399 * hash table - we're in the middle of a foreach; that would be unsafe.
2400 * Instead, return TRUE from this function so that it gets removed safely.
2402 send_message_with_reply_cleanup (task, FALSE);
2406 /* Called in GDBusWorker's thread - we must not block - without lock held */
2408 on_worker_closed (GDBusWorker *worker,
2409 gboolean remote_peer_vanished,
2413 GDBusConnection *connection;
2415 guint old_atomic_flags;
2417 G_LOCK (message_bus_lock);
2418 alive = g_hash_table_contains (alive_connections, user_data);
2421 G_UNLOCK (message_bus_lock);
2424 connection = G_DBUS_CONNECTION (user_data);
2425 g_object_ref (connection);
2426 G_UNLOCK (message_bus_lock);
2428 //g_debug ("in on_worker_closed: %s", error->message);
2430 CONNECTION_LOCK (connection);
2431 /* Even though this is atomic, we do it inside the lock to avoid breaking
2432 * assumptions in remove_match_rule(). We'd need the lock in a moment
2433 * anyway, so, no loss.
2435 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2437 if (!(old_atomic_flags & FLAG_CLOSED))
2439 g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2440 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2442 CONNECTION_UNLOCK (connection);
2444 g_object_unref (connection);
2447 /* ---------------------------------------------------------------------------------------------------- */
2449 /* Determines the biggest set of capabilities we can support on this
2452 * Called with the init_lock held.
2454 static GDBusCapabilityFlags
2455 get_offered_capabilities_max (GDBusConnection *connection)
2457 GDBusCapabilityFlags ret;
2458 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2460 if (G_IS_UNIX_CONNECTION (connection->stream))
2461 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2466 /* Called in a user thread, lock is not held */
2468 initable_init (GInitable *initable,
2469 GCancellable *cancellable,
2472 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2475 /* This method needs to be idempotent to work with the singleton
2476 * pattern. See the docs for g_initable_init(). We implement this by
2479 * Unfortunately we can't use the main lock since the on_worker_*()
2480 * callbacks above needs the lock during initialization (for message
2481 * bus connections we do a synchronous Hello() call on the bus).
2483 g_mutex_lock (&connection->init_lock);
2487 /* Make this a no-op if we're already initialized (successfully or
2490 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2492 ret = (connection->initialization_error == NULL);
2496 /* Because of init_lock, we can't get here twice in different threads */
2497 g_assert (connection->initialization_error == NULL);
2499 /* The user can pass multiple (but mutally exclusive) construct
2502 * - stream (of type GIOStream)
2503 * - address (of type gchar*)
2505 * At the end of the day we end up with a non-NULL GIOStream
2506 * object in connection->stream.
2508 if (connection->address != NULL)
2510 g_assert (connection->stream == NULL);
2512 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2513 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2515 g_set_error_literal (&connection->initialization_error,
2517 G_IO_ERROR_INVALID_ARGUMENT,
2518 _("Unsupported flags encountered when constructing a client-side connection"));
2522 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2523 NULL, /* TODO: out_guid */
2525 &connection->initialization_error);
2526 if (connection->stream == NULL)
2529 else if (connection->stream != NULL)
2535 g_assert_not_reached ();
2538 /* Authenticate the connection */
2539 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2541 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2542 g_assert (connection->guid != NULL);
2543 connection->auth = _g_dbus_auth_new (connection->stream);
2544 if (!_g_dbus_auth_run_server (connection->auth,
2545 connection->authentication_observer,
2547 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2548 get_offered_capabilities_max (connection),
2549 &connection->capabilities,
2550 &connection->credentials,
2552 &connection->initialization_error))
2555 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2557 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2558 g_assert (connection->guid == NULL);
2559 connection->auth = _g_dbus_auth_new (connection->stream);
2560 connection->guid = _g_dbus_auth_run_client (connection->auth,
2561 connection->authentication_observer,
2562 get_offered_capabilities_max (connection),
2563 &connection->capabilities,
2565 &connection->initialization_error);
2566 if (connection->guid == NULL)
2570 if (connection->authentication_observer != NULL)
2572 g_object_unref (connection->authentication_observer);
2573 connection->authentication_observer = NULL;
2576 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2578 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2581 /* We want all IO operations to be non-blocking since they happen in
2582 * the worker thread which is shared by _all_ connections.
2584 if (G_IS_SOCKET_CONNECTION (connection->stream))
2586 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2590 G_LOCK (message_bus_lock);
2591 if (alive_connections == NULL)
2592 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2593 g_hash_table_add (alive_connections, connection);
2594 G_UNLOCK (message_bus_lock);
2596 connection->worker = _g_dbus_worker_new (connection->stream,
2597 connection->capabilities,
2598 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2599 on_worker_message_received,
2600 on_worker_message_about_to_be_sent,
2604 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2605 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2607 GVariant *hello_result;
2609 /* we could lift this restriction by adding code in gdbusprivate.c */
2610 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2612 g_set_error_literal (&connection->initialization_error,
2615 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2619 hello_result = g_dbus_connection_call_sync (connection,
2620 "org.freedesktop.DBus", /* name */
2621 "/org/freedesktop/DBus", /* path */
2622 "org.freedesktop.DBus", /* interface */
2624 NULL, /* parameters */
2625 G_VARIANT_TYPE ("(s)"),
2626 CALL_FLAGS_INITIALIZING,
2628 NULL, /* TODO: cancellable */
2629 &connection->initialization_error);
2630 if (hello_result == NULL)
2633 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2634 g_variant_unref (hello_result);
2635 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2642 g_assert (connection->initialization_error != NULL);
2643 g_propagate_error (error, g_error_copy (connection->initialization_error));
2646 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2647 g_mutex_unlock (&connection->init_lock);
2653 initable_iface_init (GInitableIface *initable_iface)
2655 initable_iface->init = initable_init;
2658 /* ---------------------------------------------------------------------------------------------------- */
2661 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2666 /* ---------------------------------------------------------------------------------------------------- */
2669 * g_dbus_connection_new:
2670 * @stream: a #GIOStream
2671 * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2672 * @flags: flags describing how to make the connection
2673 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2674 * @cancellable: (nullable): a #GCancellable or %NULL
2675 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2676 * @user_data: the data to pass to @callback
2678 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2679 * with the end represented by @stream.
2681 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2682 * will be put into non-blocking mode.
2684 * The D-Bus connection will interact with @stream from a worker thread.
2685 * As a result, the caller should not interact with @stream after this
2686 * method has been called, except by calling g_object_unref() on it.
2688 * If @observer is not %NULL it may be used to control the
2689 * authentication process.
2691 * When the operation is finished, @callback will be invoked. You can
2692 * then call g_dbus_connection_new_finish() to get the result of the
2695 * This is a asynchronous failable constructor. See
2696 * g_dbus_connection_new_sync() for the synchronous
2702 g_dbus_connection_new (GIOStream *stream,
2704 GDBusConnectionFlags flags,
2705 GDBusAuthObserver *observer,
2706 GCancellable *cancellable,
2707 GAsyncReadyCallback callback,
2710 _g_dbus_initialize ();
2712 g_return_if_fail (G_IS_IO_STREAM (stream));
2714 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2722 "authentication-observer", observer,
2727 * g_dbus_connection_new_finish:
2728 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2729 * passed to g_dbus_connection_new().
2730 * @error: return location for error or %NULL
2732 * Finishes an operation started with g_dbus_connection_new().
2734 * Returns: a #GDBusConnection or %NULL if @error is set. Free
2735 * with g_object_unref().
2740 g_dbus_connection_new_finish (GAsyncResult *res,
2744 GObject *source_object;
2746 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2747 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2749 source_object = g_async_result_get_source_object (res);
2750 g_assert (source_object != NULL);
2751 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2754 g_object_unref (source_object);
2756 return G_DBUS_CONNECTION (object);
2762 * g_dbus_connection_new_sync:
2763 * @stream: a #GIOStream
2764 * @guid: (nullable): the GUID to use if a authenticating as a server or %NULL
2765 * @flags: flags describing how to make the connection
2766 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2767 * @cancellable: (nullable): a #GCancellable or %NULL
2768 * @error: return location for error or %NULL
2770 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2771 * with the end represented by @stream.
2773 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2774 * will be put into non-blocking mode.
2776 * The D-Bus connection will interact with @stream from a worker thread.
2777 * As a result, the caller should not interact with @stream after this
2778 * method has been called, except by calling g_object_unref() on it.
2780 * If @observer is not %NULL it may be used to control the
2781 * authentication process.
2783 * This is a synchronous failable constructor. See
2784 * g_dbus_connection_new() for the asynchronous version.
2786 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2791 g_dbus_connection_new_sync (GIOStream *stream,
2793 GDBusConnectionFlags flags,
2794 GDBusAuthObserver *observer,
2795 GCancellable *cancellable,
2798 _g_dbus_initialize ();
2799 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2800 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2801 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2807 "authentication-observer", observer,
2811 /* ---------------------------------------------------------------------------------------------------- */
2814 * g_dbus_connection_new_for_address:
2815 * @address: a D-Bus address
2816 * @flags: flags describing how to make the connection
2817 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2818 * @cancellable: (nullable): a #GCancellable or %NULL
2819 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2820 * @user_data: the data to pass to @callback
2822 * Asynchronously connects and sets up a D-Bus client connection for
2823 * exchanging D-Bus messages with an endpoint specified by @address
2824 * which must be in the
2825 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2827 * This constructor can only be used to initiate client-side
2828 * connections - use g_dbus_connection_new() if you need to act as the
2829 * server. In particular, @flags cannot contain the
2830 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2831 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2833 * When the operation is finished, @callback will be invoked. You can
2834 * then call g_dbus_connection_new_finish() to get the result of the
2837 * If @observer is not %NULL it may be used to control the
2838 * authentication process.
2840 * This is a asynchronous failable constructor. See
2841 * g_dbus_connection_new_for_address_sync() for the synchronous
2847 g_dbus_connection_new_for_address (const gchar *address,
2848 GDBusConnectionFlags flags,
2849 GDBusAuthObserver *observer,
2850 GCancellable *cancellable,
2851 GAsyncReadyCallback callback,
2854 _g_dbus_initialize ();
2856 g_return_if_fail (address != NULL);
2858 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2865 "authentication-observer", observer,
2870 * g_dbus_connection_new_for_address_finish:
2871 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2872 * to g_dbus_connection_new()
2873 * @error: return location for error or %NULL
2875 * Finishes an operation started with g_dbus_connection_new_for_address().
2877 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2883 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2887 GObject *source_object;
2889 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2890 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2892 source_object = g_async_result_get_source_object (res);
2893 g_assert (source_object != NULL);
2894 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2897 g_object_unref (source_object);
2899 return G_DBUS_CONNECTION (object);
2905 * g_dbus_connection_new_for_address_sync:
2906 * @address: a D-Bus address
2907 * @flags: flags describing how to make the connection
2908 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2909 * @cancellable: (nullable): a #GCancellable or %NULL
2910 * @error: return location for error or %NULL
2912 * Synchronously connects and sets up a D-Bus client connection for
2913 * exchanging D-Bus messages with an endpoint specified by @address
2914 * which must be in the
2915 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2917 * This constructor can only be used to initiate client-side
2918 * connections - use g_dbus_connection_new_sync() if you need to act
2919 * as the server. In particular, @flags cannot contain the
2920 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2921 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2923 * This is a synchronous failable constructor. See
2924 * g_dbus_connection_new_for_address() for the asynchronous version.
2926 * If @observer is not %NULL it may be used to control the
2927 * authentication process.
2929 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2935 g_dbus_connection_new_for_address_sync (const gchar *address,
2936 GDBusConnectionFlags flags,
2937 GDBusAuthObserver *observer,
2938 GCancellable *cancellable,
2941 _g_dbus_initialize ();
2943 g_return_val_if_fail (address != NULL, NULL);
2944 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2945 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2950 "authentication-observer", observer,
2954 /* ---------------------------------------------------------------------------------------------------- */
2957 * g_dbus_connection_set_exit_on_close:
2958 * @connection: a #GDBusConnection
2959 * @exit_on_close: whether the process should be terminated
2960 * when @connection is closed by the remote peer
2962 * Sets whether the process should be terminated when @connection is
2963 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2966 * Note that this function should be used with care. Most modern UNIX
2967 * desktops tie the notion of a user session the session bus, and expect
2968 * all of a users applications to quit when their bus connection goes away.
2969 * If you are setting @exit_on_close to %FALSE for the shared session
2970 * bus connection, you should make sure that your application exits
2971 * when the user session ends.
2976 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2977 gboolean exit_on_close)
2979 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2982 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2984 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2989 * g_dbus_connection_get_exit_on_close:
2990 * @connection: a #GDBusConnection
2992 * Gets whether the process is terminated when @connection is
2993 * closed by the remote peer. See
2994 * #GDBusConnection:exit-on-close for more details.
2996 * Returns: whether the process is terminated when @connection is
2997 * closed by the remote peer
3002 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3004 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3006 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3013 * g_dbus_connection_get_guid:
3014 * @connection: a #GDBusConnection
3016 * The GUID of the peer performing the role of server when
3017 * authenticating. See #GDBusConnection:guid for more details.
3019 * Returns: The GUID. Do not free this string, it is owned by
3025 g_dbus_connection_get_guid (GDBusConnection *connection)
3027 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3028 return connection->guid;
3032 * g_dbus_connection_get_unique_name:
3033 * @connection: a #GDBusConnection
3035 * Gets the unique name of @connection as assigned by the message
3036 * bus. This can also be used to figure out if @connection is a
3037 * message bus connection.
3039 * Returns: (nullable): the unique name or %NULL if @connection is not a message
3040 * bus connection. Do not free this string, it is owned by
3046 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3048 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3050 /* do not use g_return_val_if_fail(), we want the memory barrier */
3051 if (!check_initialized (connection))
3054 return connection->bus_unique_name;
3058 * g_dbus_connection_get_peer_credentials:
3059 * @connection: a #GDBusConnection
3061 * Gets the credentials of the authenticated peer. This will always
3062 * return %NULL unless @connection acted as a server
3063 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3064 * when set up and the client passed credentials as part of the
3065 * authentication process.
3067 * In a message bus setup, the message bus is always the server and
3068 * each application is a client. So this method will always return
3069 * %NULL for message bus clients.
3071 * Returns: (transfer none) (nullable): a #GCredentials or %NULL if not
3072 * available. Do not free this object, it is owned by @connection.
3077 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3079 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3081 /* do not use g_return_val_if_fail(), we want the memory barrier */
3082 if (!check_initialized (connection))
3085 return connection->credentials;
3088 /* ---------------------------------------------------------------------------------------------------- */
3090 static volatile guint _global_filter_id = 1;
3093 * g_dbus_connection_add_filter:
3094 * @connection: a #GDBusConnection
3095 * @filter_function: a filter function
3096 * @user_data: user data to pass to @filter_function
3097 * @user_data_free_func: function to free @user_data with when filter
3098 * is removed or %NULL
3100 * Adds a message filter. Filters are handlers that are run on all
3101 * incoming and outgoing messages, prior to standard dispatch. Filters
3102 * are run in the order that they were added. The same handler can be
3103 * added as a filter more than once, in which case it will be run more
3104 * than once. Filters added during a filter callback won't be run on
3105 * the message being processed. Filter functions are allowed to modify
3106 * and even drop messages.
3108 * Note that filters are run in a dedicated message handling thread so
3109 * they can't block and, generally, can't do anything but signal a
3110 * worker thread. Also note that filters are rarely needed - use API
3111 * such as g_dbus_connection_send_message_with_reply(),
3112 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3114 * If a filter consumes an incoming message the message is not
3115 * dispatched anywhere else - not even the standard dispatch machinery
3116 * (that API such as g_dbus_connection_signal_subscribe() and
3117 * g_dbus_connection_send_message_with_reply() relies on) will see the
3118 * message. Similarly, if a filter consumes an outgoing message, the
3119 * message will not be sent to the other peer.
3121 * If @user_data_free_func is non-%NULL, it will be called (in the
3122 * thread-default main context of the thread you are calling this
3123 * method from) at some point after @user_data is no longer
3124 * needed. (It is not guaranteed to be called synchronously when the
3125 * filter is removed, and may be called after @connection has been
3128 * Returns: a filter identifier that can be used with
3129 * g_dbus_connection_remove_filter()
3134 g_dbus_connection_add_filter (GDBusConnection *connection,
3135 GDBusMessageFilterFunction filter_function,
3137 GDestroyNotify user_data_free_func)
3141 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3142 g_return_val_if_fail (filter_function != NULL, 0);
3143 g_return_val_if_fail (check_initialized (connection), 0);
3145 CONNECTION_LOCK (connection);
3146 data = g_new0 (FilterData, 1);
3147 data->id = g_atomic_int_add (&_global_filter_id, 1); /* TODO: overflow etc. */
3148 data->ref_count = 1;
3149 data->filter_function = filter_function;
3150 data->user_data = user_data;
3151 data->user_data_free_func = user_data_free_func;
3152 data->context = g_main_context_ref_thread_default ();
3153 g_ptr_array_add (connection->filters, data);
3154 CONNECTION_UNLOCK (connection);
3159 /* only called from finalize(), removes all filters */
3161 purge_all_filters (GDBusConnection *connection)
3164 for (n = 0; n < connection->filters->len; n++)
3166 FilterData *data = connection->filters->pdata[n];
3168 call_destroy_notify (data->context,
3169 data->user_data_free_func,
3171 g_main_context_unref (data->context);
3177 * g_dbus_connection_remove_filter:
3178 * @connection: a #GDBusConnection
3179 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3183 * Note that since filters run in a different thread, there is a race
3184 * condition where it is possible that the filter will be running even
3185 * after calling g_dbus_connection_remove_filter(), so you cannot just
3186 * free data that the filter might be using. Instead, you should pass
3187 * a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
3188 * called when it is guaranteed that the data is no longer needed.
3193 g_dbus_connection_remove_filter (GDBusConnection *connection,
3198 FilterData *to_destroy;
3200 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3201 g_return_if_fail (check_initialized (connection));
3203 CONNECTION_LOCK (connection);
3206 for (n = 0; n < connection->filters->len; n++)
3208 FilterData *data = connection->filters->pdata[n];
3209 if (data->id == filter_id)
3212 g_ptr_array_remove_index (connection->filters, n);
3214 if (data->ref_count == 0)
3219 CONNECTION_UNLOCK (connection);
3221 /* do free without holding lock */
3222 if (to_destroy != NULL)
3224 if (to_destroy->user_data_free_func != NULL)
3225 to_destroy->user_data_free_func (to_destroy->user_data);
3226 g_main_context_unref (to_destroy->context);
3227 g_free (to_destroy);
3231 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3235 /* ---------------------------------------------------------------------------------------------------- */
3241 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3242 gchar *interface_name;
3246 GDBusSignalFlags flags;
3247 GArray *subscribers;
3252 GDBusSignalCallback callback;
3254 GDestroyNotify user_data_free_func;
3256 GMainContext *context;
3260 signal_data_free (SignalData *signal_data)
3262 g_free (signal_data->rule);
3263 g_free (signal_data->sender);
3264 g_free (signal_data->sender_unique_name);
3265 g_free (signal_data->interface_name);
3266 g_free (signal_data->member);
3267 g_free (signal_data->object_path);
3268 g_free (signal_data->arg0);
3269 g_array_free (signal_data->subscribers, TRUE);
3270 g_free (signal_data);
3274 args_to_rule (const gchar *sender,
3275 const gchar *interface_name,
3276 const gchar *member,
3277 const gchar *object_path,
3279 GDBusSignalFlags flags)
3283 rule = g_string_new ("type='signal'");
3284 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3285 g_string_prepend_c (rule, '-');
3287 g_string_append_printf (rule, ",sender='%s'", sender);
3288 if (interface_name != NULL)
3289 g_string_append_printf (rule, ",interface='%s'", interface_name);
3291 g_string_append_printf (rule, ",member='%s'", member);
3292 if (object_path != NULL)
3293 g_string_append_printf (rule, ",path='%s'", object_path);
3297 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3298 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3299 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3300 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3302 g_string_append_printf (rule, ",arg0='%s'", arg0);
3305 return g_string_free (rule, FALSE);
3308 static volatile guint _global_subscriber_id = 1;
3309 static volatile guint _global_registration_id = 1;
3310 static volatile guint _global_subtree_registration_id = 1;
3312 /* ---------------------------------------------------------------------------------------------------- */
3314 /* Called in a user thread, lock is held */
3316 add_match_rule (GDBusConnection *connection,
3317 const gchar *match_rule)
3320 GDBusMessage *message;
3322 if (match_rule[0] == '-')
3325 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3326 "/org/freedesktop/DBus", /* path */
3327 "org.freedesktop.DBus", /* interface */
3329 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3331 if (!g_dbus_connection_send_message_unlocked (connection,
3333 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3337 g_critical ("Error while sending AddMatch() message: %s", error->message);
3338 g_error_free (error);
3340 g_object_unref (message);
3343 /* ---------------------------------------------------------------------------------------------------- */
3345 /* Called in a user thread, lock is held */
3347 remove_match_rule (GDBusConnection *connection,
3348 const gchar *match_rule)
3351 GDBusMessage *message;
3353 if (match_rule[0] == '-')
3356 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3357 "/org/freedesktop/DBus", /* path */
3358 "org.freedesktop.DBus", /* interface */
3360 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3363 if (!g_dbus_connection_send_message_unlocked (connection,
3365 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3369 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3370 * critical; but we're holding the lock, and our caller checked whether
3371 * we were already closed, so we can't get that error.
3373 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3374 g_error_free (error);
3376 g_object_unref (message);
3379 /* ---------------------------------------------------------------------------------------------------- */
3382 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3384 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3385 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3386 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3387 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3388 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3391 /* ---------------------------------------------------------------------------------------------------- */
3394 * g_dbus_connection_signal_subscribe:
3395 * @connection: a #GDBusConnection
3396 * @sender: (nullable): sender name to match on (unique or well-known name)
3397 * or %NULL to listen from all senders
3398 * @interface_name: (nullable): D-Bus interface name to match on or %NULL to
3399 * match on all interfaces
3400 * @member: (nullable): D-Bus signal name to match on or %NULL to match on
3402 * @object_path: (nullable): object path to match on or %NULL to match on
3404 * @arg0: (nullable): contents of first string argument to match on or %NULL
3405 * to match on all kinds of arguments
3406 * @flags: #GDBusSignalFlags describing how arg0 is used in subscribing to the
3408 * @callback: callback to invoke when there is a signal matching the requested data
3409 * @user_data: user data to pass to @callback
3410 * @user_data_free_func: (nullable): function to free @user_data with when
3411 * subscription is removed or %NULL
3413 * Subscribes to signals on @connection and invokes @callback with a whenever
3414 * the signal is received. Note that @callback will be invoked in the
3415 * [thread-default main context][g-main-context-push-thread-default]
3416 * of the thread you are calling this method from.
3418 * If @connection is not a message bus connection, @sender must be
3421 * If @sender is a well-known name note that @callback is invoked with
3422 * the unique name for the owner of @sender, not the well-known name
3423 * as one would expect. This is because the message bus rewrites the
3424 * name. As such, to avoid certain race conditions, users should be
3425 * tracking the name owner of the well-known name and use that when
3426 * processing the received signal.
3428 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3429 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3430 * interpreted as part of a namespace or path. The first argument
3431 * of a signal is matched against that part as specified by D-Bus.
3433 * If @user_data_free_func is non-%NULL, it will be called (in the
3434 * thread-default main context of the thread you are calling this
3435 * method from) at some point after @user_data is no longer
3436 * needed. (It is not guaranteed to be called synchronously when the
3437 * signal is unsubscribed from, and may be called after @connection
3438 * has been destroyed.)
3440 * The returned subscription identifier is an opaque value which is guaranteed
3443 * This function can never fail.
3445 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3450 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3451 const gchar *sender,
3452 const gchar *interface_name,
3453 const gchar *member,
3454 const gchar *object_path,
3456 GDBusSignalFlags flags,
3457 GDBusSignalCallback callback,
3459 GDestroyNotify user_data_free_func)
3462 SignalData *signal_data;
3463 SignalSubscriber subscriber;
3464 GPtrArray *signal_data_array;
3465 const gchar *sender_unique_name;
3467 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3468 * an OOM condition. We might want to change that but that would involve making
3469 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3470 * handle that. And there's really no sensible way of handling this short of retrying
3471 * to add the match rule... and then there's the little thing that, hey, maybe there's
3472 * a reason the bus in an OOM condition.
3474 * Doable, but not really sure it's worth it...
3477 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3478 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3479 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3480 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3481 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3482 g_return_val_if_fail (callback != NULL, 0);
3483 g_return_val_if_fail (check_initialized (connection), 0);
3484 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3485 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3487 CONNECTION_LOCK (connection);
3489 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3490 * with a '-' character to prefix the rule (which will otherwise be
3493 * This allows us to hash the rule and do our lifecycle tracking in
3494 * the usual way, but the '-' prevents the match rule from ever
3495 * actually being send to the bus (either for add or remove).
3497 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3499 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3500 sender_unique_name = sender;
3502 sender_unique_name = "";
3504 subscriber.callback = callback;
3505 subscriber.user_data = user_data;
3506 subscriber.user_data_free_func = user_data_free_func;
3507 subscriber.id = g_atomic_int_add (&_global_subscriber_id, 1); /* TODO: overflow etc. */
3508 subscriber.context = g_main_context_ref_thread_default ();
3510 /* see if we've already have this rule */
3511 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3512 if (signal_data != NULL)
3514 g_array_append_val (signal_data->subscribers, subscriber);
3519 signal_data = g_new0 (SignalData, 1);
3520 signal_data->rule = rule;
3521 signal_data->sender = g_strdup (sender);
3522 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3523 signal_data->interface_name = g_strdup (interface_name);
3524 signal_data->member = g_strdup (member);
3525 signal_data->object_path = g_strdup (object_path);
3526 signal_data->arg0 = g_strdup (arg0);
3527 signal_data->flags = flags;
3528 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3529 g_array_append_val (signal_data->subscribers, subscriber);
3531 g_hash_table_insert (connection->map_rule_to_signal_data,
3535 /* Add the match rule to the bus...
3537 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3538 * always send such messages to us.
3540 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3542 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3543 add_match_rule (connection, signal_data->rule);
3546 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3547 signal_data->sender_unique_name);
3548 if (signal_data_array == NULL)
3550 signal_data_array = g_ptr_array_new ();
3551 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3552 g_strdup (signal_data->sender_unique_name),
3555 g_ptr_array_add (signal_data_array, signal_data);
3558 g_hash_table_insert (connection->map_id_to_signal_data,
3559 GUINT_TO_POINTER (subscriber.id),
3562 CONNECTION_UNLOCK (connection);
3564 return subscriber.id;
3567 /* ---------------------------------------------------------------------------------------------------- */
3569 /* called in any thread */
3570 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3572 unsubscribe_id_internal (GDBusConnection *connection,
3573 guint subscription_id,
3574 GArray *out_removed_subscribers)
3576 SignalData *signal_data;
3577 GPtrArray *signal_data_array;
3580 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3581 GUINT_TO_POINTER (subscription_id));
3582 if (signal_data == NULL)
3584 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3588 for (n = 0; n < signal_data->subscribers->len; n++)
3590 SignalSubscriber *subscriber;
3592 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3593 if (subscriber->id != subscription_id)
3596 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3597 GUINT_TO_POINTER (subscription_id)));
3598 g_array_append_val (out_removed_subscribers, *subscriber);
3599 g_array_remove_index (signal_data->subscribers, n);
3601 if (signal_data->subscribers->len == 0)
3603 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3605 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3606 signal_data->sender_unique_name);
3607 g_warn_if_fail (signal_data_array != NULL);
3608 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3610 if (signal_data_array->len == 0)
3612 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3613 signal_data->sender_unique_name));
3616 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3617 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3618 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3619 !g_dbus_connection_is_closed (connection) &&
3620 !connection->finalizing)
3622 /* The check for g_dbus_connection_is_closed() means that
3623 * sending the RemoveMatch message can't fail with
3624 * G_IO_ERROR_CLOSED, because we're holding the lock,
3625 * so on_worker_closed() can't happen between the check we just
3626 * did, and releasing the lock later.
3628 remove_match_rule (connection, signal_data->rule);
3631 signal_data_free (signal_data);
3637 g_assert_not_reached ();
3644 * g_dbus_connection_signal_unsubscribe:
3645 * @connection: a #GDBusConnection
3646 * @subscription_id: a subscription id obtained from
3647 * g_dbus_connection_signal_subscribe()
3649 * Unsubscribes from signals.
3654 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3655 guint subscription_id)
3657 GArray *subscribers;
3660 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3661 g_return_if_fail (check_initialized (connection));
3663 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3665 CONNECTION_LOCK (connection);
3666 unsubscribe_id_internal (connection,
3669 CONNECTION_UNLOCK (connection);
3672 g_assert (subscribers->len == 0 || subscribers->len == 1);
3674 /* call GDestroyNotify without lock held */
3675 for (n = 0; n < subscribers->len; n++)
3677 SignalSubscriber *subscriber;
3678 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3679 call_destroy_notify (subscriber->context,
3680 subscriber->user_data_free_func,
3681 subscriber->user_data);
3682 g_main_context_unref (subscriber->context);
3685 g_array_free (subscribers, TRUE);
3688 /* ---------------------------------------------------------------------------------------------------- */
3692 guint subscription_id;
3693 GDBusSignalCallback callback;
3695 GDBusMessage *message;
3696 GDBusConnection *connection;
3697 const gchar *sender;
3699 const gchar *interface;
3700 const gchar *member;
3703 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3707 emit_signal_instance_in_idle_cb (gpointer data)
3709 SignalInstance *signal_instance = data;
3710 GVariant *parameters;
3711 gboolean has_subscription;
3713 parameters = g_dbus_message_get_body (signal_instance->message);
3714 if (parameters == NULL)
3716 parameters = g_variant_new ("()");
3717 g_variant_ref_sink (parameters);
3721 g_variant_ref_sink (parameters);
3725 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3726 signal_instance->subscription_id,
3727 signal_instance->sender,
3728 signal_instance->path,
3729 signal_instance->interface,
3730 signal_instance->member,
3731 g_variant_print (parameters, TRUE));
3734 /* Careful here, don't do the callback if we no longer has the subscription */
3735 CONNECTION_LOCK (signal_instance->connection);
3736 has_subscription = FALSE;
3737 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3738 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3739 has_subscription = TRUE;
3740 CONNECTION_UNLOCK (signal_instance->connection);
3742 if (has_subscription)
3743 signal_instance->callback (signal_instance->connection,
3744 signal_instance->sender,
3745 signal_instance->path,
3746 signal_instance->interface,
3747 signal_instance->member,
3749 signal_instance->user_data);
3751 g_variant_unref (parameters);
3757 signal_instance_free (SignalInstance *signal_instance)
3759 g_object_unref (signal_instance->message);
3760 g_object_unref (signal_instance->connection);
3761 g_free (signal_instance);
3765 namespace_rule_matches (const gchar *namespace,
3771 len_namespace = strlen (namespace);
3772 len_name = strlen (name);
3774 if (len_name < len_namespace)
3777 if (memcmp (namespace, name, len_namespace) != 0)
3780 return len_namespace == len_name || name[len_namespace] == '.';
3784 path_rule_matches (const gchar *path_a,
3785 const gchar *path_b)
3789 len_a = strlen (path_a);
3790 len_b = strlen (path_b);
3792 if (len_a < len_b && (len_a == 0 || path_a[len_a - 1] != '/'))
3795 if (len_b < len_a && (len_b == 0 || path_b[len_b - 1] != '/'))
3798 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3801 /* called in GDBusWorker thread WITH lock held */
3803 schedule_callbacks (GDBusConnection *connection,
3804 GPtrArray *signal_data_array,
3805 GDBusMessage *message,
3806 const gchar *sender)
3809 const gchar *interface;
3810 const gchar *member;
3819 interface = g_dbus_message_get_interface (message);
3820 member = g_dbus_message_get_member (message);
3821 path = g_dbus_message_get_path (message);
3822 arg0 = g_dbus_message_get_arg0 (message);
3825 g_print ("In schedule_callbacks:\n"
3827 " interface = '%s'\n"
3838 /* TODO: if this is slow, then we can change signal_data_array into
3839 * map_object_path_to_signal_data_array or something.
3841 for (n = 0; n < signal_data_array->len; n++)
3843 SignalData *signal_data = signal_data_array->pdata[n];
3845 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3848 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3851 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3854 if (signal_data->arg0 != NULL)
3859 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3861 if (!namespace_rule_matches (signal_data->arg0, arg0))
3864 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3866 if (!path_rule_matches (signal_data->arg0, arg0))
3869 else if (!g_str_equal (signal_data->arg0, arg0))
3873 for (m = 0; m < signal_data->subscribers->len; m++)
3875 SignalSubscriber *subscriber;
3876 GSource *idle_source;
3877 SignalInstance *signal_instance;
3879 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3881 signal_instance = g_new0 (SignalInstance, 1);
3882 signal_instance->subscription_id = subscriber->id;
3883 signal_instance->callback = subscriber->callback;
3884 signal_instance->user_data = subscriber->user_data;
3885 signal_instance->message = g_object_ref (message);
3886 signal_instance->connection = g_object_ref (connection);
3887 signal_instance->sender = sender;
3888 signal_instance->path = path;
3889 signal_instance->interface = interface;
3890 signal_instance->member = member;
3892 idle_source = g_idle_source_new ();
3893 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3894 g_source_set_callback (idle_source,
3895 emit_signal_instance_in_idle_cb,
3897 (GDestroyNotify) signal_instance_free);
3898 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3899 g_source_attach (idle_source, subscriber->context);
3900 g_source_unref (idle_source);
3905 /* called in GDBusWorker thread with lock held */
3907 distribute_signals (GDBusConnection *connection,
3908 GDBusMessage *message)
3910 GPtrArray *signal_data_array;
3911 const gchar *sender;
3913 sender = g_dbus_message_get_sender (message);
3915 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3917 _g_dbus_debug_print_lock ();
3918 g_print ("========================================================================\n"
3919 "GDBus-debug:Signal:\n"
3920 " <<<< RECEIVED SIGNAL %s.%s\n"
3922 " sent by name %s\n",
3923 g_dbus_message_get_interface (message),
3924 g_dbus_message_get_member (message),
3925 g_dbus_message_get_path (message),
3926 sender != NULL ? sender : "(none)");
3927 _g_dbus_debug_print_unlock ();
3930 /* collect subscribers that match on sender */
3933 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3934 if (signal_data_array != NULL)
3935 schedule_callbacks (connection, signal_data_array, message, sender);
3938 /* collect subscribers not matching on sender */
3939 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3940 if (signal_data_array != NULL)
3941 schedule_callbacks (connection, signal_data_array, message, sender);
3944 /* ---------------------------------------------------------------------------------------------------- */
3946 /* only called from finalize(), removes all subscriptions */
3948 purge_all_signal_subscriptions (GDBusConnection *connection)
3950 GHashTableIter iter;
3953 GArray *subscribers;
3956 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3957 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3958 while (g_hash_table_iter_next (&iter, &key, NULL))
3960 guint subscription_id = GPOINTER_TO_UINT (key);
3961 g_array_append_val (ids, subscription_id);
3964 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3965 for (n = 0; n < ids->len; n++)
3967 guint subscription_id = g_array_index (ids, guint, n);
3968 unsubscribe_id_internal (connection,
3972 g_array_free (ids, TRUE);
3974 /* call GDestroyNotify without lock held */
3975 for (n = 0; n < subscribers->len; n++)
3977 SignalSubscriber *subscriber;
3978 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3979 call_destroy_notify (subscriber->context,
3980 subscriber->user_data_free_func,
3981 subscriber->user_data);
3982 g_main_context_unref (subscriber->context);
3985 g_array_free (subscribers, TRUE);
3988 /* ---------------------------------------------------------------------------------------------------- */
3990 static GDBusInterfaceVTable *
3991 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3993 /* Don't waste memory by copying padding - remember to update this
3994 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3996 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4000 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4005 /* ---------------------------------------------------------------------------------------------------- */
4007 static GDBusSubtreeVTable *
4008 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4010 /* Don't waste memory by copying padding - remember to update this
4011 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4013 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4017 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4022 /* ---------------------------------------------------------------------------------------------------- */
4024 struct ExportedObject
4027 GDBusConnection *connection;
4029 /* maps gchar* -> ExportedInterface* */
4030 GHashTable *map_if_name_to_ei;
4033 /* only called with lock held */
4035 exported_object_free (ExportedObject *eo)
4037 g_free (eo->object_path);
4038 g_hash_table_unref (eo->map_if_name_to_ei);
4047 gchar *interface_name;
4048 GDBusInterfaceVTable *vtable;
4049 GDBusInterfaceInfo *interface_info;
4051 GMainContext *context;
4053 GDestroyNotify user_data_free_func;
4054 } ExportedInterface;
4056 /* called with lock held */
4058 exported_interface_free (ExportedInterface *ei)
4060 g_dbus_interface_info_cache_release (ei->interface_info);
4061 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4063 call_destroy_notify (ei->context,
4064 ei->user_data_free_func,
4067 g_main_context_unref (ei->context);
4069 g_free (ei->interface_name);
4070 _g_dbus_interface_vtable_free (ei->vtable);
4074 /* ---------------------------------------------------------------------------------------------------- */
4076 /* Convenience function to check if @registration_id (if not zero) or
4077 * @subtree_registration_id (if not zero) has been unregistered. If
4078 * so, returns %TRUE.
4080 * May be called by any thread. Caller must *not* hold lock.
4083 has_object_been_unregistered (GDBusConnection *connection,
4084 guint registration_id,
4085 guint subtree_registration_id)
4089 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4093 CONNECTION_LOCK (connection);
4094 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4095 GUINT_TO_POINTER (registration_id)) == NULL)
4099 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4100 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4104 CONNECTION_UNLOCK (connection);
4109 /* ---------------------------------------------------------------------------------------------------- */
4113 GDBusConnection *connection;
4114 GDBusMessage *message;
4116 const gchar *property_name;
4117 const GDBusInterfaceVTable *vtable;
4118 GDBusInterfaceInfo *interface_info;
4119 const GDBusPropertyInfo *property_info;
4120 guint registration_id;
4121 guint subtree_registration_id;
4125 property_data_free (PropertyData *data)
4127 g_object_unref (data->connection);
4128 g_object_unref (data->message);
4132 /* called in thread where object was registered - no locks held */
4134 invoke_get_property_in_idle_cb (gpointer _data)
4136 PropertyData *data = _data;
4139 GDBusMessage *reply;
4141 if (has_object_been_unregistered (data->connection,
4142 data->registration_id,
4143 data->subtree_registration_id))
4145 reply = g_dbus_message_new_method_error (data->message,
4146 "org.freedesktop.DBus.Error.UnknownMethod",
4147 _("No such interface āorg.freedesktop.DBus.Propertiesā on object at path %s"),
4148 g_dbus_message_get_path (data->message));
4149 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4150 g_object_unref (reply);
4155 value = data->vtable->get_property (data->connection,
4156 g_dbus_message_get_sender (data->message),
4157 g_dbus_message_get_path (data->message),
4158 data->interface_info->name,
4159 data->property_name,
4166 g_assert_no_error (error);
4168 g_variant_take_ref (value);
4169 reply = g_dbus_message_new_method_reply (data->message);
4170 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4171 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4172 g_variant_unref (value);
4173 g_object_unref (reply);
4177 gchar *dbus_error_name;
4178 g_assert (error != NULL);
4179 dbus_error_name = g_dbus_error_encode_gerror (error);
4180 reply = g_dbus_message_new_method_error_literal (data->message,
4183 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4184 g_free (dbus_error_name);
4185 g_error_free (error);
4186 g_object_unref (reply);
4193 /* called in thread where object was registered - no locks held */
4195 invoke_set_property_in_idle_cb (gpointer _data)
4197 PropertyData *data = _data;
4199 GDBusMessage *reply;
4205 g_variant_get (g_dbus_message_get_body (data->message),
4211 if (!data->vtable->set_property (data->connection,
4212 g_dbus_message_get_sender (data->message),
4213 g_dbus_message_get_path (data->message),
4214 data->interface_info->name,
4215 data->property_name,
4220 gchar *dbus_error_name;
4221 g_assert (error != NULL);
4222 dbus_error_name = g_dbus_error_encode_gerror (error);
4223 reply = g_dbus_message_new_method_error_literal (data->message,
4226 g_free (dbus_error_name);
4227 g_error_free (error);
4231 reply = g_dbus_message_new_method_reply (data->message);
4234 g_assert (reply != NULL);
4235 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4236 g_object_unref (reply);
4237 g_variant_unref (value);
4242 /* called in any thread with connection's lock held */
4244 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4245 GDBusMessage *message,
4246 guint registration_id,
4247 guint subtree_registration_id,
4249 GDBusInterfaceInfo *interface_info,
4250 const GDBusInterfaceVTable *vtable,
4251 GMainContext *main_context,
4255 const char *interface_name;
4256 const char *property_name;
4257 const GDBusPropertyInfo *property_info;
4258 GSource *idle_source;
4259 PropertyData *property_data;
4260 GDBusMessage *reply;
4265 g_variant_get (g_dbus_message_get_body (message),
4270 g_variant_get (g_dbus_message_get_body (message),
4279 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4281 property_info = NULL;
4283 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4284 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4285 if (property_info == NULL)
4287 reply = g_dbus_message_new_method_error (message,
4288 "org.freedesktop.DBus.Error.InvalidArgs",
4289 _("No such property ā%sā"),
4291 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4292 g_object_unref (reply);
4297 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4299 reply = g_dbus_message_new_method_error (message,
4300 "org.freedesktop.DBus.Error.InvalidArgs",
4301 _("Property ā%sā is not readable"),
4303 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4304 g_object_unref (reply);
4308 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4310 reply = g_dbus_message_new_method_error (message,
4311 "org.freedesktop.DBus.Error.InvalidArgs",
4312 _("Property ā%sā is not writable"),
4314 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4315 g_object_unref (reply);
4324 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4325 * of the given value is wrong
4327 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4328 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4330 reply = g_dbus_message_new_method_error (message,
4331 "org.freedesktop.DBus.Error.InvalidArgs",
4332 _("Error setting property ā%sā: Expected type ā%sā but got ā%sā"),
4333 property_name, property_info->signature,
4334 g_variant_get_type_string (value));
4335 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4336 g_variant_unref (value);
4337 g_object_unref (reply);
4342 g_variant_unref (value);
4345 /* If the vtable pointer for get_property() resp. set_property() is
4346 * NULL then dispatch the call via the method_call() handler.
4350 if (vtable->get_property == NULL)
4352 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4353 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4354 vtable, main_context, user_data);
4361 if (vtable->set_property == NULL)
4363 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4364 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4365 vtable, main_context, user_data);
4371 /* ok, got the property info - call user code in an idle handler */
4372 property_data = g_new0 (PropertyData, 1);
4373 property_data->connection = g_object_ref (connection);
4374 property_data->message = g_object_ref (message);
4375 property_data->user_data = user_data;
4376 property_data->property_name = property_name;
4377 property_data->vtable = vtable;
4378 property_data->interface_info = interface_info;
4379 property_data->property_info = property_info;
4380 property_data->registration_id = registration_id;
4381 property_data->subtree_registration_id = subtree_registration_id;
4383 idle_source = g_idle_source_new ();
4384 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4385 g_source_set_callback (idle_source,
4386 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4388 (GDestroyNotify) property_data_free);
4390 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4392 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4393 g_source_attach (idle_source, main_context);
4394 g_source_unref (idle_source);
4402 /* called in GDBusWorker thread with connection's lock held */
4404 handle_getset_property (GDBusConnection *connection,
4406 GDBusMessage *message,
4409 ExportedInterface *ei;
4411 const char *interface_name;
4412 const char *property_name;
4417 g_variant_get (g_dbus_message_get_body (message),
4422 g_variant_get (g_dbus_message_get_body (message),
4428 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4429 * no such interface registered
4431 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4434 GDBusMessage *reply;
4435 reply = g_dbus_message_new_method_error (message,
4436 "org.freedesktop.DBus.Error.InvalidArgs",
4437 _("No such interface ā%sā"),
4439 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4440 g_object_unref (reply);
4445 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4458 /* ---------------------------------------------------------------------------------------------------- */
4462 GDBusConnection *connection;
4463 GDBusMessage *message;
4465 const GDBusInterfaceVTable *vtable;
4466 GDBusInterfaceInfo *interface_info;
4467 guint registration_id;
4468 guint subtree_registration_id;
4469 } PropertyGetAllData;
4472 property_get_all_data_free (PropertyData *data)
4474 g_object_unref (data->connection);
4475 g_object_unref (data->message);
4479 /* called in thread where object was registered - no locks held */
4481 invoke_get_all_properties_in_idle_cb (gpointer _data)
4483 PropertyGetAllData *data = _data;
4484 GVariantBuilder builder;
4485 GDBusMessage *reply;
4488 if (has_object_been_unregistered (data->connection,
4489 data->registration_id,
4490 data->subtree_registration_id))
4492 reply = g_dbus_message_new_method_error (data->message,
4493 "org.freedesktop.DBus.Error.UnknownMethod",
4494 _("No such interface āorg.freedesktop.DBus.Propertiesā on object at path %s"),
4495 g_dbus_message_get_path (data->message));
4496 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4497 g_object_unref (reply);
4501 /* TODO: Right now we never fail this call - we just omit values if
4502 * a get_property() call is failing.
4504 * We could fail the whole call if just a single get_property() call
4505 * returns an error. We need clarification in the D-Bus spec about this.
4507 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4508 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4509 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4511 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4514 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4517 value = data->vtable->get_property (data->connection,
4518 g_dbus_message_get_sender (data->message),
4519 g_dbus_message_get_path (data->message),
4520 data->interface_info->name,
4521 property_info->name,
4528 g_variant_take_ref (value);
4529 g_variant_builder_add (&builder,
4531 property_info->name,
4533 g_variant_unref (value);
4535 g_variant_builder_close (&builder);
4537 reply = g_dbus_message_new_method_reply (data->message);
4538 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4539 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4540 g_object_unref (reply);
4547 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4551 if (!interface_info->properties)
4554 for (i = 0; interface_info->properties[i]; i++)
4555 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4561 /* called in any thread with connection's lock held */
4563 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4564 GDBusMessage *message,
4565 guint registration_id,
4566 guint subtree_registration_id,
4567 GDBusInterfaceInfo *interface_info,
4568 const GDBusInterfaceVTable *vtable,
4569 GMainContext *main_context,
4573 GSource *idle_source;
4574 PropertyGetAllData *property_get_all_data;
4581 /* If the vtable pointer for get_property() is NULL but we have a
4582 * non-zero number of readable properties, then dispatch the call via
4583 * the method_call() handler.
4585 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4587 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4588 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4589 vtable, main_context, user_data);
4594 /* ok, got the property info - call user in an idle handler */
4595 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4596 property_get_all_data->connection = g_object_ref (connection);
4597 property_get_all_data->message = g_object_ref (message);
4598 property_get_all_data->user_data = user_data;
4599 property_get_all_data->vtable = vtable;
4600 property_get_all_data->interface_info = interface_info;
4601 property_get_all_data->registration_id = registration_id;
4602 property_get_all_data->subtree_registration_id = subtree_registration_id;
4604 idle_source = g_idle_source_new ();
4605 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4606 g_source_set_callback (idle_source,
4607 invoke_get_all_properties_in_idle_cb,
4608 property_get_all_data,
4609 (GDestroyNotify) property_get_all_data_free);
4610 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4611 g_source_attach (idle_source, main_context);
4612 g_source_unref (idle_source);
4620 /* called in GDBusWorker thread with connection's lock held */
4622 handle_get_all_properties (GDBusConnection *connection,
4624 GDBusMessage *message)
4626 ExportedInterface *ei;
4628 const char *interface_name;
4632 g_variant_get (g_dbus_message_get_body (message),
4636 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4637 * no such interface registered
4639 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4642 GDBusMessage *reply;
4643 reply = g_dbus_message_new_method_error (message,
4644 "org.freedesktop.DBus.Error.InvalidArgs",
4645 _("No such interface ā%sā"),
4647 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4648 g_object_unref (reply);
4653 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4665 /* ---------------------------------------------------------------------------------------------------- */
4667 static const gchar introspect_header[] =
4668 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4669 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4670 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4673 static const gchar introspect_tail[] =
4676 static const gchar introspect_properties_interface[] =
4677 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4678 " <method name=\"Get\">\n"
4679 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4680 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4681 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4683 " <method name=\"GetAll\">\n"
4684 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4685 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4687 " <method name=\"Set\">\n"
4688 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4689 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4690 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4692 " <signal name=\"PropertiesChanged\">\n"
4693 " <arg type=\"s\" name=\"interface_name\"/>\n"
4694 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4695 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4699 static const gchar introspect_introspectable_interface[] =
4700 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4701 " <method name=\"Introspect\">\n"
4702 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4705 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4706 " <method name=\"Ping\"/>\n"
4707 " <method name=\"GetMachineId\">\n"
4708 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4713 introspect_append_header (GString *s)
4715 g_string_append (s, introspect_header);
4719 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4721 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4727 begin = object_path + path_len;
4728 end = strchr (begin, '/');
4730 s = g_strndup (begin, end - begin);
4732 s = g_strdup (begin);
4734 if (!g_hash_table_contains (set, s))
4735 g_hash_table_add (set, s);
4741 /* TODO: we want a nicer public interface for this */
4742 /* called in any thread with connection's lock held */
4744 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4749 GHashTableIter hash_iter;
4750 const gchar *object_path;
4756 CONNECTION_ENSURE_LOCK (connection);
4758 path_len = strlen (path);
4762 set = g_hash_table_new (g_str_hash, g_str_equal);
4764 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4765 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4766 maybe_add_path (path, path_len, object_path, set);
4768 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4769 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4770 maybe_add_path (path, path_len, object_path, set);
4772 p = g_ptr_array_new ();
4773 keys = g_hash_table_get_keys (set);
4774 for (l = keys; l != NULL; l = l->next)
4775 g_ptr_array_add (p, l->data);
4776 g_hash_table_unref (set);
4779 g_ptr_array_add (p, NULL);
4780 ret = (gchar **) g_ptr_array_free (p, FALSE);
4784 /* called in any thread with connection's lock not held */
4786 g_dbus_connection_list_registered (GDBusConnection *connection,
4790 CONNECTION_LOCK (connection);
4791 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4792 CONNECTION_UNLOCK (connection);
4796 /* called in GDBusWorker thread with connection's lock held */
4798 handle_introspect (GDBusConnection *connection,
4800 GDBusMessage *message)
4804 GDBusMessage *reply;
4805 GHashTableIter hash_iter;
4806 ExportedInterface *ei;
4809 /* first the header with the standard interfaces */
4810 s = g_string_sized_new (sizeof (introspect_header) +
4811 sizeof (introspect_properties_interface) +
4812 sizeof (introspect_introspectable_interface) +
4813 sizeof (introspect_tail));
4814 introspect_append_header (s);
4815 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4816 "org.freedesktop.DBus.Properties"))
4817 g_string_append (s, introspect_properties_interface);
4819 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4820 "org.freedesktop.DBus.Introspectable"))
4821 g_string_append (s, introspect_introspectable_interface);
4823 /* then include the registered interfaces */
4824 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4825 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4826 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4828 /* finally include nodes registered below us */
4829 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4830 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4831 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4832 g_strfreev (registered);
4833 g_string_append (s, introspect_tail);
4835 reply = g_dbus_message_new_method_reply (message);
4836 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4837 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4838 g_object_unref (reply);
4839 g_string_free (s, TRUE);
4844 /* called in thread where object was registered - no locks held */
4846 call_in_idle_cb (gpointer user_data)
4848 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4849 GDBusInterfaceVTable *vtable;
4850 guint registration_id;
4851 guint subtree_registration_id;
4853 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4854 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4856 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4858 subtree_registration_id))
4860 GDBusMessage *reply;
4861 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4862 "org.freedesktop.DBus.Error.UnknownMethod",
4863 _("No such interface ā%sā on object at path %s"),
4864 g_dbus_method_invocation_get_interface_name (invocation),
4865 g_dbus_method_invocation_get_object_path (invocation));
4866 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4867 g_object_unref (reply);
4871 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4872 g_assert (vtable != NULL && vtable->method_call != NULL);
4874 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4875 g_dbus_method_invocation_get_sender (invocation),
4876 g_dbus_method_invocation_get_object_path (invocation),
4877 g_dbus_method_invocation_get_interface_name (invocation),
4878 g_dbus_method_invocation_get_method_name (invocation),
4879 g_dbus_method_invocation_get_parameters (invocation),
4880 g_object_ref (invocation),
4881 g_dbus_method_invocation_get_user_data (invocation));
4887 /* called in GDBusWorker thread with connection's lock held */
4889 schedule_method_call (GDBusConnection *connection,
4890 GDBusMessage *message,
4891 guint registration_id,
4892 guint subtree_registration_id,
4893 const GDBusInterfaceInfo *interface_info,
4894 const GDBusMethodInfo *method_info,
4895 const GDBusPropertyInfo *property_info,
4896 GVariant *parameters,
4897 const GDBusInterfaceVTable *vtable,
4898 GMainContext *main_context,
4901 GDBusMethodInvocation *invocation;
4902 GSource *idle_source;
4904 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4905 g_dbus_message_get_path (message),
4906 g_dbus_message_get_interface (message),
4907 g_dbus_message_get_member (message),
4915 /* TODO: would be nicer with a real MethodData like we already
4916 * have PropertyData and PropertyGetAllData... */
4917 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4918 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4919 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4921 idle_source = g_idle_source_new ();
4922 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4923 g_source_set_callback (idle_source,
4927 g_source_set_name (idle_source, "[gio, " __FILE__ "] call_in_idle_cb");
4928 g_source_attach (idle_source, main_context);
4929 g_source_unref (idle_source);
4932 /* called in GDBusWorker thread with connection's lock held */
4934 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4935 GDBusMessage *message,
4936 guint registration_id,
4937 guint subtree_registration_id,
4938 GDBusInterfaceInfo *interface_info,
4939 const GDBusInterfaceVTable *vtable,
4940 GMainContext *main_context,
4943 GDBusMethodInfo *method_info;
4944 GDBusMessage *reply;
4945 GVariant *parameters;
4947 GVariantType *in_type;
4951 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4952 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4954 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4955 * error to the caller
4957 if (method_info == NULL)
4959 reply = g_dbus_message_new_method_error (message,
4960 "org.freedesktop.DBus.Error.UnknownMethod",
4961 _("No such method ā%sā"),
4962 g_dbus_message_get_member (message));
4963 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4964 g_object_unref (reply);
4969 parameters = g_dbus_message_get_body (message);
4970 if (parameters == NULL)
4972 parameters = g_variant_new ("()");
4973 g_variant_ref_sink (parameters);
4977 g_variant_ref (parameters);
4980 /* Check that the incoming args are of the right type - if they are not, return
4981 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4983 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4984 if (!g_variant_is_of_type (parameters, in_type))
4988 type_string = g_variant_type_dup_string (in_type);
4990 reply = g_dbus_message_new_method_error (message,
4991 "org.freedesktop.DBus.Error.InvalidArgs",
4992 _("Type of message, ā%sā, does not match expected type ā%sā"),
4993 g_variant_get_type_string (parameters),
4995 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4996 g_variant_type_free (in_type);
4997 g_variant_unref (parameters);
4998 g_object_unref (reply);
4999 g_free (type_string);
5003 g_variant_type_free (in_type);
5005 /* schedule the call in idle */
5006 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5007 interface_info, method_info, NULL, parameters,
5008 vtable, main_context, user_data);
5009 g_variant_unref (parameters);
5016 /* ---------------------------------------------------------------------------------------------------- */
5018 /* called in GDBusWorker thread with connection's lock held */
5020 obj_message_func (GDBusConnection *connection,
5022 GDBusMessage *message)
5024 const gchar *interface_name;
5025 const gchar *member;
5026 const gchar *signature;
5031 interface_name = g_dbus_message_get_interface (message);
5032 member = g_dbus_message_get_member (message);
5033 signature = g_dbus_message_get_signature (message);
5035 /* see if we have an interface for handling this call */
5036 if (interface_name != NULL)
5038 ExportedInterface *ei;
5039 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5042 /* we do - invoke the handler in idle in the right thread */
5044 /* handle no vtable or handler being present */
5045 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5048 handled = validate_and_maybe_schedule_method_call (connection,
5060 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5061 g_strcmp0 (member, "Introspect") == 0 &&
5062 g_strcmp0 (signature, "") == 0)
5064 handled = handle_introspect (connection, eo, message);
5067 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5068 g_strcmp0 (member, "Get") == 0 &&
5069 g_strcmp0 (signature, "ss") == 0)
5071 handled = handle_getset_property (connection, eo, message, TRUE);
5074 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5075 g_strcmp0 (member, "Set") == 0 &&
5076 g_strcmp0 (signature, "ssv") == 0)
5078 handled = handle_getset_property (connection, eo, message, FALSE);
5081 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5082 g_strcmp0 (member, "GetAll") == 0 &&
5083 g_strcmp0 (signature, "s") == 0)
5085 handled = handle_get_all_properties (connection, eo, message);
5094 * g_dbus_connection_register_object:
5095 * @connection: a #GDBusConnection
5096 * @object_path: the object path to register at
5097 * @interface_info: introspection data for the interface
5098 * @vtable: (nullable): a #GDBusInterfaceVTable to call into or %NULL
5099 * @user_data: (nullable): data to pass to functions in @vtable
5100 * @user_data_free_func: function to call when the object path is unregistered
5101 * @error: return location for error or %NULL
5103 * Registers callbacks for exported objects at @object_path with the
5104 * D-Bus interface that is described in @interface_info.
5106 * Calls to functions in @vtable (and @user_data_free_func) will happen
5108 * [thread-default main context][g-main-context-push-thread-default]
5109 * of the thread you are calling this method from.
5111 * Note that all #GVariant values passed to functions in @vtable will match
5112 * the signature given in @interface_info - if a remote caller passes
5113 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5114 * is returned to the remote caller.
5116 * Additionally, if the remote caller attempts to invoke methods or
5117 * access properties not mentioned in @interface_info the
5118 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5119 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5120 * are returned to the caller.
5122 * It is considered a programming error if the
5123 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5124 * #GVariant of incorrect type.
5126 * If an existing callback is already registered at @object_path and
5127 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5129 * GDBus automatically implements the standard D-Bus interfaces
5130 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5131 * and org.freedesktop.Peer, so you don't have to implement those for the
5132 * objects you export. You can implement org.freedesktop.DBus.Properties
5133 * yourself, e.g. to handle getting and setting of properties asynchronously.
5135 * Note that the reference count on @interface_info will be
5136 * incremented by 1 (unless allocated statically, e.g. if the
5137 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5138 * as the object is exported. Also note that @vtable will be copied.
5140 * See this [server][gdbus-server] for an example of how to use this method.
5142 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5143 * that can be used with g_dbus_connection_unregister_object()
5148 g_dbus_connection_register_object (GDBusConnection *connection,
5149 const gchar *object_path,
5150 GDBusInterfaceInfo *interface_info,
5151 const GDBusInterfaceVTable *vtable,
5153 GDestroyNotify user_data_free_func,
5157 ExportedInterface *ei;
5160 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5161 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5162 g_return_val_if_fail (interface_info != NULL, 0);
5163 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5164 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5165 g_return_val_if_fail (check_initialized (connection), 0);
5169 CONNECTION_LOCK (connection);
5171 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5174 eo = g_new0 (ExportedObject, 1);
5175 eo->object_path = g_strdup (object_path);
5176 eo->connection = connection;
5177 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5180 (GDestroyNotify) exported_interface_free);
5181 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5184 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5190 _("An object is already exported for the interface %s at %s"),
5191 interface_info->name,
5196 ei = g_new0 (ExportedInterface, 1);
5197 ei->id = g_atomic_int_add (&_global_registration_id, 1); /* TODO: overflow etc. */
5199 ei->user_data = user_data;
5200 ei->user_data_free_func = user_data_free_func;
5201 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5202 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5203 g_dbus_interface_info_cache_build (ei->interface_info);
5204 ei->interface_name = g_strdup (interface_info->name);
5205 ei->context = g_main_context_ref_thread_default ();
5207 g_hash_table_insert (eo->map_if_name_to_ei,
5208 (gpointer) ei->interface_name,
5210 g_hash_table_insert (connection->map_id_to_ei,
5211 GUINT_TO_POINTER (ei->id),
5217 CONNECTION_UNLOCK (connection);
5223 * g_dbus_connection_unregister_object:
5224 * @connection: a #GDBusConnection
5225 * @registration_id: a registration id obtained from
5226 * g_dbus_connection_register_object()
5228 * Unregisters an object.
5230 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5235 g_dbus_connection_unregister_object (GDBusConnection *connection,
5236 guint registration_id)
5238 ExportedInterface *ei;
5242 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5243 g_return_val_if_fail (check_initialized (connection), FALSE);
5247 CONNECTION_LOCK (connection);
5249 ei = g_hash_table_lookup (connection->map_id_to_ei,
5250 GUINT_TO_POINTER (registration_id));
5256 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5257 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5258 /* unregister object path if we have no more exported interfaces */
5259 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5260 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5266 CONNECTION_UNLOCK (connection);
5272 GClosure *method_call_closure;
5273 GClosure *get_property_closure;
5274 GClosure *set_property_closure;
5275 } RegisterObjectData;
5277 static RegisterObjectData *
5278 register_object_data_new (GClosure *method_call_closure,
5279 GClosure *get_property_closure,
5280 GClosure *set_property_closure)
5282 RegisterObjectData *data;
5284 data = g_new0 (RegisterObjectData, 1);
5286 if (method_call_closure != NULL)
5288 data->method_call_closure = g_closure_ref (method_call_closure);
5289 g_closure_sink (method_call_closure);
5290 if (G_CLOSURE_NEEDS_MARSHAL (method_call_closure))
5291 g_closure_set_marshal (method_call_closure, g_cclosure_marshal_generic);
5294 if (get_property_closure != NULL)
5296 data->get_property_closure = g_closure_ref (get_property_closure);
5297 g_closure_sink (get_property_closure);
5298 if (G_CLOSURE_NEEDS_MARSHAL (get_property_closure))
5299 g_closure_set_marshal (get_property_closure, g_cclosure_marshal_generic);
5302 if (set_property_closure != NULL)
5304 data->set_property_closure = g_closure_ref (set_property_closure);
5305 g_closure_sink (set_property_closure);
5306 if (G_CLOSURE_NEEDS_MARSHAL (set_property_closure))
5307 g_closure_set_marshal (set_property_closure, g_cclosure_marshal_generic);
5314 register_object_free_func (gpointer user_data)
5316 RegisterObjectData *data = user_data;
5318 g_clear_pointer (&data->method_call_closure, g_closure_unref);
5319 g_clear_pointer (&data->get_property_closure, g_closure_unref);
5320 g_clear_pointer (&data->set_property_closure, g_closure_unref);
5326 register_with_closures_on_method_call (GDBusConnection *connection,
5327 const gchar *sender,
5328 const gchar *object_path,
5329 const gchar *interface_name,
5330 const gchar *method_name,
5331 GVariant *parameters,
5332 GDBusMethodInvocation *invocation,
5335 RegisterObjectData *data = user_data;
5336 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5338 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5339 g_value_set_object (¶ms[0], connection);
5341 g_value_init (¶ms[1], G_TYPE_STRING);
5342 g_value_set_string (¶ms[1], sender);
5344 g_value_init (¶ms[2], G_TYPE_STRING);
5345 g_value_set_string (¶ms[2], object_path);
5347 g_value_init (¶ms[3], G_TYPE_STRING);
5348 g_value_set_string (¶ms[3], interface_name);
5350 g_value_init (¶ms[4], G_TYPE_STRING);
5351 g_value_set_string (¶ms[4], method_name);
5353 g_value_init (¶ms[5], G_TYPE_VARIANT);
5354 g_value_set_variant (¶ms[5], parameters);
5356 g_value_init (¶ms[6], G_TYPE_DBUS_METHOD_INVOCATION);
5357 g_value_set_object (¶ms[6], invocation);
5359 g_closure_invoke (data->method_call_closure, NULL, G_N_ELEMENTS (params), params, NULL);
5361 g_value_unset (params + 0);
5362 g_value_unset (params + 1);
5363 g_value_unset (params + 2);
5364 g_value_unset (params + 3);
5365 g_value_unset (params + 4);
5366 g_value_unset (params + 5);
5367 g_value_unset (params + 6);
5371 register_with_closures_on_get_property (GDBusConnection *connection,
5372 const gchar *sender,
5373 const gchar *object_path,
5374 const gchar *interface_name,
5375 const gchar *property_name,
5379 RegisterObjectData *data = user_data;
5380 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5381 GValue result_value = G_VALUE_INIT;
5384 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5385 g_value_set_object (¶ms[0], connection);
5387 g_value_init (¶ms[1], G_TYPE_STRING);
5388 g_value_set_string (¶ms[1], sender);
5390 g_value_init (¶ms[2], G_TYPE_STRING);
5391 g_value_set_string (¶ms[2], object_path);
5393 g_value_init (¶ms[3], G_TYPE_STRING);
5394 g_value_set_string (¶ms[3], interface_name);
5396 g_value_init (¶ms[4], G_TYPE_STRING);
5397 g_value_set_string (¶ms[4], property_name);
5399 g_value_init (&result_value, G_TYPE_VARIANT);
5401 g_closure_invoke (data->get_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5403 result = g_value_get_variant (&result_value);
5405 g_variant_ref (result);
5407 g_value_unset (params + 0);
5408 g_value_unset (params + 1);
5409 g_value_unset (params + 2);
5410 g_value_unset (params + 3);
5411 g_value_unset (params + 4);
5412 g_value_unset (&result_value);
5415 g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5416 _("Unable to retrieve property %s.%s"),
5417 interface_name, property_name);
5423 register_with_closures_on_set_property (GDBusConnection *connection,
5424 const gchar *sender,
5425 const gchar *object_path,
5426 const gchar *interface_name,
5427 const gchar *property_name,
5432 RegisterObjectData *data = user_data;
5433 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5434 GValue result_value = G_VALUE_INIT;
5437 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5438 g_value_set_object (¶ms[0], connection);
5440 g_value_init (¶ms[1], G_TYPE_STRING);
5441 g_value_set_string (¶ms[1], sender);
5443 g_value_init (¶ms[2], G_TYPE_STRING);
5444 g_value_set_string (¶ms[2], object_path);
5446 g_value_init (¶ms[3], G_TYPE_STRING);
5447 g_value_set_string (¶ms[3], interface_name);
5449 g_value_init (¶ms[4], G_TYPE_STRING);
5450 g_value_set_string (¶ms[4], property_name);
5452 g_value_init (¶ms[5], G_TYPE_VARIANT);
5453 g_value_set_variant (¶ms[5], value);
5455 g_value_init (&result_value, G_TYPE_BOOLEAN);
5457 g_closure_invoke (data->set_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5459 result = g_value_get_boolean (&result_value);
5461 g_value_unset (params + 0);
5462 g_value_unset (params + 1);
5463 g_value_unset (params + 2);
5464 g_value_unset (params + 3);
5465 g_value_unset (params + 4);
5466 g_value_unset (params + 5);
5467 g_value_unset (&result_value);
5471 G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5472 _("Unable to set property %s.%s"),
5473 interface_name, property_name);
5479 * g_dbus_connection_register_object_with_closures: (rename-to g_dbus_connection_register_object)
5480 * @connection: A #GDBusConnection.
5481 * @object_path: The object path to register at.
5482 * @interface_info: Introspection data for the interface.
5483 * @method_call_closure: (nullable): #GClosure for handling incoming method calls.
5484 * @get_property_closure: (nullable): #GClosure for getting a property.
5485 * @set_property_closure: (nullable): #GClosure for setting a property.
5486 * @error: Return location for error or %NULL.
5488 * Version of g_dbus_connection_register_object() using closures instead of a
5489 * #GDBusInterfaceVTable for easier binding in other languages.
5491 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5492 * that can be used with g_dbus_connection_unregister_object() .
5497 g_dbus_connection_register_object_with_closures (GDBusConnection *connection,
5498 const gchar *object_path,
5499 GDBusInterfaceInfo *interface_info,
5500 GClosure *method_call_closure,
5501 GClosure *get_property_closure,
5502 GClosure *set_property_closure,
5505 RegisterObjectData *data;
5506 GDBusInterfaceVTable vtable =
5508 method_call_closure != NULL ? register_with_closures_on_method_call : NULL,
5509 get_property_closure != NULL ? register_with_closures_on_get_property : NULL,
5510 set_property_closure != NULL ? register_with_closures_on_set_property : NULL
5513 data = register_object_data_new (method_call_closure, get_property_closure, set_property_closure);
5515 return g_dbus_connection_register_object (connection,
5520 register_object_free_func,
5524 /* ---------------------------------------------------------------------------------------------------- */
5527 * g_dbus_connection_emit_signal:
5528 * @connection: a #GDBusConnection
5529 * @destination_bus_name: (nullable): the unique bus name for the destination
5530 * for the signal or %NULL to emit to all listeners
5531 * @object_path: path of remote object
5532 * @interface_name: D-Bus interface to emit a signal on
5533 * @signal_name: the name of the signal to emit
5534 * @parameters: (nullable): a #GVariant tuple with parameters for the signal
5535 * or %NULL if not passing parameters
5536 * @error: Return location for error or %NULL
5540 * If the parameters GVariant is floating, it is consumed.
5542 * This can only fail if @parameters is not compatible with the D-Bus protocol
5543 * (%G_IO_ERROR_INVALID_ARGUMENT), or if @connection has been closed
5544 * (%G_IO_ERROR_CLOSED).
5546 * Returns: %TRUE unless @error is set
5551 g_dbus_connection_emit_signal (GDBusConnection *connection,
5552 const gchar *destination_bus_name,
5553 const gchar *object_path,
5554 const gchar *interface_name,
5555 const gchar *signal_name,
5556 GVariant *parameters,
5559 GDBusMessage *message;
5565 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5566 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5567 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5568 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5569 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5570 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5571 g_return_val_if_fail (check_initialized (connection), FALSE);
5573 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5575 _g_dbus_debug_print_lock ();
5576 g_print ("========================================================================\n"
5577 "GDBus-debug:Emission:\n"
5578 " >>>> SIGNAL EMISSION %s.%s()\n"
5580 " destination %s\n",
5581 interface_name, signal_name,
5583 destination_bus_name != NULL ? destination_bus_name : "(none)");
5584 _g_dbus_debug_print_unlock ();
5587 message = g_dbus_message_new_signal (object_path,
5591 if (destination_bus_name != NULL)
5592 g_dbus_message_set_header (message,
5593 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5594 g_variant_new_string (destination_bus_name));
5596 if (parameters != NULL)
5597 g_dbus_message_set_body (message, parameters);
5599 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5600 g_object_unref (message);
5606 add_call_flags (GDBusMessage *message,
5607 GDBusCallFlags flags)
5609 GDBusMessageFlags msg_flags = 0;
5611 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5612 msg_flags |= G_DBUS_MESSAGE_FLAGS_NO_AUTO_START;
5613 if (flags & G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
5614 msg_flags |= G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION;
5616 g_dbus_message_set_flags (message, msg_flags);
5620 decode_method_reply (GDBusMessage *reply,
5621 const gchar *method_name,
5622 const GVariantType *reply_type,
5623 GUnixFDList **out_fd_list,
5629 switch (g_dbus_message_get_message_type (reply))
5631 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5632 result = g_dbus_message_get_body (reply);
5635 result = g_variant_new ("()");
5636 g_variant_ref_sink (result);
5640 g_variant_ref (result);
5643 if (!g_variant_is_of_type (result, reply_type))
5645 gchar *type_string = g_variant_type_dup_string (reply_type);
5649 G_IO_ERROR_INVALID_ARGUMENT,
5650 _("Method ā%sā returned type ā%sā, but expected ā%sā"),
5651 method_name, g_variant_get_type_string (result), type_string);
5653 g_variant_unref (result);
5654 g_free (type_string);
5661 if (out_fd_list != NULL)
5663 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5664 if (*out_fd_list != NULL)
5665 g_object_ref (*out_fd_list);
5671 case G_DBUS_MESSAGE_TYPE_ERROR:
5672 g_dbus_message_to_gerror (reply, error);
5676 g_assert_not_reached ();
5686 GVariantType *reply_type;
5687 gchar *method_name; /* for error message */
5689 GUnixFDList *fd_list;
5693 call_state_free (CallState *state)
5695 g_variant_type_free (state->reply_type);
5696 g_free (state->method_name);
5698 if (state->fd_list != NULL)
5699 g_object_unref (state->fd_list);
5700 g_slice_free (CallState, state);
5703 /* called in any thread, with the connection's lock not held */
5705 g_dbus_connection_call_done (GObject *source,
5706 GAsyncResult *result,
5709 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5710 GTask *task = user_data;
5711 CallState *state = g_task_get_task_data (task);
5712 GError *error = NULL;
5713 GDBusMessage *reply;
5714 GVariant *value = NULL;
5716 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5720 if (G_UNLIKELY (_g_dbus_debug_call ()))
5722 _g_dbus_debug_print_lock ();
5723 g_print ("========================================================================\n"
5724 "GDBus-debug:Call:\n"
5725 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5728 g_dbus_message_get_reply_serial (reply));
5731 g_print ("SUCCESS\n");
5735 g_print ("FAILED: %s\n",
5738 _g_dbus_debug_print_unlock ();
5742 value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5745 g_task_return_error (task, error);
5747 g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5749 g_clear_object (&reply);
5750 g_object_unref (task);
5753 /* called in any thread, with the connection's lock not held */
5755 g_dbus_connection_call_internal (GDBusConnection *connection,
5756 const gchar *bus_name,
5757 const gchar *object_path,
5758 const gchar *interface_name,
5759 const gchar *method_name,
5760 GVariant *parameters,
5761 const GVariantType *reply_type,
5762 GDBusCallFlags flags,
5764 GUnixFDList *fd_list,
5765 GCancellable *cancellable,
5766 GAsyncReadyCallback callback,
5769 GDBusMessage *message;
5772 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5773 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5774 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5775 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5776 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5777 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5778 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5779 g_return_if_fail (check_initialized (connection));
5781 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5783 g_return_if_fail (fd_list == NULL);
5786 message = g_dbus_message_new_method_call (bus_name,
5790 add_call_flags (message, flags);
5791 if (parameters != NULL)
5792 g_dbus_message_set_body (message, parameters);
5795 if (fd_list != NULL)
5796 g_dbus_message_set_unix_fd_list (message, fd_list);
5799 /* If the user has no callback then we can just send the message with
5800 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5801 * the logic for processing the reply. If the service sends the reply
5802 * anyway then it will just be ignored.
5804 if (callback != NULL)
5809 state = g_slice_new0 (CallState);
5810 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5812 if (reply_type == NULL)
5813 reply_type = G_VARIANT_TYPE_ANY;
5815 state->reply_type = g_variant_type_copy (reply_type);
5817 task = g_task_new (connection, cancellable, callback, user_data);
5818 g_task_set_source_tag (task, g_dbus_connection_call_internal);
5819 g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5821 g_dbus_connection_send_message_with_reply (connection,
5823 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5827 g_dbus_connection_call_done,
5832 GDBusMessageFlags flags;
5834 flags = g_dbus_message_get_flags (message);
5835 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5836 g_dbus_message_set_flags (message, flags);
5838 g_dbus_connection_send_message (connection,
5840 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5844 if (G_UNLIKELY (_g_dbus_debug_call ()))
5846 _g_dbus_debug_print_lock ();
5847 g_print ("========================================================================\n"
5848 "GDBus-debug:Call:\n"
5849 " >>>> ASYNC %s.%s()\n"
5851 " owned by name %s (serial %d)\n",
5855 bus_name != NULL ? bus_name : "(none)",
5857 _g_dbus_debug_print_unlock ();
5860 if (message != NULL)
5861 g_object_unref (message);
5864 /* called in any thread, with the connection's lock not held */
5866 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5867 GUnixFDList **out_fd_list,
5875 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5876 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5877 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5879 task = G_TASK (res);
5880 state = g_task_get_task_data (task);
5882 ret = g_task_propagate_pointer (task, error);
5886 if (out_fd_list != NULL)
5887 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5891 /* called in any user thread, with the connection's lock not held */
5893 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5894 const gchar *bus_name,
5895 const gchar *object_path,
5896 const gchar *interface_name,
5897 const gchar *method_name,
5898 GVariant *parameters,
5899 const GVariantType *reply_type,
5900 GDBusCallFlags flags,
5902 GUnixFDList *fd_list,
5903 GUnixFDList **out_fd_list,
5904 GCancellable *cancellable,
5907 GDBusMessage *message;
5908 GDBusMessage *reply;
5910 GError *local_error;
5911 GDBusSendMessageFlags send_flags;
5917 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5918 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5919 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5920 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5921 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5922 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5923 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5925 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5927 g_return_val_if_fail (fd_list == NULL, NULL);
5929 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5931 if (!(flags & CALL_FLAGS_INITIALIZING))
5932 g_return_val_if_fail (check_initialized (connection), FALSE);
5934 if (reply_type == NULL)
5935 reply_type = G_VARIANT_TYPE_ANY;
5937 message = g_dbus_message_new_method_call (bus_name,
5941 add_call_flags (message, flags);
5942 if (parameters != NULL)
5943 g_dbus_message_set_body (message, parameters);
5946 if (fd_list != NULL)
5947 g_dbus_message_set_unix_fd_list (message, fd_list);
5950 if (G_UNLIKELY (_g_dbus_debug_call ()))
5952 _g_dbus_debug_print_lock ();
5953 g_print ("========================================================================\n"
5954 "GDBus-debug:Call:\n"
5955 " >>>> SYNC %s.%s()\n"
5957 " owned by name %s\n",
5961 bus_name != NULL ? bus_name : "(none)");
5962 _g_dbus_debug_print_unlock ();
5967 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5969 /* translate from one flavour of flags to another... */
5970 if (flags & CALL_FLAGS_INITIALIZING)
5971 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5973 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5977 NULL, /* volatile guint32 *out_serial */
5981 if (G_UNLIKELY (_g_dbus_debug_call ()))
5983 _g_dbus_debug_print_lock ();
5984 g_print ("========================================================================\n"
5985 "GDBus-debug:Call:\n"
5986 " <<<< SYNC COMPLETE %s.%s()\n"
5992 g_print ("SUCCESS\n");
5996 g_print ("FAILED: %s\n",
5997 local_error->message);
5999 _g_dbus_debug_print_unlock ();
6005 *error = local_error;
6007 g_error_free (local_error);
6011 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6014 if (message != NULL)
6015 g_object_unref (message);
6017 g_object_unref (reply);
6022 /* ---------------------------------------------------------------------------------------------------- */
6025 * g_dbus_connection_call:
6026 * @connection: a #GDBusConnection
6027 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6028 * @connection is not a message bus connection
6029 * @object_path: path of remote object
6030 * @interface_name: D-Bus interface to invoke method on
6031 * @method_name: the name of the method to invoke
6032 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6033 * or %NULL if not passing parameters
6034 * @reply_type: (nullable): the expected type of the reply (which will be a
6036 * @flags: flags from the #GDBusCallFlags enumeration
6037 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6038 * timeout or %G_MAXINT for no timeout
6039 * @cancellable: (nullable): a #GCancellable or %NULL
6040 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
6041 * is satisfied or %NULL if you don't care about the result of the
6043 * @user_data: the data to pass to @callback
6045 * Asynchronously invokes the @method_name method on the
6046 * @interface_name D-Bus interface on the remote object at
6047 * @object_path owned by @bus_name.
6049 * If @connection is closed then the operation will fail with
6050 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6051 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6052 * not compatible with the D-Bus protocol, the operation fails with
6053 * %G_IO_ERROR_INVALID_ARGUMENT.
6055 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6056 * error will be raised if it does not match. Said another way, if you give a @reply_type
6057 * then any non-%NULL return value will be of this type. Unless itās
6058 * %G_VARIANT_TYPE_UNIT, the @reply_type will be a tuple containing one or more
6061 * If the @parameters #GVariant is floating, it is consumed. This allows
6062 * convenient 'inline' use of g_variant_new(), e.g.:
6063 * |[<!-- language="C" -->
6064 * g_dbus_connection_call (connection,
6065 * "org.freedesktop.StringThings",
6066 * "/org/freedesktop/StringThings",
6067 * "org.freedesktop.StringThings",
6069 * g_variant_new ("(ss)",
6073 * G_DBUS_CALL_FLAGS_NONE,
6076 * (GAsyncReadyCallback) two_strings_done,
6080 * This is an asynchronous method. When the operation is finished,
6081 * @callback will be invoked in the
6082 * [thread-default main context][g-main-context-push-thread-default]
6083 * of the thread you are calling this method from. You can then call
6084 * g_dbus_connection_call_finish() to get the result of the operation.
6085 * See g_dbus_connection_call_sync() for the synchronous version of this
6088 * If @callback is %NULL then the D-Bus method call message will be sent with
6089 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6094 g_dbus_connection_call (GDBusConnection *connection,
6095 const gchar *bus_name,
6096 const gchar *object_path,
6097 const gchar *interface_name,
6098 const gchar *method_name,
6099 GVariant *parameters,
6100 const GVariantType *reply_type,
6101 GDBusCallFlags flags,
6103 GCancellable *cancellable,
6104 GAsyncReadyCallback callback,
6107 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);
6111 * g_dbus_connection_call_finish:
6112 * @connection: a #GDBusConnection
6113 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6114 * @error: return location for error or %NULL
6116 * Finishes an operation started with g_dbus_connection_call().
6118 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6119 * return values. Free with g_variant_unref().
6124 g_dbus_connection_call_finish (GDBusConnection *connection,
6128 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6132 * g_dbus_connection_call_sync:
6133 * @connection: a #GDBusConnection
6134 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6135 * @connection is not a message bus connection
6136 * @object_path: path of remote object
6137 * @interface_name: D-Bus interface to invoke method on
6138 * @method_name: the name of the method to invoke
6139 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6140 * or %NULL if not passing parameters
6141 * @reply_type: (nullable): the expected type of the reply, or %NULL
6142 * @flags: flags from the #GDBusCallFlags enumeration
6143 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6144 * timeout or %G_MAXINT for no timeout
6145 * @cancellable: (nullable): a #GCancellable or %NULL
6146 * @error: return location for error or %NULL
6148 * Synchronously invokes the @method_name method on the
6149 * @interface_name D-Bus interface on the remote object at
6150 * @object_path owned by @bus_name.
6152 * If @connection is closed then the operation will fail with
6153 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6154 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6155 * contains a value not compatible with the D-Bus protocol, the operation
6156 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6158 * If @reply_type is non-%NULL then the reply will be checked for having
6159 * this type and an error will be raised if it does not match. Said
6160 * another way, if you give a @reply_type then any non-%NULL return
6161 * value will be of this type.
6163 * If the @parameters #GVariant is floating, it is consumed.
6164 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6165 * |[<!-- language="C" -->
6166 * g_dbus_connection_call_sync (connection,
6167 * "org.freedesktop.StringThings",
6168 * "/org/freedesktop/StringThings",
6169 * "org.freedesktop.StringThings",
6171 * g_variant_new ("(ss)",
6175 * G_DBUS_CALL_FLAGS_NONE,
6181 * The calling thread is blocked until a reply is received. See
6182 * g_dbus_connection_call() for the asynchronous version of
6185 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6186 * return values. Free with g_variant_unref().
6191 g_dbus_connection_call_sync (GDBusConnection *connection,
6192 const gchar *bus_name,
6193 const gchar *object_path,
6194 const gchar *interface_name,
6195 const gchar *method_name,
6196 GVariant *parameters,
6197 const GVariantType *reply_type,
6198 GDBusCallFlags flags,
6200 GCancellable *cancellable,
6203 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);
6206 /* ---------------------------------------------------------------------------------------------------- */
6211 * g_dbus_connection_call_with_unix_fd_list:
6212 * @connection: a #GDBusConnection
6213 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6214 * @connection is not a message bus connection
6215 * @object_path: path of remote object
6216 * @interface_name: D-Bus interface to invoke method on
6217 * @method_name: the name of the method to invoke
6218 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6219 * or %NULL if not passing parameters
6220 * @reply_type: (nullable): the expected type of the reply, or %NULL
6221 * @flags: flags from the #GDBusCallFlags enumeration
6222 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6223 * timeout or %G_MAXINT for no timeout
6224 * @fd_list: (nullable): a #GUnixFDList or %NULL
6225 * @cancellable: (nullable): a #GCancellable or %NULL
6226 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
6227 * satisfied or %NULL if you don't * care about the result of the
6229 * @user_data: The data to pass to @callback.
6231 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6233 * This method is only available on UNIX.
6238 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6239 const gchar *bus_name,
6240 const gchar *object_path,
6241 const gchar *interface_name,
6242 const gchar *method_name,
6243 GVariant *parameters,
6244 const GVariantType *reply_type,
6245 GDBusCallFlags flags,
6247 GUnixFDList *fd_list,
6248 GCancellable *cancellable,
6249 GAsyncReadyCallback callback,
6252 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);
6256 * g_dbus_connection_call_with_unix_fd_list_finish:
6257 * @connection: a #GDBusConnection
6258 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6259 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6260 * g_dbus_connection_call_with_unix_fd_list()
6261 * @error: return location for error or %NULL
6263 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6265 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6266 * return values. Free with g_variant_unref().
6271 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6272 GUnixFDList **out_fd_list,
6276 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6280 * g_dbus_connection_call_with_unix_fd_list_sync:
6281 * @connection: a #GDBusConnection
6282 * @bus_name: (nullable): a unique or well-known bus name or %NULL
6283 * if @connection is not a message bus connection
6284 * @object_path: path of remote object
6285 * @interface_name: D-Bus interface to invoke method on
6286 * @method_name: the name of the method to invoke
6287 * @parameters: (nullable): a #GVariant tuple with parameters for
6288 * the method or %NULL if not passing parameters
6289 * @reply_type: (nullable): the expected type of the reply, or %NULL
6290 * @flags: flags from the #GDBusCallFlags enumeration
6291 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6292 * timeout or %G_MAXINT for no timeout
6293 * @fd_list: (nullable): a #GUnixFDList or %NULL
6294 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6295 * @cancellable: (nullable): a #GCancellable or %NULL
6296 * @error: return location for error or %NULL
6298 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6300 * This method is only available on UNIX.
6302 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6303 * return values. Free with g_variant_unref().
6308 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6309 const gchar *bus_name,
6310 const gchar *object_path,
6311 const gchar *interface_name,
6312 const gchar *method_name,
6313 GVariant *parameters,
6314 const GVariantType *reply_type,
6315 GDBusCallFlags flags,
6317 GUnixFDList *fd_list,
6318 GUnixFDList **out_fd_list,
6319 GCancellable *cancellable,
6322 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);
6325 #endif /* G_OS_UNIX */
6327 /* ---------------------------------------------------------------------------------------------------- */
6329 struct ExportedSubtree
6333 GDBusConnection *connection;
6334 GDBusSubtreeVTable *vtable;
6335 GDBusSubtreeFlags flags;
6337 GMainContext *context;
6339 GDestroyNotify user_data_free_func;
6343 exported_subtree_free (ExportedSubtree *es)
6345 call_destroy_notify (es->context,
6346 es->user_data_free_func,
6349 g_main_context_unref (es->context);
6351 _g_dbus_subtree_vtable_free (es->vtable);
6352 g_free (es->object_path);
6356 /* called without lock held in the thread where the caller registered
6360 handle_subtree_introspect (GDBusConnection *connection,
6361 ExportedSubtree *es,
6362 GDBusMessage *message)
6366 GDBusMessage *reply;
6369 const gchar *sender;
6370 const gchar *requested_object_path;
6371 const gchar *requested_node;
6372 GDBusInterfaceInfo **interfaces;
6374 gchar **subnode_paths;
6375 gboolean has_properties_interface;
6376 gboolean has_introspectable_interface;
6380 requested_object_path = g_dbus_message_get_path (message);
6381 sender = g_dbus_message_get_sender (message);
6382 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6384 s = g_string_new (NULL);
6385 introspect_append_header (s);
6387 /* Strictly we don't need the children in dynamic mode, but we avoid the
6388 * conditionals to preserve code clarity
6390 children = es->vtable->enumerate (es->connection,
6397 requested_node = strrchr (requested_object_path, '/') + 1;
6399 /* Assert existence of object if we are not dynamic */
6400 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6401 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6406 requested_node = NULL;
6409 interfaces = es->vtable->introspect (es->connection,
6414 if (interfaces != NULL)
6416 has_properties_interface = FALSE;
6417 has_introspectable_interface = FALSE;
6419 for (n = 0; interfaces[n] != NULL; n++)
6421 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6422 has_properties_interface = TRUE;
6423 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6424 has_introspectable_interface = TRUE;
6426 if (!has_properties_interface)
6427 g_string_append (s, introspect_properties_interface);
6428 if (!has_introspectable_interface)
6429 g_string_append (s, introspect_introspectable_interface);
6431 for (n = 0; interfaces[n] != NULL; n++)
6433 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6434 g_dbus_interface_info_unref (interfaces[n]);
6436 g_free (interfaces);
6439 /* then include <node> entries from the Subtree for the root */
6442 for (n = 0; children != NULL && children[n] != NULL; n++)
6443 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6446 /* finally include nodes registered below us */
6447 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6448 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6449 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6450 g_strfreev (subnode_paths);
6452 g_string_append (s, "</node>\n");
6454 reply = g_dbus_message_new_method_reply (message);
6455 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6456 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6457 g_object_unref (reply);
6462 g_string_free (s, TRUE);
6463 g_strfreev (children);
6467 /* called without lock held in the thread where the caller registered
6471 handle_subtree_method_invocation (GDBusConnection *connection,
6472 ExportedSubtree *es,
6473 GDBusMessage *message)
6476 const gchar *sender;
6477 const gchar *interface_name;
6478 const gchar *member;
6479 const gchar *signature;
6480 const gchar *requested_object_path;
6481 const gchar *requested_node;
6483 GDBusInterfaceInfo *interface_info;
6484 const GDBusInterfaceVTable *interface_vtable;
6485 gpointer interface_user_data;
6487 GDBusInterfaceInfo **interfaces;
6488 gboolean is_property_get;
6489 gboolean is_property_set;
6490 gboolean is_property_get_all;
6495 requested_object_path = g_dbus_message_get_path (message);
6496 sender = g_dbus_message_get_sender (message);
6497 interface_name = g_dbus_message_get_interface (message);
6498 member = g_dbus_message_get_member (message);
6499 signature = g_dbus_message_get_signature (message);
6500 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6502 is_property_get = FALSE;
6503 is_property_set = FALSE;
6504 is_property_get_all = FALSE;
6505 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6507 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6508 is_property_get = TRUE;
6509 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6510 is_property_set = TRUE;
6511 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6512 is_property_get_all = TRUE;
6517 requested_node = strrchr (requested_object_path, '/') + 1;
6519 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6521 /* We don't want to dispatch to unenumerated
6522 * nodes, so ensure that the child exists.
6527 children = es->vtable->enumerate (es->connection,
6532 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6533 g_strfreev (children);
6541 requested_node = NULL;
6544 /* get introspection data for the node */
6545 interfaces = es->vtable->introspect (es->connection,
6547 requested_object_path,
6551 if (interfaces == NULL)
6554 interface_info = NULL;
6555 for (n = 0; interfaces[n] != NULL; n++)
6557 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6558 interface_info = interfaces[n];
6561 /* dispatch the call if the user wants to handle it */
6562 if (interface_info != NULL)
6564 /* figure out where to dispatch the method call */
6565 interface_user_data = NULL;
6566 interface_vtable = es->vtable->dispatch (es->connection,
6571 &interface_user_data,
6573 if (interface_vtable == NULL)
6576 CONNECTION_LOCK (connection);
6577 handled = validate_and_maybe_schedule_method_call (es->connection,
6584 interface_user_data);
6585 CONNECTION_UNLOCK (connection);
6587 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6588 else if (is_property_get || is_property_set || is_property_get_all)
6590 if (is_property_get)
6591 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6592 else if (is_property_set)
6593 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6594 else if (is_property_get_all)
6595 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6597 g_assert_not_reached ();
6599 /* see if the object supports this interface at all */
6600 for (n = 0; interfaces[n] != NULL; n++)
6602 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6603 interface_info = interfaces[n];
6606 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6607 * claims it won't support the interface
6609 if (interface_info == NULL)
6611 GDBusMessage *reply;
6612 reply = g_dbus_message_new_method_error (message,
6613 "org.freedesktop.DBus.Error.InvalidArgs",
6614 _("No such interface ā%sā"),
6616 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6617 g_object_unref (reply);
6622 /* figure out where to dispatch the property get/set/getall calls */
6623 interface_user_data = NULL;
6624 interface_vtable = es->vtable->dispatch (es->connection,
6629 &interface_user_data,
6631 if (interface_vtable == NULL)
6633 g_warning ("The subtree introspection function indicates that '%s' "
6634 "is a valid interface name, but calling the dispatch "
6635 "function on that interface gave us NULL", interface_name);
6639 if (is_property_get || is_property_set)
6641 CONNECTION_LOCK (connection);
6642 handled = validate_and_maybe_schedule_property_getset (es->connection,
6650 interface_user_data);
6651 CONNECTION_UNLOCK (connection);
6653 else if (is_property_get_all)
6655 CONNECTION_LOCK (connection);
6656 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6663 interface_user_data);
6664 CONNECTION_UNLOCK (connection);
6669 if (interfaces != NULL)
6671 for (n = 0; interfaces[n] != NULL; n++)
6672 g_dbus_interface_info_unref (interfaces[n]);
6673 g_free (interfaces);
6681 GDBusMessage *message;
6682 ExportedSubtree *es;
6683 } SubtreeDeferredData;
6686 subtree_deferred_data_free (SubtreeDeferredData *data)
6688 g_object_unref (data->message);
6692 /* called without lock held in the thread where the caller registered the subtree */
6694 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6696 SubtreeDeferredData *data = _data;
6701 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6702 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6703 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6704 handled = handle_subtree_introspect (data->es->connection,
6708 handled = handle_subtree_method_invocation (data->es->connection,
6714 CONNECTION_LOCK (data->es->connection);
6715 handled = handle_generic_unlocked (data->es->connection, data->message);
6716 CONNECTION_UNLOCK (data->es->connection);
6719 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6722 GDBusMessage *reply;
6723 reply = g_dbus_message_new_method_error (data->message,
6724 "org.freedesktop.DBus.Error.UnknownMethod",
6725 _("Method ā%sā on interface ā%sā with signature ā%sā does not exist"),
6726 g_dbus_message_get_member (data->message),
6727 g_dbus_message_get_interface (data->message),
6728 g_dbus_message_get_signature (data->message));
6729 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6730 g_object_unref (reply);
6736 /* called in GDBusWorker thread with connection's lock held */
6738 subtree_message_func (GDBusConnection *connection,
6739 ExportedSubtree *es,
6740 GDBusMessage *message)
6742 GSource *idle_source;
6743 SubtreeDeferredData *data;
6745 data = g_new0 (SubtreeDeferredData, 1);
6746 data->message = g_object_ref (message);
6749 /* defer this call to an idle handler in the right thread */
6750 idle_source = g_idle_source_new ();
6751 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6752 g_source_set_callback (idle_source,
6753 process_subtree_vtable_message_in_idle_cb,
6755 (GDestroyNotify) subtree_deferred_data_free);
6756 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6757 g_source_attach (idle_source, es->context);
6758 g_source_unref (idle_source);
6760 /* since we own the entire subtree, handlers for objects not in the subtree have been
6761 * tried already by libdbus-1 - so we just need to ensure that we're always going
6762 * to reply to the message
6768 * g_dbus_connection_register_subtree:
6769 * @connection: a #GDBusConnection
6770 * @object_path: the object path to register the subtree at
6771 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6772 * dispatch nodes in the subtree
6773 * @flags: flags used to fine tune the behavior of the subtree
6774 * @user_data: data to pass to functions in @vtable
6775 * @user_data_free_func: function to call when the subtree is unregistered
6776 * @error: return location for error or %NULL
6778 * Registers a whole subtree of dynamic objects.
6780 * The @enumerate and @introspection functions in @vtable are used to
6781 * convey, to remote callers, what nodes exist in the subtree rooted
6784 * When handling remote calls into any node in the subtree, first the
6785 * @enumerate function is used to check if the node exists. If the node exists
6786 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6787 * the @introspection function is used to check if the node supports the
6788 * requested method. If so, the @dispatch function is used to determine
6789 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6790 * #gpointer will be used to call into the interface vtable for processing
6793 * All calls into user-provided code will be invoked in the
6794 * [thread-default main context][g-main-context-push-thread-default]
6795 * of the thread you are calling this method from.
6797 * If an existing subtree is already registered at @object_path or
6798 * then @error is set to #G_IO_ERROR_EXISTS.
6800 * Note that it is valid to register regular objects (using
6801 * g_dbus_connection_register_object()) in a subtree registered with
6802 * g_dbus_connection_register_subtree() - if so, the subtree handler
6803 * is tried as the last resort. One way to think about a subtree
6804 * handler is to consider it a fallback handler for object paths not
6805 * registered via g_dbus_connection_register_object() or other bindings.
6807 * Note that @vtable will be copied so you cannot change it after
6810 * See this [server][gdbus-subtree-server] for an example of how to use
6813 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6814 * that can be used with g_dbus_connection_unregister_subtree() .
6819 g_dbus_connection_register_subtree (GDBusConnection *connection,
6820 const gchar *object_path,
6821 const GDBusSubtreeVTable *vtable,
6822 GDBusSubtreeFlags flags,
6824 GDestroyNotify user_data_free_func,
6828 ExportedSubtree *es;
6830 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6831 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6832 g_return_val_if_fail (vtable != NULL, 0);
6833 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6834 g_return_val_if_fail (check_initialized (connection), 0);
6838 CONNECTION_LOCK (connection);
6840 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6846 _("A subtree is already exported for %s"),
6851 es = g_new0 (ExportedSubtree, 1);
6852 es->object_path = g_strdup (object_path);
6853 es->connection = connection;
6855 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6857 es->id = g_atomic_int_add (&_global_subtree_registration_id, 1); /* TODO: overflow etc. */
6858 es->user_data = user_data;
6859 es->user_data_free_func = user_data_free_func;
6860 es->context = g_main_context_ref_thread_default ();
6862 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6863 g_hash_table_insert (connection->map_id_to_es,
6864 GUINT_TO_POINTER (es->id),
6870 CONNECTION_UNLOCK (connection);
6875 /* ---------------------------------------------------------------------------------------------------- */
6878 * g_dbus_connection_unregister_subtree:
6879 * @connection: a #GDBusConnection
6880 * @registration_id: a subtree registration id obtained from
6881 * g_dbus_connection_register_subtree()
6883 * Unregisters a subtree.
6885 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6890 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6891 guint registration_id)
6893 ExportedSubtree *es;
6896 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6897 g_return_val_if_fail (check_initialized (connection), FALSE);
6901 CONNECTION_LOCK (connection);
6903 es = g_hash_table_lookup (connection->map_id_to_es,
6904 GUINT_TO_POINTER (registration_id));
6908 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6909 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6914 CONNECTION_UNLOCK (connection);
6919 /* ---------------------------------------------------------------------------------------------------- */
6921 /* may be called in any thread, with connection's lock held */
6923 handle_generic_ping_unlocked (GDBusConnection *connection,
6924 const gchar *object_path,
6925 GDBusMessage *message)
6927 GDBusMessage *reply;
6928 reply = g_dbus_message_new_method_reply (message);
6929 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6930 g_object_unref (reply);
6933 /* may be called in any thread, with connection's lock held */
6935 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6936 const gchar *object_path,
6937 GDBusMessage *message)
6939 GDBusMessage *reply;
6942 if (connection->machine_id == NULL)
6947 connection->machine_id = _g_dbus_get_machine_id (&error);
6948 if (connection->machine_id == NULL)
6950 reply = g_dbus_message_new_method_error_literal (message,
6951 "org.freedesktop.DBus.Error.Failed",
6953 g_error_free (error);
6959 reply = g_dbus_message_new_method_reply (message);
6960 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6962 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6963 g_object_unref (reply);
6966 /* may be called in any thread, with connection's lock held */
6968 handle_generic_introspect_unlocked (GDBusConnection *connection,
6969 const gchar *object_path,
6970 GDBusMessage *message)
6975 GDBusMessage *reply;
6977 /* first the header */
6978 s = g_string_new (NULL);
6979 introspect_append_header (s);
6981 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6982 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6983 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6984 g_strfreev (registered);
6985 g_string_append (s, "</node>\n");
6987 reply = g_dbus_message_new_method_reply (message);
6988 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6989 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6990 g_object_unref (reply);
6991 g_string_free (s, TRUE);
6994 /* may be called in any thread, with connection's lock held */
6996 handle_generic_unlocked (GDBusConnection *connection,
6997 GDBusMessage *message)
7000 const gchar *interface_name;
7001 const gchar *member;
7002 const gchar *signature;
7005 CONNECTION_ENSURE_LOCK (connection);
7009 interface_name = g_dbus_message_get_interface (message);
7010 member = g_dbus_message_get_member (message);
7011 signature = g_dbus_message_get_signature (message);
7012 path = g_dbus_message_get_path (message);
7014 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7015 g_strcmp0 (member, "Introspect") == 0 &&
7016 g_strcmp0 (signature, "") == 0)
7018 handle_generic_introspect_unlocked (connection, path, message);
7021 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7022 g_strcmp0 (member, "Ping") == 0 &&
7023 g_strcmp0 (signature, "") == 0)
7025 handle_generic_ping_unlocked (connection, path, message);
7028 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7029 g_strcmp0 (member, "GetMachineId") == 0 &&
7030 g_strcmp0 (signature, "") == 0)
7032 handle_generic_get_machine_id_unlocked (connection, path, message);
7039 /* ---------------------------------------------------------------------------------------------------- */
7041 /* called in GDBusWorker thread with connection's lock held */
7043 distribute_method_call (GDBusConnection *connection,
7044 GDBusMessage *message)
7046 GDBusMessage *reply;
7048 ExportedSubtree *es;
7049 const gchar *object_path;
7050 const gchar *interface_name;
7051 const gchar *member;
7053 gchar *subtree_path;
7056 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7058 interface_name = g_dbus_message_get_interface (message);
7059 member = g_dbus_message_get_member (message);
7060 path = g_dbus_message_get_path (message);
7061 subtree_path = g_strdup (path);
7062 needle = strrchr (subtree_path, '/');
7063 if (needle != NULL && needle != subtree_path)
7069 g_free (subtree_path);
7070 subtree_path = NULL;
7074 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7076 _g_dbus_debug_print_lock ();
7077 g_print ("========================================================================\n"
7078 "GDBus-debug:Incoming:\n"
7079 " <<<< METHOD INVOCATION %s.%s()\n"
7081 " invoked by name %s\n"
7083 interface_name, member,
7085 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7086 g_dbus_message_get_serial (message));
7087 _g_dbus_debug_print_unlock ();
7090 object_path = g_dbus_message_get_path (message);
7091 g_assert (object_path != NULL);
7093 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7096 if (obj_message_func (connection, eo, message))
7100 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7103 if (subtree_message_func (connection, es, message))
7107 if (subtree_path != NULL)
7109 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7112 if (subtree_message_func (connection, es, message))
7117 if (handle_generic_unlocked (connection, message))
7120 /* if we end up here, the message has not been not handled - so return an error saying this */
7121 reply = g_dbus_message_new_method_error (message,
7122 "org.freedesktop.DBus.Error.UnknownMethod",
7123 _("No such interface ā%sā on object at path %s"),
7126 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7127 g_object_unref (reply);
7130 g_free (subtree_path);
7133 /* ---------------------------------------------------------------------------------------------------- */
7135 /* Called in any user thread, with the message_bus_lock held. */
7137 message_bus_get_singleton (GBusType bus_type,
7141 const gchar *starter_bus;
7147 case G_BUS_TYPE_SESSION:
7148 ret = &the_session_bus;
7151 case G_BUS_TYPE_SYSTEM:
7152 ret = &the_system_bus;
7155 case G_BUS_TYPE_STARTER:
7156 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7157 if (g_strcmp0 (starter_bus, "session") == 0)
7159 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7162 else if (g_strcmp0 (starter_bus, "system") == 0)
7164 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7169 if (starter_bus != NULL)
7173 G_IO_ERROR_INVALID_ARGUMENT,
7174 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7175 " ā unknown value ā%sā"),
7180 g_set_error_literal (error,
7182 G_IO_ERROR_INVALID_ARGUMENT,
7183 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7184 "variable is not set"));
7190 g_assert_not_reached ();
7198 /* Called in any user thread, without holding locks. */
7199 static GDBusConnection *
7200 get_uninitialized_connection (GBusType bus_type,
7201 GCancellable *cancellable,
7204 GWeakRef *singleton;
7205 GDBusConnection *ret;
7209 G_LOCK (message_bus_lock);
7210 singleton = message_bus_get_singleton (bus_type, error);
7211 if (singleton == NULL)
7214 ret = g_weak_ref_get (singleton);
7219 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7220 if (address == NULL)
7222 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7224 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7225 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7226 "exit-on-close", TRUE,
7229 g_weak_ref_set (singleton, ret);
7233 g_assert (ret != NULL);
7236 G_UNLOCK (message_bus_lock);
7240 /* May be called from any thread. Must not hold message_bus_lock. */
7242 _g_bus_get_singleton_if_exists (GBusType bus_type)
7244 GWeakRef *singleton;
7245 GDBusConnection *ret = NULL;
7247 G_LOCK (message_bus_lock);
7248 singleton = message_bus_get_singleton (bus_type, NULL);
7249 if (singleton == NULL)
7252 ret = g_weak_ref_get (singleton);
7255 G_UNLOCK (message_bus_lock);
7259 /* May be called from any thread. Must not hold message_bus_lock. */
7261 _g_bus_forget_singleton (GBusType bus_type)
7263 GWeakRef *singleton;
7265 G_LOCK (message_bus_lock);
7267 singleton = message_bus_get_singleton (bus_type, NULL);
7269 if (singleton != NULL)
7270 g_weak_ref_set (singleton, NULL);
7272 G_UNLOCK (message_bus_lock);
7277 * @bus_type: a #GBusType
7278 * @cancellable: (nullable): a #GCancellable or %NULL
7279 * @error: return location for error or %NULL
7281 * Synchronously connects to the message bus specified by @bus_type.
7282 * Note that the returned object may shared with other callers,
7283 * e.g. if two separate parts of a process calls this function with
7284 * the same @bus_type, they will share the same object.
7286 * This is a synchronous failable function. See g_bus_get() and
7287 * g_bus_get_finish() for the asynchronous version.
7289 * The returned object is a singleton, that is, shared with other
7290 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7291 * event that you need a private message bus connection, use
7292 * g_dbus_address_get_for_bus_sync() and
7293 * g_dbus_connection_new_for_address().
7295 * Note that the returned #GDBusConnection object will (usually) have
7296 * the #GDBusConnection:exit-on-close property set to %TRUE.
7298 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7299 * Free with g_object_unref().
7304 g_bus_get_sync (GBusType bus_type,
7305 GCancellable *cancellable,
7308 GDBusConnection *connection;
7310 _g_dbus_initialize ();
7312 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7314 connection = get_uninitialized_connection (bus_type, cancellable, error);
7315 if (connection == NULL)
7318 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7320 g_object_unref (connection);
7329 bus_get_async_initable_cb (GObject *source_object,
7333 GTask *task = user_data;
7334 GError *error = NULL;
7336 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7340 g_assert (error != NULL);
7341 g_task_return_error (task, error);
7342 g_object_unref (source_object);
7346 g_task_return_pointer (task, source_object, g_object_unref);
7348 g_object_unref (task);
7353 * @bus_type: a #GBusType
7354 * @cancellable: (nullable): a #GCancellable or %NULL
7355 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7356 * @user_data: the data to pass to @callback
7358 * Asynchronously connects to the message bus specified by @bus_type.
7360 * When the operation is finished, @callback will be invoked. You can
7361 * then call g_bus_get_finish() to get the result of the operation.
7363 * This is a asynchronous failable function. See g_bus_get_sync() for
7364 * the synchronous version.
7369 g_bus_get (GBusType bus_type,
7370 GCancellable *cancellable,
7371 GAsyncReadyCallback callback,
7374 GDBusConnection *connection;
7376 GError *error = NULL;
7378 _g_dbus_initialize ();
7380 task = g_task_new (NULL, cancellable, callback, user_data);
7381 g_task_set_source_tag (task, g_bus_get);
7383 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7384 if (connection == NULL)
7386 g_assert (error != NULL);
7387 g_task_return_error (task, error);
7388 g_object_unref (task);
7392 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7395 bus_get_async_initable_cb,
7402 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7404 * @error: return location for error or %NULL
7406 * Finishes an operation started with g_bus_get().
7408 * The returned object is a singleton, that is, shared with other
7409 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7410 * event that you need a private message bus connection, use
7411 * g_dbus_address_get_for_bus_sync() and
7412 * g_dbus_connection_new_for_address().
7414 * Note that the returned #GDBusConnection object will (usually) have
7415 * the #GDBusConnection:exit-on-close property set to %TRUE.
7417 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7418 * Free with g_object_unref().
7423 g_bus_get_finish (GAsyncResult *res,
7426 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7427 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7429 return g_task_propagate_pointer (G_TASK (res), error);
7432 /* ---------------------------------------------------------------------------------------------------- */