1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
98 #include "gdbusauth.h"
99 #include "gdbusutils.h"
100 #include "gdbusaddress.h"
101 #include "gdbusmessage.h"
102 #include "gdbusconnection.h"
103 #include "gdbuserror.h"
104 #include "gioenumtypes.h"
105 #include "gdbusintrospection.h"
106 #include "gdbusmethodinvocation.h"
107 #include "gdbusprivate.h"
108 #include "gdbusauthobserver.h"
109 #include "ginitable.h"
110 #include "gasyncinitable.h"
111 #include "giostream.h"
112 #include "gasyncresult.h"
114 #include "gmarshal-internal.h"
117 #include "gunixconnection.h"
118 #include "gunixfdmessage.h"
121 #include "glibintl.h"
123 #define G_DBUS_CONNECTION_FLAGS_ALL \
124 (G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT | \
125 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER | \
126 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS | \
127 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION | \
128 G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING | \
129 G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER)
132 * SECTION:gdbusconnection
133 * @short_description: D-Bus Connections
134 * @include: gio/gio.h
136 * The #GDBusConnection type is used for D-Bus connections to remote
137 * peers such as a message buses. It is a low-level API that offers a
138 * lot of flexibility. For instance, it lets you establish a connection
139 * over any transport that can by represented as a #GIOStream.
141 * This class is rarely used directly in D-Bus clients. If you are writing
142 * a D-Bus client, it is often easier to use the g_bus_own_name(),
143 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
145 * As an exception to the usual GLib rule that a particular object must not
146 * be used by two threads at the same time, #GDBusConnection's methods may be
147 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
148 * can safely return the same #GDBusConnection when called from any thread.
150 * Most of the ways to obtain a #GDBusConnection automatically initialize it
151 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
152 * g_bus_get(), and the synchronous versions of those methods, give you an
153 * initialized connection. Language bindings for GIO should use
154 * g_initable_new() or g_async_initable_new_async(), which also initialize the
157 * If you construct an uninitialized #GDBusConnection, such as via
158 * g_object_new(), you must initialize it via g_initable_init() or
159 * g_async_initable_init_async() before using its methods or properties.
160 * Calling methods or accessing properties on a #GDBusConnection that has not
161 * completed initialization successfully is considered to be invalid, and leads
162 * to undefined behaviour. In particular, if initialization fails with a
163 * #GError, the only valid thing you can do with that #GDBusConnection is to
164 * free it with g_object_unref().
166 * ## An example D-Bus server # {#gdbus-server}
168 * Here is an example for a D-Bus server:
169 * [gdbus-example-server.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-server.c)
171 * ## An example for exporting a subtree # {#gdbus-subtree-server}
173 * Here is an example for exporting a subtree:
174 * [gdbus-example-subtree.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-subtree.c)
176 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
178 * Here is an example for passing UNIX file descriptors:
179 * [gdbus-unix-fd-client.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-unix-fd-client.c)
181 * ## An example for exporting a GObject # {#gdbus-export}
183 * Here is an example for exporting a #GObject:
184 * [gdbus-example-export.c](https://gitlab.gnome.org/GNOME/glib/-/blob/HEAD/gio/tests/gdbus-example-export.c)
187 /* ---------------------------------------------------------------------------------------------------- */
189 typedef struct _GDBusConnectionClass GDBusConnectionClass;
192 * GDBusConnectionClass:
193 * @closed: Signal class handler for the #GDBusConnection::closed signal.
195 * Class structure for #GDBusConnection.
199 struct _GDBusConnectionClass
202 GObjectClass parent_class;
206 void (*closed) (GDBusConnection *connection,
207 gboolean remote_peer_vanished,
211 G_LOCK_DEFINE_STATIC (message_bus_lock);
213 static GWeakRef the_session_bus;
214 static GWeakRef the_system_bus;
216 /* Extra pseudo-member of GDBusSendMessageFlags.
217 * Set by initable_init() to indicate that despite not being initialized yet,
218 * enough of the only-valid-after-init members are set that we can send a
219 * message, and we're being called from its thread, so no memory barrier is
220 * required before accessing them.
222 #define SEND_MESSAGE_FLAGS_INITIALIZING (1u << 31)
224 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
225 #define CALL_FLAGS_INITIALIZING (1u << 31)
227 /* ---------------------------------------------------------------------------------------------------- */
231 GDestroyNotify callback;
233 } CallDestroyNotifyData;
236 call_destroy_notify_data_in_idle (gpointer user_data)
238 CallDestroyNotifyData *data = user_data;
239 data->callback (data->user_data);
244 call_destroy_notify_data_free (CallDestroyNotifyData *data)
250 * call_destroy_notify: <internal>
251 * @context: (nullable): A #GMainContext or %NULL.
252 * @callback: (nullable): A #GDestroyNotify or %NULL.
253 * @user_data: Data to pass to @callback.
255 * Schedules @callback to run in @context.
258 call_destroy_notify (GMainContext *context,
259 GDestroyNotify callback,
262 GSource *idle_source;
263 CallDestroyNotifyData *data;
265 if (callback == NULL)
268 data = g_new0 (CallDestroyNotifyData, 1);
269 data->callback = callback;
270 data->user_data = user_data;
272 idle_source = g_idle_source_new ();
273 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
274 g_source_set_callback (idle_source,
275 call_destroy_notify_data_in_idle,
277 (GDestroyNotify) call_destroy_notify_data_free);
278 g_source_set_static_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
279 g_source_attach (idle_source, context);
280 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 authenticated 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 gint atomic_flags; /* (atomic) */
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
906 * [D-Bus specification](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses)
907 * uses the term ‘UUID’ to refer to this, whereas GLib consistently uses the
908 * term ‘GUID’ for historical reasons.
910 * Despite its name, the format of #GDBusConnection:guid does not follow
911 * [RFC 4122](https://datatracker.ietf.org/doc/html/rfc4122) or the Microsoft
916 g_object_class_install_property (gobject_class,
918 g_param_spec_string ("guid",
920 P_("GUID of the server peer"),
924 G_PARAM_CONSTRUCT_ONLY |
925 G_PARAM_STATIC_NAME |
926 G_PARAM_STATIC_BLURB |
927 G_PARAM_STATIC_NICK));
930 * GDBusConnection:unique-name:
932 * The unique name as assigned by the message bus or %NULL if the
933 * connection is not open or not a message bus connection.
937 g_object_class_install_property (gobject_class,
939 g_param_spec_string ("unique-name",
941 P_("Unique name of bus connection"),
944 G_PARAM_STATIC_NAME |
945 G_PARAM_STATIC_BLURB |
946 G_PARAM_STATIC_NICK));
949 * GDBusConnection:closed:
951 * A boolean specifying whether the connection has been closed.
955 g_object_class_install_property (gobject_class,
957 g_param_spec_boolean ("closed",
959 P_("Whether the connection is closed"),
962 G_PARAM_STATIC_NAME |
963 G_PARAM_STATIC_BLURB |
964 G_PARAM_STATIC_NICK));
967 * GDBusConnection:exit-on-close:
969 * A boolean specifying whether the process will be terminated (by
970 * calling `raise(SIGTERM)`) if the connection is closed by the
973 * Note that #GDBusConnection objects returned by g_bus_get_finish()
974 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
978 g_object_class_install_property (gobject_class,
980 g_param_spec_boolean ("exit-on-close",
982 P_("Whether the process is terminated when the connection is closed"),
986 G_PARAM_STATIC_NAME |
987 G_PARAM_STATIC_BLURB |
988 G_PARAM_STATIC_NICK));
991 * GDBusConnection:capabilities:
993 * Flags from the #GDBusCapabilityFlags enumeration
994 * representing connection features negotiated with the other peer.
998 g_object_class_install_property (gobject_class,
999 PROP_CAPABILITY_FLAGS,
1000 g_param_spec_flags ("capabilities",
1003 G_TYPE_DBUS_CAPABILITY_FLAGS,
1004 G_DBUS_CAPABILITY_FLAGS_NONE,
1006 G_PARAM_STATIC_NAME |
1007 G_PARAM_STATIC_BLURB |
1008 G_PARAM_STATIC_NICK));
1011 * GDBusConnection:authentication-observer:
1013 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1017 g_object_class_install_property (gobject_class,
1018 PROP_AUTHENTICATION_OBSERVER,
1019 g_param_spec_object ("authentication-observer",
1020 P_("Authentication Observer"),
1021 P_("Object used to assist in the authentication process"),
1022 G_TYPE_DBUS_AUTH_OBSERVER,
1024 G_PARAM_CONSTRUCT_ONLY |
1025 G_PARAM_STATIC_NAME |
1026 G_PARAM_STATIC_BLURB |
1027 G_PARAM_STATIC_NICK));
1030 * GDBusConnection::closed:
1031 * @connection: the #GDBusConnection emitting the signal
1032 * @remote_peer_vanished: %TRUE if @connection is closed because the
1033 * remote peer closed its end of the connection
1034 * @error: (nullable): a #GError with more details about the event or %NULL
1036 * Emitted when the connection is closed.
1038 * The cause of this event can be
1040 * - If g_dbus_connection_close() is called. In this case
1041 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1043 * - If the remote peer closes the connection. In this case
1044 * @remote_peer_vanished is set to %TRUE and @error is set.
1046 * - If the remote peer sends invalid or malformed data. In this
1047 * case @remote_peer_vanished is set to %FALSE and @error is set.
1049 * Upon receiving this signal, you should give up your reference to
1050 * @connection. You are guaranteed that this signal is emitted only
1055 signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1056 G_TYPE_DBUS_CONNECTION,
1058 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1061 _g_cclosure_marshal_VOID__BOOLEAN_BOXED,
1066 g_signal_set_va_marshaller (signals[CLOSED_SIGNAL],
1067 G_TYPE_FROM_CLASS (klass),
1068 _g_cclosure_marshal_VOID__BOOLEAN_BOXEDv);
1072 g_dbus_connection_init (GDBusConnection *connection)
1074 g_mutex_init (&connection->lock);
1075 g_mutex_init (&connection->init_lock);
1077 connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1079 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1081 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1083 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1086 (GDestroyNotify) g_ptr_array_unref);
1088 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1091 (GDestroyNotify) exported_object_free);
1093 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1096 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1099 (GDestroyNotify) exported_subtree_free);
1101 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1104 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1107 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1109 connection->filters = g_ptr_array_new ();
1113 * g_dbus_connection_get_stream:
1114 * @connection: a #GDBusConnection
1116 * Gets the underlying stream used for IO.
1118 * While the #GDBusConnection is active, it will interact with this
1119 * stream from a worker thread, so it is not safe to interact with
1120 * the stream directly.
1122 * Returns: (transfer none) (not nullable): the stream used for IO
1127 g_dbus_connection_get_stream (GDBusConnection *connection)
1129 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1131 /* do not use g_return_val_if_fail(), we want the memory barrier */
1132 if (!check_initialized (connection))
1135 return connection->stream;
1139 * g_dbus_connection_start_message_processing:
1140 * @connection: a #GDBusConnection
1142 * If @connection was created with
1143 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1144 * starts processing messages. Does nothing on if @connection wasn't
1145 * created with this flag or if the method has already been called.
1150 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1152 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1154 /* do not use g_return_val_if_fail(), we want the memory barrier */
1155 if (!check_initialized (connection))
1158 g_assert (connection->worker != NULL);
1159 _g_dbus_worker_unfreeze (connection->worker);
1163 * g_dbus_connection_is_closed:
1164 * @connection: a #GDBusConnection
1166 * Gets whether @connection is closed.
1168 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1173 g_dbus_connection_is_closed (GDBusConnection *connection)
1177 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1179 flags = g_atomic_int_get (&connection->atomic_flags);
1181 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1185 * g_dbus_connection_get_capabilities:
1186 * @connection: a #GDBusConnection
1188 * Gets the capabilities negotiated with the remote peer
1190 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1194 GDBusCapabilityFlags
1195 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1197 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1199 /* do not use g_return_val_if_fail(), we want the memory barrier */
1200 if (!check_initialized (connection))
1201 return G_DBUS_CAPABILITY_FLAGS_NONE;
1203 return connection->capabilities;
1207 * g_dbus_connection_get_flags:
1208 * @connection: a #GDBusConnection
1210 * Gets the flags used to construct this connection
1212 * Returns: zero or more flags from the #GDBusConnectionFlags enumeration
1216 GDBusConnectionFlags
1217 g_dbus_connection_get_flags (GDBusConnection *connection)
1219 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CONNECTION_FLAGS_NONE);
1221 /* do not use g_return_val_if_fail(), we want the memory barrier */
1222 if (!check_initialized (connection))
1223 return G_DBUS_CONNECTION_FLAGS_NONE;
1225 return connection->flags;
1228 /* ---------------------------------------------------------------------------------------------------- */
1230 /* Called in a temporary thread without holding locks. */
1232 flush_in_thread_func (GTask *task,
1233 gpointer source_object,
1235 GCancellable *cancellable)
1237 GError *error = NULL;
1239 if (g_dbus_connection_flush_sync (source_object,
1242 g_task_return_boolean (task, TRUE);
1244 g_task_return_error (task, error);
1248 * g_dbus_connection_flush:
1249 * @connection: a #GDBusConnection
1250 * @cancellable: (nullable): a #GCancellable or %NULL
1251 * @callback: (nullable): a #GAsyncReadyCallback to call when the
1252 * request is satisfied or %NULL if you don't care about the result
1253 * @user_data: The data to pass to @callback
1255 * Asynchronously flushes @connection, that is, writes all queued
1256 * outgoing message to the transport and then flushes the transport
1257 * (using g_output_stream_flush_async()). This is useful in programs
1258 * that wants to emit a D-Bus signal and then exit immediately. Without
1259 * flushing the connection, there is no guaranteed that the message has
1260 * been sent to the networking buffers in the OS kernel.
1262 * This is an asynchronous method. When the operation is finished,
1263 * @callback will be invoked in the
1264 * [thread-default main context][g-main-context-push-thread-default]
1265 * of the thread you are calling this method from. You can
1266 * then call g_dbus_connection_flush_finish() to get the result of the
1267 * operation. See g_dbus_connection_flush_sync() for the synchronous
1273 g_dbus_connection_flush (GDBusConnection *connection,
1274 GCancellable *cancellable,
1275 GAsyncReadyCallback callback,
1280 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1282 task = g_task_new (connection, cancellable, callback, user_data);
1283 g_task_set_source_tag (task, g_dbus_connection_flush);
1284 g_task_run_in_thread (task, flush_in_thread_func);
1285 g_object_unref (task);
1289 * g_dbus_connection_flush_finish:
1290 * @connection: a #GDBusConnection
1291 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1292 * to g_dbus_connection_flush()
1293 * @error: return location for error or %NULL
1295 * Finishes an operation started with g_dbus_connection_flush().
1297 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1302 g_dbus_connection_flush_finish (GDBusConnection *connection,
1306 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1307 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1308 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1310 return g_task_propagate_boolean (G_TASK (res), error);
1314 * g_dbus_connection_flush_sync:
1315 * @connection: a #GDBusConnection
1316 * @cancellable: (nullable): a #GCancellable or %NULL
1317 * @error: return location for error or %NULL
1319 * Synchronously flushes @connection. The calling thread is blocked
1320 * until this is done. See g_dbus_connection_flush() for the
1321 * asynchronous version of this method and more details about what it
1324 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1329 g_dbus_connection_flush_sync (GDBusConnection *connection,
1330 GCancellable *cancellable,
1335 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1336 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1340 /* This is only a best-effort attempt to see whether the connection is
1341 * closed, so it doesn't need the lock. If the connection closes just
1342 * after this check, but before scheduling the flush operation, the
1343 * result will be more or less the same as if the connection closed while
1344 * the flush operation was pending - it'll fail with either CLOSED or
1347 if (!check_unclosed (connection, 0, error))
1350 g_assert (connection->worker != NULL);
1352 ret = _g_dbus_worker_flush_sync (connection->worker,
1360 /* ---------------------------------------------------------------------------------------------------- */
1364 GDBusConnection *connection;
1366 gboolean remote_peer_vanished;
1370 emit_closed_data_free (EmitClosedData *data)
1372 g_object_unref (data->connection);
1373 if (data->error != NULL)
1374 g_error_free (data->error);
1378 /* Called in a user thread that has acquired the main context that was
1379 * thread-default when the object was constructed
1382 emit_closed_in_idle (gpointer user_data)
1384 EmitClosedData *data = user_data;
1387 g_object_notify (G_OBJECT (data->connection), "closed");
1388 g_signal_emit (data->connection,
1389 signals[CLOSED_SIGNAL],
1391 data->remote_peer_vanished,
1397 /* Can be called from any thread, must hold lock.
1398 * FLAG_CLOSED must already have been set.
1401 schedule_closed_unlocked (GDBusConnection *connection,
1402 gboolean remote_peer_vanished,
1405 GSource *idle_source;
1406 EmitClosedData *data;
1408 CONNECTION_ENSURE_LOCK (connection);
1410 data = g_new0 (EmitClosedData, 1);
1411 data->connection = g_object_ref (connection);
1412 data->remote_peer_vanished = remote_peer_vanished;
1413 data->error = error != NULL ? g_error_copy (error) : NULL;
1415 idle_source = g_idle_source_new ();
1416 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1417 g_source_set_callback (idle_source,
1418 emit_closed_in_idle,
1420 (GDestroyNotify) emit_closed_data_free);
1421 g_source_set_static_name (idle_source, "[gio] emit_closed_in_idle");
1422 g_source_attach (idle_source, connection->main_context_at_construction);
1423 g_source_unref (idle_source);
1426 /* ---------------------------------------------------------------------------------------------------- */
1429 * g_dbus_connection_close:
1430 * @connection: a #GDBusConnection
1431 * @cancellable: (nullable): a #GCancellable or %NULL
1432 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1433 * satisfied or %NULL if you don't care about the result
1434 * @user_data: The data to pass to @callback
1436 * Closes @connection. Note that this never causes the process to
1437 * exit (this might only happen if the other end of a shared message
1438 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1440 * Once the connection is closed, operations such as sending a message
1441 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1442 * will not automatically flush the connection so queued messages may
1443 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1445 * If @connection is already closed, this method fails with
1446 * %G_IO_ERROR_CLOSED.
1448 * When @connection has been closed, the #GDBusConnection::closed
1449 * signal is emitted in the
1450 * [thread-default main context][g-main-context-push-thread-default]
1451 * of the thread that @connection was constructed in.
1453 * This is an asynchronous method. When the operation is finished,
1454 * @callback will be invoked in the
1455 * [thread-default main context][g-main-context-push-thread-default]
1456 * of the thread you are calling this method from. You can
1457 * then call g_dbus_connection_close_finish() to get the result of the
1458 * operation. See g_dbus_connection_close_sync() for the synchronous
1464 g_dbus_connection_close (GDBusConnection *connection,
1465 GCancellable *cancellable,
1466 GAsyncReadyCallback callback,
1471 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1473 /* do not use g_return_val_if_fail(), we want the memory barrier */
1474 if (!check_initialized (connection))
1477 g_assert (connection->worker != NULL);
1479 task = g_task_new (connection, cancellable, callback, user_data);
1480 g_task_set_source_tag (task, g_dbus_connection_close);
1481 _g_dbus_worker_close (connection->worker, task);
1482 g_object_unref (task);
1486 * g_dbus_connection_close_finish:
1487 * @connection: a #GDBusConnection
1488 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1489 * to g_dbus_connection_close()
1490 * @error: return location for error or %NULL
1492 * Finishes an operation started with g_dbus_connection_close().
1494 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1499 g_dbus_connection_close_finish (GDBusConnection *connection,
1503 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1504 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1505 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1507 return g_task_propagate_boolean (G_TASK (res), error);
1512 GAsyncResult *result;
1515 /* Can be called by any thread, without the connection lock */
1517 sync_close_cb (GObject *source_object,
1521 SyncCloseData *data = user_data;
1523 data->result = g_object_ref (res);
1524 g_main_loop_quit (data->loop);
1528 * g_dbus_connection_close_sync:
1529 * @connection: a #GDBusConnection
1530 * @cancellable: (nullable): a #GCancellable or %NULL
1531 * @error: return location for error or %NULL
1533 * Synchronously closes @connection. The calling thread is blocked
1534 * until this is done. See g_dbus_connection_close() for the
1535 * asynchronous version of this method and more details about what it
1538 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1543 g_dbus_connection_close_sync (GDBusConnection *connection,
1544 GCancellable *cancellable,
1549 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1550 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1554 if (check_unclosed (connection, 0, error))
1556 GMainContext *context;
1559 context = g_main_context_new ();
1560 g_main_context_push_thread_default (context);
1561 data.loop = g_main_loop_new (context, TRUE);
1564 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1565 g_main_loop_run (data.loop);
1566 ret = g_dbus_connection_close_finish (connection, data.result, error);
1568 g_object_unref (data.result);
1569 g_main_loop_unref (data.loop);
1570 g_main_context_pop_thread_default (context);
1571 g_main_context_unref (context);
1577 /* ---------------------------------------------------------------------------------------------------- */
1580 * g_dbus_connection_get_last_serial:
1581 * @connection: a #GDBusConnection
1583 * Retrieves the last serial number assigned to a #GDBusMessage on
1584 * the current thread. This includes messages sent via both low-level
1585 * API such as g_dbus_connection_send_message() as well as
1586 * high-level API such as g_dbus_connection_emit_signal(),
1587 * g_dbus_connection_call() or g_dbus_proxy_call().
1589 * Returns: the last used serial or zero when no message has been sent
1590 * within the current thread
1595 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1599 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1601 CONNECTION_LOCK (connection);
1602 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1604 CONNECTION_UNLOCK (connection);
1609 /* ---------------------------------------------------------------------------------------------------- */
1611 /* Can be called by any thread, with the connection lock held */
1613 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1614 GDBusMessage *message,
1615 GDBusSendMessageFlags flags,
1616 guint32 *out_serial,
1621 guint32 serial_to_use;
1623 CONNECTION_ENSURE_LOCK (connection);
1625 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1626 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1628 /* TODO: check all necessary headers are present */
1630 if (out_serial != NULL)
1633 /* If we're in initable_init(), don't check for being initialized, to avoid
1634 * chicken-and-egg problems. initable_init() is responsible for setting up
1635 * our prerequisites (mainly connection->worker), and only calling us
1636 * from its own thread (so no memory barrier is needed).
1638 if (!check_unclosed (connection,
1639 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1643 blob = g_dbus_message_to_blob (message,
1645 connection->capabilities,
1650 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1651 serial_to_use = g_dbus_message_get_serial (message);
1653 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1658 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1661 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1664 g_assert_not_reached ();
1669 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1670 blob_size, serial_to_use, connection);
1671 g_printerr ("----\n");
1672 hexdump (blob, blob_size);
1673 g_printerr ("----\n");
1676 /* TODO: use connection->auth to encode the blob */
1678 if (out_serial != NULL)
1679 *out_serial = serial_to_use;
1681 /* store used serial for the current thread */
1682 /* TODO: watch the thread disposal and remove associated record
1684 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1686 g_hash_table_replace (connection->map_thread_to_last_serial,
1688 GUINT_TO_POINTER (serial_to_use));
1690 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1691 g_dbus_message_set_serial (message, serial_to_use);
1693 g_dbus_message_lock (message);
1695 _g_dbus_worker_send_message (connection->worker,
1697 (gchar*) blob, /* transfer ownership */
1704 * g_dbus_connection_send_message:
1705 * @connection: a #GDBusConnection
1706 * @message: a #GDBusMessage
1707 * @flags: flags affecting how the message is sent
1708 * @out_serial: (out) (optional): return location for serial number assigned
1709 * to @message when sending it or %NULL
1710 * @error: Return location for error or %NULL
1712 * Asynchronously sends @message to the peer represented by @connection.
1714 * Unless @flags contain the
1715 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1716 * will be assigned by @connection and set on @message via
1717 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1718 * serial number used will be written to this location prior to
1719 * submitting the message to the underlying transport. While it has a `volatile`
1720 * qualifier, this is a historical artifact and the argument passed to it should
1721 * not be `volatile`.
1723 * If @connection is closed then the operation will fail with
1724 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1725 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1727 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1728 * for an example of how to use this low-level API to send and receive
1729 * UNIX file descriptors.
1731 * Note that @message must be unlocked, unless @flags contain the
1732 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1734 * Returns: %TRUE if the message was well-formed and queued for
1735 * transmission, %FALSE if @error is set
1740 g_dbus_connection_send_message (GDBusConnection *connection,
1741 GDBusMessage *message,
1742 GDBusSendMessageFlags flags,
1743 volatile guint32 *out_serial,
1748 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1749 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1750 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1751 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1753 CONNECTION_LOCK (connection);
1754 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, (guint32 *) out_serial, error);
1755 CONNECTION_UNLOCK (connection);
1759 /* ---------------------------------------------------------------------------------------------------- */
1765 gulong cancellable_handler_id;
1767 GSource *timeout_source;
1772 /* Can be called from any thread with or without lock held */
1774 send_message_data_free (SendMessageData *data)
1776 g_assert (data->timeout_source == NULL);
1777 g_assert (data->cancellable_handler_id == 0);
1779 g_slice_free (SendMessageData, data);
1782 /* ---------------------------------------------------------------------------------------------------- */
1784 /* can be called from any thread with lock held; @task is (transfer full) */
1786 send_message_with_reply_cleanup (GTask *task, gboolean remove)
1788 GDBusConnection *connection = g_task_get_source_object (task);
1789 SendMessageData *data = g_task_get_task_data (task);
1791 CONNECTION_ENSURE_LOCK (connection);
1793 g_assert (!data->delivered);
1795 data->delivered = TRUE;
1797 if (data->timeout_source != NULL)
1799 g_source_destroy (data->timeout_source);
1800 data->timeout_source = NULL;
1802 if (data->cancellable_handler_id > 0)
1804 g_cancellable_disconnect (g_task_get_cancellable (task), data->cancellable_handler_id);
1805 data->cancellable_handler_id = 0;
1810 gboolean removed = g_hash_table_remove (connection->map_method_serial_to_task,
1811 GUINT_TO_POINTER (data->serial));
1812 g_warn_if_fail (removed);
1815 g_object_unref (task);
1818 /* ---------------------------------------------------------------------------------------------------- */
1820 /* Called from GDBus worker thread with lock held; @task is (transfer full). */
1822 send_message_data_deliver_reply_unlocked (GTask *task,
1823 GDBusMessage *reply)
1825 SendMessageData *data = g_task_get_task_data (task);
1827 if (data->delivered)
1830 g_task_return_pointer (task, g_object_ref (reply), g_object_unref);
1832 send_message_with_reply_cleanup (task, TRUE);
1838 /* Called from a user thread, lock is not held */
1840 send_message_data_deliver_error (GTask *task,
1843 const char *message)
1845 GDBusConnection *connection = g_task_get_source_object (task);
1846 SendMessageData *data = g_task_get_task_data (task);
1848 CONNECTION_LOCK (connection);
1849 if (data->delivered)
1851 CONNECTION_UNLOCK (connection);
1855 g_object_ref (task);
1856 send_message_with_reply_cleanup (task, TRUE);
1857 CONNECTION_UNLOCK (connection);
1859 g_task_return_new_error (task, domain, code, "%s", message);
1860 g_object_unref (task);
1863 /* ---------------------------------------------------------------------------------------------------- */
1865 /* Called from a user thread, lock is not held; @task is (transfer full) */
1867 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1869 GTask *task = user_data;
1871 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_CANCELLED,
1872 _("Operation was cancelled"));
1876 /* Can be called from any thread with or without lock held */
1878 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1881 GTask *task = user_data;
1882 GSource *idle_source;
1884 /* postpone cancellation to idle handler since we may be called directly
1885 * via g_cancellable_connect() (e.g. holding lock)
1887 idle_source = g_idle_source_new ();
1888 g_source_set_static_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
1889 g_task_attach_source (task, idle_source, send_message_with_reply_cancelled_idle_cb);
1890 g_source_unref (idle_source);
1893 /* ---------------------------------------------------------------------------------------------------- */
1895 /* Called from a user thread, lock is not held; @task is (transfer full) */
1897 send_message_with_reply_timeout_cb (gpointer user_data)
1899 GTask *task = user_data;
1901 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
1902 _("Timeout was reached"));
1906 /* ---------------------------------------------------------------------------------------------------- */
1908 /* Called from a user thread, connection's lock is held */
1910 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1911 GDBusMessage *message,
1912 GDBusSendMessageFlags flags,
1914 guint32 *out_serial,
1915 GCancellable *cancellable,
1916 GAsyncReadyCallback callback,
1920 SendMessageData *data;
1921 GError *error = NULL;
1924 if (out_serial == NULL)
1925 out_serial = &serial;
1927 if (timeout_msec == -1)
1928 timeout_msec = 25 * 1000;
1930 data = g_slice_new0 (SendMessageData);
1931 task = g_task_new (connection, cancellable, callback, user_data);
1932 g_task_set_source_tag (task,
1933 g_dbus_connection_send_message_with_reply_unlocked);
1934 g_task_set_task_data (task, data, (GDestroyNotify) send_message_data_free);
1936 if (g_task_return_error_if_cancelled (task))
1938 g_object_unref (task);
1942 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1944 g_task_return_error (task, error);
1945 g_object_unref (task);
1948 data->serial = *out_serial;
1950 if (cancellable != NULL)
1952 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1953 G_CALLBACK (send_message_with_reply_cancelled_cb),
1954 g_object_ref (task),
1958 if (timeout_msec != G_MAXINT)
1960 data->timeout_source = g_timeout_source_new (timeout_msec);
1961 g_task_attach_source (task, data->timeout_source,
1962 (GSourceFunc) send_message_with_reply_timeout_cb);
1963 g_source_unref (data->timeout_source);
1966 g_hash_table_insert (connection->map_method_serial_to_task,
1967 GUINT_TO_POINTER (*out_serial),
1968 g_steal_pointer (&task));
1972 * g_dbus_connection_send_message_with_reply:
1973 * @connection: a #GDBusConnection
1974 * @message: a #GDBusMessage
1975 * @flags: flags affecting how the message is sent
1976 * @timeout_msec: the timeout in milliseconds, -1 to use the default
1977 * timeout or %G_MAXINT for no timeout
1978 * @out_serial: (out) (optional): return location for serial number assigned
1979 * to @message when sending it or %NULL
1980 * @cancellable: (nullable): a #GCancellable or %NULL
1981 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
1982 * is satisfied or %NULL if you don't care about the result
1983 * @user_data: The data to pass to @callback
1985 * Asynchronously sends @message to the peer represented by @connection.
1987 * Unless @flags contain the
1988 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1989 * will be assigned by @connection and set on @message via
1990 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1991 * serial number used will be written to this location prior to
1992 * submitting the message to the underlying transport. While it has a `volatile`
1993 * qualifier, this is a historical artifact and the argument passed to it should
1994 * not be `volatile`.
1996 * If @connection is closed then the operation will fail with
1997 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1998 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1999 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2001 * This is an asynchronous method. When the operation is finished, @callback
2002 * will be invoked in the
2003 * [thread-default main context][g-main-context-push-thread-default]
2004 * of the thread you are calling this method from. You can then call
2005 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2006 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2008 * Note that @message must be unlocked, unless @flags contain the
2009 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2011 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2012 * for an example of how to use this low-level API to send and receive
2013 * UNIX file descriptors.
2018 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2019 GDBusMessage *message,
2020 GDBusSendMessageFlags flags,
2022 volatile guint32 *out_serial,
2023 GCancellable *cancellable,
2024 GAsyncReadyCallback callback,
2027 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2028 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2029 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2030 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2032 CONNECTION_LOCK (connection);
2033 g_dbus_connection_send_message_with_reply_unlocked (connection,
2037 (guint32 *) out_serial,
2041 CONNECTION_UNLOCK (connection);
2045 * g_dbus_connection_send_message_with_reply_finish:
2046 * @connection: a #GDBusConnection
2047 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2048 * g_dbus_connection_send_message_with_reply()
2049 * @error: teturn location for error or %NULL
2051 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2053 * Note that @error is only set if a local in-process error
2054 * occurred. That is to say that the returned #GDBusMessage object may
2055 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2056 * g_dbus_message_to_gerror() to transcode this to a #GError.
2058 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2059 * for an example of how to use this low-level API to send and receive
2060 * UNIX file descriptors.
2062 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2067 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2071 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2072 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
2073 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2075 return g_task_propagate_pointer (G_TASK (res), error);
2078 /* ---------------------------------------------------------------------------------------------------- */
2083 GMainContext *context;
2085 } SendMessageSyncData;
2087 /* Called from a user thread, lock is not held */
2089 send_message_with_reply_sync_cb (GDBusConnection *connection,
2093 SendMessageSyncData *data = user_data;
2094 data->res = g_object_ref (res);
2095 g_main_loop_quit (data->loop);
2099 * g_dbus_connection_send_message_with_reply_sync:
2100 * @connection: a #GDBusConnection
2101 * @message: a #GDBusMessage
2102 * @flags: flags affecting how the message is sent.
2103 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2104 * timeout or %G_MAXINT for no timeout
2105 * @out_serial: (out) (optional): return location for serial number
2106 * assigned to @message when sending it or %NULL
2107 * @cancellable: (nullable): a #GCancellable or %NULL
2108 * @error: return location for error or %NULL
2110 * Synchronously sends @message to the peer represented by @connection
2111 * and blocks the calling thread until a reply is received or the
2112 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2113 * for the asynchronous version of this method.
2115 * Unless @flags contain the
2116 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2117 * will be assigned by @connection and set on @message via
2118 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2119 * serial number used will be written to this location prior to
2120 * submitting the message to the underlying transport. While it has a `volatile`
2121 * qualifier, this is a historical artifact and the argument passed to it should
2122 * not be `volatile`.
2124 * If @connection is closed then the operation will fail with
2125 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2126 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2127 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2129 * Note that @error is only set if a local in-process error
2130 * occurred. That is to say that the returned #GDBusMessage object may
2131 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2132 * g_dbus_message_to_gerror() to transcode this to a #GError.
2134 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2135 * for an example of how to use this low-level API to send and receive
2136 * UNIX file descriptors.
2138 * Note that @message must be unlocked, unless @flags contain the
2139 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2141 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2142 * to @message or %NULL if @error is set
2147 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2148 GDBusMessage *message,
2149 GDBusSendMessageFlags flags,
2151 volatile guint32 *out_serial,
2152 GCancellable *cancellable,
2155 SendMessageSyncData data;
2156 GDBusMessage *reply;
2158 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2159 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2160 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2161 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2162 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2165 data.context = g_main_context_new ();
2166 data.loop = g_main_loop_new (data.context, FALSE);
2168 g_main_context_push_thread_default (data.context);
2170 g_dbus_connection_send_message_with_reply (connection,
2176 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2178 g_main_loop_run (data.loop);
2179 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2183 g_main_context_pop_thread_default (data.context);
2185 g_main_context_unref (data.context);
2186 g_main_loop_unref (data.loop);
2188 g_object_unref (data.res);
2193 /* ---------------------------------------------------------------------------------------------------- */
2199 GDBusMessageFilterFunction filter_function;
2201 GDestroyNotify user_data_free_func;
2202 GMainContext *context;
2206 filter_data_destroy (FilterData *filter, gboolean notify_sync)
2210 if (filter->user_data_free_func != NULL)
2211 filter->user_data_free_func (filter->user_data);
2215 call_destroy_notify (filter->context,
2216 filter->user_data_free_func,
2219 g_main_context_unref (filter->context);
2223 /* requires CONNECTION_LOCK */
2224 static FilterData **
2225 copy_filter_list (GPtrArray *filters)
2230 copy = g_new (FilterData *, filters->len + 1);
2231 for (n = 0; n < filters->len; n++)
2233 copy[n] = filters->pdata[n];
2234 copy[n]->ref_count++;
2241 /* requires CONNECTION_LOCK */
2243 free_filter_list (FilterData **filters)
2247 for (n = 0; filters[n]; n++)
2249 filters[n]->ref_count--;
2250 if (filters[n]->ref_count == 0)
2251 filter_data_destroy (filters[n], FALSE);
2256 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2258 on_worker_message_received (GDBusWorker *worker,
2259 GDBusMessage *message,
2262 GDBusConnection *connection;
2263 FilterData **filters;
2267 G_LOCK (message_bus_lock);
2268 alive = g_hash_table_contains (alive_connections, user_data);
2271 G_UNLOCK (message_bus_lock);
2274 connection = G_DBUS_CONNECTION (user_data);
2275 g_object_ref (connection);
2276 G_UNLOCK (message_bus_lock);
2278 //g_debug ("in on_worker_message_received");
2280 g_object_ref (message);
2281 g_dbus_message_lock (message);
2283 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2285 /* First collect the set of callback functions */
2286 CONNECTION_LOCK (connection);
2287 filters = copy_filter_list (connection->filters);
2288 CONNECTION_UNLOCK (connection);
2290 /* then call the filters in order (without holding the lock) */
2291 for (n = 0; filters[n]; n++)
2293 message = filters[n]->filter_function (connection,
2296 filters[n]->user_data);
2297 if (message == NULL)
2299 g_dbus_message_lock (message);
2302 CONNECTION_LOCK (connection);
2303 free_filter_list (filters);
2304 CONNECTION_UNLOCK (connection);
2306 /* Standard dispatch unless the filter ate the message - no need to
2307 * do anything if the message was altered
2309 if (message != NULL)
2311 GDBusMessageType message_type;
2313 message_type = g_dbus_message_get_message_type (message);
2314 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2316 guint32 reply_serial;
2319 reply_serial = g_dbus_message_get_reply_serial (message);
2320 CONNECTION_LOCK (connection);
2321 task = g_hash_table_lookup (connection->map_method_serial_to_task,
2322 GUINT_TO_POINTER (reply_serial));
2325 /* This removes @task from @map_method_serial_to_task. */
2326 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2327 send_message_data_deliver_reply_unlocked (task, message);
2331 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2333 CONNECTION_UNLOCK (connection);
2335 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2337 CONNECTION_LOCK (connection);
2338 distribute_signals (connection, message);
2339 CONNECTION_UNLOCK (connection);
2341 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2343 CONNECTION_LOCK (connection);
2344 distribute_method_call (connection, message);
2345 CONNECTION_UNLOCK (connection);
2349 if (message != NULL)
2350 g_object_unref (message);
2351 g_object_unref (connection);
2354 /* Called in GDBusWorker's thread, lock is not held */
2355 static GDBusMessage *
2356 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2357 GDBusMessage *message,
2360 GDBusConnection *connection;
2361 FilterData **filters;
2365 G_LOCK (message_bus_lock);
2366 alive = g_hash_table_contains (alive_connections, user_data);
2369 G_UNLOCK (message_bus_lock);
2372 connection = G_DBUS_CONNECTION (user_data);
2373 g_object_ref (connection);
2374 G_UNLOCK (message_bus_lock);
2376 //g_debug ("in on_worker_message_about_to_be_sent");
2378 /* First collect the set of callback functions */
2379 CONNECTION_LOCK (connection);
2380 filters = copy_filter_list (connection->filters);
2381 CONNECTION_UNLOCK (connection);
2383 /* then call the filters in order (without holding the lock) */
2384 for (n = 0; filters[n]; n++)
2386 g_dbus_message_lock (message);
2387 message = filters[n]->filter_function (connection,
2390 filters[n]->user_data);
2391 if (message == NULL)
2395 CONNECTION_LOCK (connection);
2396 free_filter_list (filters);
2397 CONNECTION_UNLOCK (connection);
2399 g_object_unref (connection);
2404 /* called with connection lock held, in GDBusWorker thread */
2406 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2408 GTask *task = value;
2409 SendMessageData *data = g_task_get_task_data (task);
2411 if (data->delivered)
2414 g_task_return_new_error (task,
2417 _("The connection is closed"));
2419 /* Ask send_message_with_reply_cleanup not to remove the element from the
2420 * hash table - we're in the middle of a foreach; that would be unsafe.
2421 * Instead, return TRUE from this function so that it gets removed safely.
2423 send_message_with_reply_cleanup (task, FALSE);
2427 /* Called in GDBusWorker's thread - we must not block - without lock held */
2429 on_worker_closed (GDBusWorker *worker,
2430 gboolean remote_peer_vanished,
2434 GDBusConnection *connection;
2436 guint old_atomic_flags;
2438 G_LOCK (message_bus_lock);
2439 alive = g_hash_table_contains (alive_connections, user_data);
2442 G_UNLOCK (message_bus_lock);
2445 connection = G_DBUS_CONNECTION (user_data);
2446 g_object_ref (connection);
2447 G_UNLOCK (message_bus_lock);
2449 //g_debug ("in on_worker_closed: %s", error->message);
2451 CONNECTION_LOCK (connection);
2452 /* Even though this is atomic, we do it inside the lock to avoid breaking
2453 * assumptions in remove_match_rule(). We'd need the lock in a moment
2454 * anyway, so, no loss.
2456 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2458 if (!(old_atomic_flags & FLAG_CLOSED))
2460 g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2461 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2463 CONNECTION_UNLOCK (connection);
2465 g_object_unref (connection);
2468 /* ---------------------------------------------------------------------------------------------------- */
2470 /* Determines the biggest set of capabilities we can support on this
2473 * Called with the init_lock held.
2475 static GDBusCapabilityFlags
2476 get_offered_capabilities_max (GDBusConnection *connection)
2478 GDBusCapabilityFlags ret;
2479 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2481 if (G_IS_UNIX_CONNECTION (connection->stream))
2482 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2487 /* Called in a user thread, lock is not held */
2489 initable_init (GInitable *initable,
2490 GCancellable *cancellable,
2493 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2496 /* This method needs to be idempotent to work with the singleton
2497 * pattern. See the docs for g_initable_init(). We implement this by
2500 * Unfortunately we can't use the main lock since the on_worker_*()
2501 * callbacks above needs the lock during initialization (for message
2502 * bus connections we do a synchronous Hello() call on the bus).
2504 g_mutex_lock (&connection->init_lock);
2508 /* Make this a no-op if we're already initialized (successfully or
2511 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2513 ret = (connection->initialization_error == NULL);
2517 /* Because of init_lock, we can't get here twice in different threads */
2518 g_assert (connection->initialization_error == NULL);
2520 /* The user can pass multiple (but mutally exclusive) construct
2523 * - stream (of type GIOStream)
2524 * - address (of type gchar*)
2526 * At the end of the day we end up with a non-NULL GIOStream
2527 * object in connection->stream.
2529 if (connection->address != NULL)
2531 g_assert (connection->stream == NULL);
2533 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2534 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS) ||
2535 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER))
2537 g_set_error_literal (&connection->initialization_error,
2539 G_IO_ERROR_INVALID_ARGUMENT,
2540 _("Unsupported flags encountered when constructing a client-side connection"));
2544 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2545 NULL, /* TODO: out_guid */
2547 &connection->initialization_error);
2548 if (connection->stream == NULL)
2551 else if (connection->stream != NULL)
2557 g_assert_not_reached ();
2560 /* Authenticate the connection */
2561 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2563 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2564 g_assert (connection->guid != NULL);
2565 connection->auth = _g_dbus_auth_new (connection->stream);
2566 if (!_g_dbus_auth_run_server (connection->auth,
2567 connection->authentication_observer,
2569 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2570 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER),
2571 get_offered_capabilities_max (connection),
2572 &connection->capabilities,
2573 &connection->credentials,
2575 &connection->initialization_error))
2578 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2580 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2581 g_assert (connection->guid == NULL);
2582 connection->auth = _g_dbus_auth_new (connection->stream);
2583 connection->guid = _g_dbus_auth_run_client (connection->auth,
2584 connection->authentication_observer,
2585 get_offered_capabilities_max (connection),
2586 &connection->capabilities,
2588 &connection->initialization_error);
2589 if (connection->guid == NULL)
2593 if (connection->authentication_observer != NULL)
2595 g_object_unref (connection->authentication_observer);
2596 connection->authentication_observer = NULL;
2599 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2601 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2604 /* We want all IO operations to be non-blocking since they happen in
2605 * the worker thread which is shared by _all_ connections.
2607 if (G_IS_SOCKET_CONNECTION (connection->stream))
2609 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2613 G_LOCK (message_bus_lock);
2614 if (alive_connections == NULL)
2615 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2616 g_hash_table_add (alive_connections, connection);
2617 G_UNLOCK (message_bus_lock);
2619 connection->worker = _g_dbus_worker_new (connection->stream,
2620 connection->capabilities,
2621 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2622 on_worker_message_received,
2623 on_worker_message_about_to_be_sent,
2627 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2628 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2630 GVariant *hello_result;
2632 /* we could lift this restriction by adding code in gdbusprivate.c */
2633 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2635 g_set_error_literal (&connection->initialization_error,
2638 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2642 hello_result = g_dbus_connection_call_sync (connection,
2643 "org.freedesktop.DBus", /* name */
2644 "/org/freedesktop/DBus", /* path */
2645 "org.freedesktop.DBus", /* interface */
2647 NULL, /* parameters */
2648 G_VARIANT_TYPE ("(s)"),
2649 CALL_FLAGS_INITIALIZING,
2651 NULL, /* TODO: cancellable */
2652 &connection->initialization_error);
2653 if (hello_result == NULL)
2656 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2657 g_variant_unref (hello_result);
2658 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2665 g_assert (connection->initialization_error != NULL);
2666 g_propagate_error (error, g_error_copy (connection->initialization_error));
2669 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2670 g_mutex_unlock (&connection->init_lock);
2676 initable_iface_init (GInitableIface *initable_iface)
2678 initable_iface->init = initable_init;
2681 /* ---------------------------------------------------------------------------------------------------- */
2684 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2689 /* ---------------------------------------------------------------------------------------------------- */
2692 * g_dbus_connection_new:
2693 * @stream: a #GIOStream
2694 * @guid: (nullable): the GUID to use if authenticating as a server or %NULL
2695 * @flags: flags describing how to make the connection
2696 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2697 * @cancellable: (nullable): a #GCancellable or %NULL
2698 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2699 * @user_data: the data to pass to @callback
2701 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2702 * with the end represented by @stream.
2704 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2705 * will be put into non-blocking mode.
2707 * The D-Bus connection will interact with @stream from a worker thread.
2708 * As a result, the caller should not interact with @stream after this
2709 * method has been called, except by calling g_object_unref() on it.
2711 * If @observer is not %NULL it may be used to control the
2712 * authentication process.
2714 * When the operation is finished, @callback will be invoked. You can
2715 * then call g_dbus_connection_new_finish() to get the result of the
2718 * This is an asynchronous failable constructor. See
2719 * g_dbus_connection_new_sync() for the synchronous
2725 g_dbus_connection_new (GIOStream *stream,
2727 GDBusConnectionFlags flags,
2728 GDBusAuthObserver *observer,
2729 GCancellable *cancellable,
2730 GAsyncReadyCallback callback,
2733 _g_dbus_initialize ();
2735 g_return_if_fail (G_IS_IO_STREAM (stream));
2736 g_return_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0);
2738 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2746 "authentication-observer", observer,
2751 * g_dbus_connection_new_finish:
2752 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2753 * passed to g_dbus_connection_new().
2754 * @error: return location for error or %NULL
2756 * Finishes an operation started with g_dbus_connection_new().
2758 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set. Free
2759 * with g_object_unref().
2764 g_dbus_connection_new_finish (GAsyncResult *res,
2768 GObject *source_object;
2770 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2771 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2773 source_object = g_async_result_get_source_object (res);
2774 g_assert (source_object != NULL);
2775 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2778 g_object_unref (source_object);
2780 return G_DBUS_CONNECTION (object);
2786 * g_dbus_connection_new_sync:
2787 * @stream: a #GIOStream
2788 * @guid: (nullable): the GUID to use if authenticating as a server or %NULL
2789 * @flags: flags describing how to make the connection
2790 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2791 * @cancellable: (nullable): a #GCancellable or %NULL
2792 * @error: return location for error or %NULL
2794 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2795 * with the end represented by @stream.
2797 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2798 * will be put into non-blocking mode.
2800 * The D-Bus connection will interact with @stream from a worker thread.
2801 * As a result, the caller should not interact with @stream after this
2802 * method has been called, except by calling g_object_unref() on it.
2804 * If @observer is not %NULL it may be used to control the
2805 * authentication process.
2807 * This is a synchronous failable constructor. See
2808 * g_dbus_connection_new() for the asynchronous version.
2810 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
2811 * Free with g_object_unref().
2816 g_dbus_connection_new_sync (GIOStream *stream,
2818 GDBusConnectionFlags flags,
2819 GDBusAuthObserver *observer,
2820 GCancellable *cancellable,
2823 _g_dbus_initialize ();
2824 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2825 g_return_val_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0, NULL);
2826 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2827 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2833 "authentication-observer", observer,
2837 /* ---------------------------------------------------------------------------------------------------- */
2840 * g_dbus_connection_new_for_address:
2841 * @address: a D-Bus address
2842 * @flags: flags describing how to make the connection
2843 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2844 * @cancellable: (nullable): a #GCancellable or %NULL
2845 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2846 * @user_data: the data to pass to @callback
2848 * Asynchronously connects and sets up a D-Bus client connection for
2849 * exchanging D-Bus messages with an endpoint specified by @address
2850 * which must be in the
2851 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2853 * This constructor can only be used to initiate client-side
2854 * connections - use g_dbus_connection_new() if you need to act as the
2855 * server. In particular, @flags cannot contain the
2856 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER,
2857 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS or
2858 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER flags.
2860 * When the operation is finished, @callback will be invoked. You can
2861 * then call g_dbus_connection_new_for_address_finish() to get the result of
2864 * If @observer is not %NULL it may be used to control the
2865 * authentication process.
2867 * This is an asynchronous failable constructor. See
2868 * g_dbus_connection_new_for_address_sync() for the synchronous
2874 g_dbus_connection_new_for_address (const gchar *address,
2875 GDBusConnectionFlags flags,
2876 GDBusAuthObserver *observer,
2877 GCancellable *cancellable,
2878 GAsyncReadyCallback callback,
2881 _g_dbus_initialize ();
2883 g_return_if_fail (address != NULL);
2884 g_return_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0);
2886 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2893 "authentication-observer", observer,
2898 * g_dbus_connection_new_for_address_finish:
2899 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2900 * to g_dbus_connection_new()
2901 * @error: return location for error or %NULL
2903 * Finishes an operation started with g_dbus_connection_new_for_address().
2905 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
2906 * Free with g_object_unref().
2911 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2915 GObject *source_object;
2917 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2918 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2920 source_object = g_async_result_get_source_object (res);
2921 g_assert (source_object != NULL);
2922 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2925 g_object_unref (source_object);
2927 return G_DBUS_CONNECTION (object);
2933 * g_dbus_connection_new_for_address_sync:
2934 * @address: a D-Bus address
2935 * @flags: flags describing how to make the connection
2936 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2937 * @cancellable: (nullable): a #GCancellable or %NULL
2938 * @error: return location for error or %NULL
2940 * Synchronously connects and sets up a D-Bus client connection for
2941 * exchanging D-Bus messages with an endpoint specified by @address
2942 * which must be in the
2943 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2945 * This constructor can only be used to initiate client-side
2946 * connections - use g_dbus_connection_new_sync() if you need to act
2947 * as the server. In particular, @flags cannot contain the
2948 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER,
2949 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS or
2950 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER flags.
2952 * This is a synchronous failable constructor. See
2953 * g_dbus_connection_new_for_address() for the asynchronous version.
2955 * If @observer is not %NULL it may be used to control the
2956 * authentication process.
2958 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
2959 * Free with g_object_unref().
2964 g_dbus_connection_new_for_address_sync (const gchar *address,
2965 GDBusConnectionFlags flags,
2966 GDBusAuthObserver *observer,
2967 GCancellable *cancellable,
2970 _g_dbus_initialize ();
2972 g_return_val_if_fail (address != NULL, NULL);
2973 g_return_val_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0, NULL);
2974 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2975 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2980 "authentication-observer", observer,
2984 /* ---------------------------------------------------------------------------------------------------- */
2987 * g_dbus_connection_set_exit_on_close:
2988 * @connection: a #GDBusConnection
2989 * @exit_on_close: whether the process should be terminated
2990 * when @connection is closed by the remote peer
2992 * Sets whether the process should be terminated when @connection is
2993 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2996 * Note that this function should be used with care. Most modern UNIX
2997 * desktops tie the notion of a user session with the session bus, and expect
2998 * all of a user's applications to quit when their bus connection goes away.
2999 * If you are setting @exit_on_close to %FALSE for the shared session
3000 * bus connection, you should make sure that your application exits
3001 * when the user session ends.
3006 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3007 gboolean exit_on_close)
3009 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3012 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3014 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3019 * g_dbus_connection_get_exit_on_close:
3020 * @connection: a #GDBusConnection
3022 * Gets whether the process is terminated when @connection is
3023 * closed by the remote peer. See
3024 * #GDBusConnection:exit-on-close for more details.
3026 * Returns: whether the process is terminated when @connection is
3027 * closed by the remote peer
3032 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3034 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3036 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3043 * g_dbus_connection_get_guid:
3044 * @connection: a #GDBusConnection
3046 * The GUID of the peer performing the role of server when
3047 * authenticating. See #GDBusConnection:guid for more details.
3049 * Returns: (not nullable): The GUID. Do not free this string, it is owned by
3055 g_dbus_connection_get_guid (GDBusConnection *connection)
3057 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3058 return connection->guid;
3062 * g_dbus_connection_get_unique_name:
3063 * @connection: a #GDBusConnection
3065 * Gets the unique name of @connection as assigned by the message
3066 * bus. This can also be used to figure out if @connection is a
3067 * message bus connection.
3069 * Returns: (nullable): the unique name or %NULL if @connection is not a message
3070 * bus connection. Do not free this string, it is owned by
3076 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3078 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3080 /* do not use g_return_val_if_fail(), we want the memory barrier */
3081 if (!check_initialized (connection))
3084 return connection->bus_unique_name;
3088 * g_dbus_connection_get_peer_credentials:
3089 * @connection: a #GDBusConnection
3091 * Gets the credentials of the authenticated peer. This will always
3092 * return %NULL unless @connection acted as a server
3093 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3094 * when set up and the client passed credentials as part of the
3095 * authentication process.
3097 * In a message bus setup, the message bus is always the server and
3098 * each application is a client. So this method will always return
3099 * %NULL for message bus clients.
3101 * Returns: (transfer none) (nullable): a #GCredentials or %NULL if not
3102 * available. Do not free this object, it is owned by @connection.
3107 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3109 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3111 /* do not use g_return_val_if_fail(), we want the memory barrier */
3112 if (!check_initialized (connection))
3115 return connection->credentials;
3118 /* ---------------------------------------------------------------------------------------------------- */
3120 static guint _global_filter_id = 1; /* (atomic) */
3123 * g_dbus_connection_add_filter:
3124 * @connection: a #GDBusConnection
3125 * @filter_function: a filter function
3126 * @user_data: user data to pass to @filter_function
3127 * @user_data_free_func: function to free @user_data with when filter
3128 * is removed or %NULL
3130 * Adds a message filter. Filters are handlers that are run on all
3131 * incoming and outgoing messages, prior to standard dispatch. Filters
3132 * are run in the order that they were added. The same handler can be
3133 * added as a filter more than once, in which case it will be run more
3134 * than once. Filters added during a filter callback won't be run on
3135 * the message being processed. Filter functions are allowed to modify
3136 * and even drop messages.
3138 * Note that filters are run in a dedicated message handling thread so
3139 * they can't block and, generally, can't do anything but signal a
3140 * worker thread. Also note that filters are rarely needed - use API
3141 * such as g_dbus_connection_send_message_with_reply(),
3142 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3144 * If a filter consumes an incoming message the message is not
3145 * dispatched anywhere else - not even the standard dispatch machinery
3146 * (that API such as g_dbus_connection_signal_subscribe() and
3147 * g_dbus_connection_send_message_with_reply() relies on) will see the
3148 * message. Similarly, if a filter consumes an outgoing message, the
3149 * message will not be sent to the other peer.
3151 * If @user_data_free_func is non-%NULL, it will be called (in the
3152 * thread-default main context of the thread you are calling this
3153 * method from) at some point after @user_data is no longer
3154 * needed. (It is not guaranteed to be called synchronously when the
3155 * filter is removed, and may be called after @connection has been
3158 * Returns: a filter identifier that can be used with
3159 * g_dbus_connection_remove_filter()
3164 g_dbus_connection_add_filter (GDBusConnection *connection,
3165 GDBusMessageFilterFunction filter_function,
3167 GDestroyNotify user_data_free_func)
3171 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3172 g_return_val_if_fail (filter_function != NULL, 0);
3173 g_return_val_if_fail (check_initialized (connection), 0);
3175 CONNECTION_LOCK (connection);
3176 data = g_new0 (FilterData, 1);
3177 data->id = (guint) g_atomic_int_add (&_global_filter_id, 1); /* TODO: overflow etc. */
3178 data->ref_count = 1;
3179 data->filter_function = filter_function;
3180 data->user_data = user_data;
3181 data->user_data_free_func = user_data_free_func;
3182 data->context = g_main_context_ref_thread_default ();
3183 g_ptr_array_add (connection->filters, data);
3184 CONNECTION_UNLOCK (connection);
3189 /* only called from finalize(), removes all filters */
3191 purge_all_filters (GDBusConnection *connection)
3195 for (n = 0; n < connection->filters->len; n++)
3196 filter_data_destroy (connection->filters->pdata[n], FALSE);
3200 * g_dbus_connection_remove_filter:
3201 * @connection: a #GDBusConnection
3202 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3206 * Note that since filters run in a different thread, there is a race
3207 * condition where it is possible that the filter will be running even
3208 * after calling g_dbus_connection_remove_filter(), so you cannot just
3209 * free data that the filter might be using. Instead, you should pass
3210 * a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
3211 * called when it is guaranteed that the data is no longer needed.
3216 g_dbus_connection_remove_filter (GDBusConnection *connection,
3221 FilterData *to_destroy;
3223 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3224 g_return_if_fail (check_initialized (connection));
3226 CONNECTION_LOCK (connection);
3229 for (n = 0; n < connection->filters->len; n++)
3231 FilterData *data = connection->filters->pdata[n];
3232 if (data->id == filter_id)
3235 g_ptr_array_remove_index (connection->filters, n);
3237 if (data->ref_count == 0)
3242 CONNECTION_UNLOCK (connection);
3244 /* do free without holding lock */
3245 if (to_destroy != NULL)
3246 filter_data_destroy (to_destroy, TRUE);
3249 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3253 /* ---------------------------------------------------------------------------------------------------- */
3259 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3260 gchar *interface_name;
3264 GDBusSignalFlags flags;
3265 GPtrArray *subscribers; /* (owned) (element-type SignalSubscriber) */
3269 signal_data_free (SignalData *signal_data)
3271 g_free (signal_data->rule);
3272 g_free (signal_data->sender);
3273 g_free (signal_data->sender_unique_name);
3274 g_free (signal_data->interface_name);
3275 g_free (signal_data->member);
3276 g_free (signal_data->object_path);
3277 g_free (signal_data->arg0);
3278 g_ptr_array_unref (signal_data->subscribers);
3279 g_free (signal_data);
3284 /* All fields are immutable after construction. */
3285 gatomicrefcount ref_count;
3286 GDBusSignalCallback callback;
3288 GDestroyNotify user_data_free_func;
3290 GMainContext *context;
3293 static SignalSubscriber *
3294 signal_subscriber_ref (SignalSubscriber *subscriber)
3296 g_atomic_ref_count_inc (&subscriber->ref_count);
3301 signal_subscriber_unref (SignalSubscriber *subscriber)
3303 if (g_atomic_ref_count_dec (&subscriber->ref_count))
3305 /* Destroy the user data. It doesn’t matter which thread
3306 * signal_subscriber_unref() is called in (or whether it’s called with a
3307 * lock held), as call_destroy_notify() always defers to the next
3308 * #GMainContext iteration. */
3309 call_destroy_notify (subscriber->context,
3310 subscriber->user_data_free_func,
3311 subscriber->user_data);
3313 g_main_context_unref (subscriber->context);
3314 g_free (subscriber);
3319 args_to_rule (const gchar *sender,
3320 const gchar *interface_name,
3321 const gchar *member,
3322 const gchar *object_path,
3324 GDBusSignalFlags flags)
3328 rule = g_string_new ("type='signal'");
3329 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3330 g_string_prepend_c (rule, '-');
3332 g_string_append_printf (rule, ",sender='%s'", sender);
3333 if (interface_name != NULL)
3334 g_string_append_printf (rule, ",interface='%s'", interface_name);
3336 g_string_append_printf (rule, ",member='%s'", member);
3337 if (object_path != NULL)
3338 g_string_append_printf (rule, ",path='%s'", object_path);
3342 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3343 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3344 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3345 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3347 g_string_append_printf (rule, ",arg0='%s'", arg0);
3350 return g_string_free (rule, FALSE);
3353 static guint _global_subscriber_id = 1; /* (atomic) */
3354 static guint _global_registration_id = 1; /* (atomic) */
3355 static guint _global_subtree_registration_id = 1; /* (atomic) */
3357 /* ---------------------------------------------------------------------------------------------------- */
3359 /* Called in a user thread, lock is held */
3361 add_match_rule (GDBusConnection *connection,
3362 const gchar *match_rule)
3365 GDBusMessage *message;
3367 if (match_rule[0] == '-')
3370 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3371 "/org/freedesktop/DBus", /* path */
3372 "org.freedesktop.DBus", /* interface */
3374 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3376 if (!g_dbus_connection_send_message_unlocked (connection,
3378 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3382 g_critical ("Error while sending AddMatch() message: %s", error->message);
3383 g_error_free (error);
3385 g_object_unref (message);
3388 /* ---------------------------------------------------------------------------------------------------- */
3390 /* Called in a user thread, lock is held */
3392 remove_match_rule (GDBusConnection *connection,
3393 const gchar *match_rule)
3396 GDBusMessage *message;
3398 if (match_rule[0] == '-')
3401 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3402 "/org/freedesktop/DBus", /* path */
3403 "org.freedesktop.DBus", /* interface */
3405 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3408 if (!g_dbus_connection_send_message_unlocked (connection,
3410 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3414 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3415 * critical; but we're holding the lock, and our caller checked whether
3416 * we were already closed, so we can't get that error.
3418 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3419 g_error_free (error);
3421 g_object_unref (message);
3424 /* ---------------------------------------------------------------------------------------------------- */
3427 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3429 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3430 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3431 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3432 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3433 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3436 /* ---------------------------------------------------------------------------------------------------- */
3439 * g_dbus_connection_signal_subscribe:
3440 * @connection: a #GDBusConnection
3441 * @sender: (nullable): sender name to match on (unique or well-known name)
3442 * or %NULL to listen from all senders
3443 * @interface_name: (nullable): D-Bus interface name to match on or %NULL to
3444 * match on all interfaces
3445 * @member: (nullable): D-Bus signal name to match on or %NULL to match on
3447 * @object_path: (nullable): object path to match on or %NULL to match on
3449 * @arg0: (nullable): contents of first string argument to match on or %NULL
3450 * to match on all kinds of arguments
3451 * @flags: #GDBusSignalFlags describing how arg0 is used in subscribing to the
3453 * @callback: callback to invoke when there is a signal matching the requested data
3454 * @user_data: user data to pass to @callback
3455 * @user_data_free_func: (nullable): function to free @user_data with when
3456 * subscription is removed or %NULL
3458 * Subscribes to signals on @connection and invokes @callback with a whenever
3459 * the signal is received. Note that @callback will be invoked in the
3460 * [thread-default main context][g-main-context-push-thread-default]
3461 * of the thread you are calling this method from.
3463 * If @connection is not a message bus connection, @sender must be
3466 * If @sender is a well-known name note that @callback is invoked with
3467 * the unique name for the owner of @sender, not the well-known name
3468 * as one would expect. This is because the message bus rewrites the
3469 * name. As such, to avoid certain race conditions, users should be
3470 * tracking the name owner of the well-known name and use that when
3471 * processing the received signal.
3473 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3474 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3475 * interpreted as part of a namespace or path. The first argument
3476 * of a signal is matched against that part as specified by D-Bus.
3478 * If @user_data_free_func is non-%NULL, it will be called (in the
3479 * thread-default main context of the thread you are calling this
3480 * method from) at some point after @user_data is no longer
3481 * needed. (It is not guaranteed to be called synchronously when the
3482 * signal is unsubscribed from, and may be called after @connection
3483 * has been destroyed.)
3485 * As @callback is potentially invoked in a different thread from where it’s
3486 * emitted, it’s possible for this to happen after
3487 * g_dbus_connection_signal_unsubscribe() has been called in another thread.
3488 * Due to this, @user_data should have a strong reference which is freed with
3489 * @user_data_free_func, rather than pointing to data whose lifecycle is tied
3490 * to the signal subscription. For example, if a #GObject is used to store the
3491 * subscription ID from g_dbus_connection_signal_subscribe(), a strong reference
3492 * to that #GObject must be passed to @user_data, and g_object_unref() passed to
3493 * @user_data_free_func. You are responsible for breaking the resulting
3494 * reference count cycle by explicitly unsubscribing from the signal when
3495 * dropping the last external reference to the #GObject. Alternatively, a weak
3496 * reference may be used.
3498 * It is guaranteed that if you unsubscribe from a signal using
3499 * g_dbus_connection_signal_unsubscribe() from the same thread which made the
3500 * corresponding g_dbus_connection_signal_subscribe() call, @callback will not
3501 * be invoked after g_dbus_connection_signal_unsubscribe() returns.
3503 * The returned subscription identifier is an opaque value which is guaranteed
3506 * This function can never fail.
3508 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3513 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3514 const gchar *sender,
3515 const gchar *interface_name,
3516 const gchar *member,
3517 const gchar *object_path,
3519 GDBusSignalFlags flags,
3520 GDBusSignalCallback callback,
3522 GDestroyNotify user_data_free_func)
3525 SignalData *signal_data;
3526 SignalSubscriber *subscriber;
3527 GPtrArray *signal_data_array;
3528 const gchar *sender_unique_name;
3530 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3531 * an OOM condition. We might want to change that but that would involve making
3532 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3533 * handle that. And there's really no sensible way of handling this short of retrying
3534 * to add the match rule... and then there's the little thing that, hey, maybe there's
3535 * a reason the bus in an OOM condition.
3537 * Doable, but not really sure it's worth it...
3540 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3541 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3542 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3543 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3544 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3545 g_return_val_if_fail (callback != NULL, 0);
3546 g_return_val_if_fail (check_initialized (connection), 0);
3547 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3548 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3550 CONNECTION_LOCK (connection);
3552 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3553 * with a '-' character to prefix the rule (which will otherwise be
3556 * This allows us to hash the rule and do our lifecycle tracking in
3557 * the usual way, but the '-' prevents the match rule from ever
3558 * actually being send to the bus (either for add or remove).
3560 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3562 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3563 sender_unique_name = sender;
3565 sender_unique_name = "";
3567 subscriber = g_new0 (SignalSubscriber, 1);
3568 subscriber->ref_count = 1;
3569 subscriber->callback = callback;
3570 subscriber->user_data = user_data;
3571 subscriber->user_data_free_func = user_data_free_func;
3572 subscriber->id = (guint) g_atomic_int_add (&_global_subscriber_id, 1); /* TODO: overflow etc. */
3573 subscriber->context = g_main_context_ref_thread_default ();
3575 /* see if we've already have this rule */
3576 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3577 if (signal_data != NULL)
3579 g_ptr_array_add (signal_data->subscribers, subscriber);
3584 signal_data = g_new0 (SignalData, 1);
3585 signal_data->rule = rule;
3586 signal_data->sender = g_strdup (sender);
3587 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3588 signal_data->interface_name = g_strdup (interface_name);
3589 signal_data->member = g_strdup (member);
3590 signal_data->object_path = g_strdup (object_path);
3591 signal_data->arg0 = g_strdup (arg0);
3592 signal_data->flags = flags;
3593 signal_data->subscribers = g_ptr_array_new_with_free_func ((GDestroyNotify) signal_subscriber_unref);
3594 g_ptr_array_add (signal_data->subscribers, subscriber);
3596 g_hash_table_insert (connection->map_rule_to_signal_data,
3600 /* Add the match rule to the bus...
3602 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3603 * always send such messages to us.
3605 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3607 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3608 add_match_rule (connection, signal_data->rule);
3611 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3612 signal_data->sender_unique_name);
3613 if (signal_data_array == NULL)
3615 signal_data_array = g_ptr_array_new ();
3616 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3617 g_strdup (signal_data->sender_unique_name),
3620 g_ptr_array_add (signal_data_array, signal_data);
3623 g_hash_table_insert (connection->map_id_to_signal_data,
3624 GUINT_TO_POINTER (subscriber->id),
3627 CONNECTION_UNLOCK (connection);
3629 return subscriber->id;
3632 /* ---------------------------------------------------------------------------------------------------- */
3634 /* called in any thread */
3635 /* must hold lock when calling this (except if connection->finalizing is TRUE)
3636 * returns the number of removed subscribers */
3638 unsubscribe_id_internal (GDBusConnection *connection,
3639 guint subscription_id)
3641 SignalData *signal_data;
3642 GPtrArray *signal_data_array;
3644 guint n_removed = 0;
3646 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3647 GUINT_TO_POINTER (subscription_id));
3648 if (signal_data == NULL)
3650 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3654 for (n = 0; n < signal_data->subscribers->len; n++)
3656 SignalSubscriber *subscriber = signal_data->subscribers->pdata[n];
3658 if (subscriber->id != subscription_id)
3661 /* It’s OK to rearrange the array order using the ‘fast’ #GPtrArray
3662 * removal functions, since we’re going to exit the loop below anyway — we
3663 * never move on to the next element. Secondly, subscription IDs are
3664 * guaranteed to be unique. */
3665 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3666 GUINT_TO_POINTER (subscription_id)));
3668 g_ptr_array_remove_index_fast (signal_data->subscribers, n);
3670 if (signal_data->subscribers->len == 0)
3672 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3674 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3675 signal_data->sender_unique_name);
3676 g_warn_if_fail (signal_data_array != NULL);
3677 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3679 if (signal_data_array->len == 0)
3681 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3682 signal_data->sender_unique_name));
3685 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3686 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3687 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3688 !g_dbus_connection_is_closed (connection) &&
3689 !connection->finalizing)
3691 /* The check for g_dbus_connection_is_closed() means that
3692 * sending the RemoveMatch message can't fail with
3693 * G_IO_ERROR_CLOSED, because we're holding the lock,
3694 * so on_worker_closed() can't happen between the check we just
3695 * did, and releasing the lock later.
3697 remove_match_rule (connection, signal_data->rule);
3700 signal_data_free (signal_data);
3706 g_assert_not_reached ();
3713 * g_dbus_connection_signal_unsubscribe:
3714 * @connection: a #GDBusConnection
3715 * @subscription_id: a subscription id obtained from
3716 * g_dbus_connection_signal_subscribe()
3718 * Unsubscribes from signals.
3720 * Note that there may still be D-Bus traffic to process (relating to this
3721 * signal subscription) in the current thread-default #GMainContext after this
3722 * function has returned. You should continue to iterate the #GMainContext
3723 * until the #GDestroyNotify function passed to
3724 * g_dbus_connection_signal_subscribe() is called, in order to avoid memory
3725 * leaks through callbacks queued on the #GMainContext after it’s stopped being
3727 * Alternatively, any idle source with a priority lower than %G_PRIORITY_DEFAULT
3728 * that was scheduled after unsubscription, also indicates that all resources
3729 * of this subscription are released.
3734 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3735 guint subscription_id)
3737 guint n_subscribers_removed G_GNUC_UNUSED /* when compiling with G_DISABLE_ASSERT */;
3739 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3740 g_return_if_fail (check_initialized (connection));
3742 CONNECTION_LOCK (connection);
3743 n_subscribers_removed = unsubscribe_id_internal (connection, subscription_id);
3744 CONNECTION_UNLOCK (connection);
3747 g_assert (n_subscribers_removed == 0 || n_subscribers_removed == 1);
3750 /* ---------------------------------------------------------------------------------------------------- */
3754 SignalSubscriber *subscriber; /* (owned) */
3755 GDBusMessage *message;
3756 GDBusConnection *connection;
3757 const gchar *sender; /* (nullable) for peer-to-peer connections */
3759 const gchar *interface;
3760 const gchar *member;
3763 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3767 emit_signal_instance_in_idle_cb (gpointer data)
3769 SignalInstance *signal_instance = data;
3770 GVariant *parameters;
3771 gboolean has_subscription;
3773 parameters = g_dbus_message_get_body (signal_instance->message);
3774 if (parameters == NULL)
3776 parameters = g_variant_new ("()");
3777 g_variant_ref_sink (parameters);
3781 g_variant_ref_sink (parameters);
3785 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3786 signal_instance->subscriber->id,
3787 signal_instance->sender,
3788 signal_instance->path,
3789 signal_instance->interface,
3790 signal_instance->member,
3791 g_variant_print (parameters, TRUE));
3794 /* Careful here, don't do the callback if we no longer has the subscription */
3795 CONNECTION_LOCK (signal_instance->connection);
3796 has_subscription = FALSE;
3797 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3798 GUINT_TO_POINTER (signal_instance->subscriber->id)) != NULL)
3799 has_subscription = TRUE;
3800 CONNECTION_UNLOCK (signal_instance->connection);
3802 if (has_subscription)
3803 signal_instance->subscriber->callback (signal_instance->connection,
3804 signal_instance->sender,
3805 signal_instance->path,
3806 signal_instance->interface,
3807 signal_instance->member,
3809 signal_instance->subscriber->user_data);
3811 g_variant_unref (parameters);
3817 signal_instance_free (SignalInstance *signal_instance)
3819 g_object_unref (signal_instance->message);
3820 g_object_unref (signal_instance->connection);
3821 signal_subscriber_unref (signal_instance->subscriber);
3822 g_free (signal_instance);
3826 namespace_rule_matches (const gchar *namespace,
3832 len_namespace = strlen (namespace);
3833 len_name = strlen (name);
3835 if (len_name < len_namespace)
3838 if (memcmp (namespace, name, len_namespace) != 0)
3841 return len_namespace == len_name || name[len_namespace] == '.';
3845 path_rule_matches (const gchar *path_a,
3846 const gchar *path_b)
3850 len_a = strlen (path_a);
3851 len_b = strlen (path_b);
3853 if (len_a < len_b && (len_a == 0 || path_a[len_a - 1] != '/'))
3856 if (len_b < len_a && (len_b == 0 || path_b[len_b - 1] != '/'))
3859 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3862 /* called in GDBusWorker thread WITH lock held
3864 * @sender is (nullable) for peer-to-peer connections */
3866 schedule_callbacks (GDBusConnection *connection,
3867 GPtrArray *signal_data_array,
3868 GDBusMessage *message,
3869 const gchar *sender)
3872 const gchar *interface;
3873 const gchar *member;
3882 interface = g_dbus_message_get_interface (message);
3883 member = g_dbus_message_get_member (message);
3884 path = g_dbus_message_get_path (message);
3885 arg0 = g_dbus_message_get_arg0 (message);
3888 g_print ("In schedule_callbacks:\n"
3890 " interface = '%s'\n"
3901 /* TODO: if this is slow, then we can change signal_data_array into
3902 * map_object_path_to_signal_data_array or something.
3904 for (n = 0; n < signal_data_array->len; n++)
3906 SignalData *signal_data = signal_data_array->pdata[n];
3908 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3911 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3914 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3917 if (signal_data->arg0 != NULL)
3922 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3924 if (!namespace_rule_matches (signal_data->arg0, arg0))
3927 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3929 if (!path_rule_matches (signal_data->arg0, arg0))
3932 else if (!g_str_equal (signal_data->arg0, arg0))
3936 for (m = 0; m < signal_data->subscribers->len; m++)
3938 SignalSubscriber *subscriber = signal_data->subscribers->pdata[m];
3939 GSource *idle_source;
3940 SignalInstance *signal_instance;
3942 signal_instance = g_new0 (SignalInstance, 1);
3943 signal_instance->subscriber = signal_subscriber_ref (subscriber);
3944 signal_instance->message = g_object_ref (message);
3945 signal_instance->connection = g_object_ref (connection);
3946 signal_instance->sender = sender;
3947 signal_instance->path = path;
3948 signal_instance->interface = interface;
3949 signal_instance->member = member;
3951 idle_source = g_idle_source_new ();
3952 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3953 g_source_set_callback (idle_source,
3954 emit_signal_instance_in_idle_cb,
3956 (GDestroyNotify) signal_instance_free);
3957 g_source_set_static_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3958 g_source_attach (idle_source, subscriber->context);
3959 g_source_unref (idle_source);
3964 /* called in GDBusWorker thread with lock held */
3966 distribute_signals (GDBusConnection *connection,
3967 GDBusMessage *message)
3969 GPtrArray *signal_data_array;
3970 const gchar *sender;
3972 sender = g_dbus_message_get_sender (message);
3974 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3976 _g_dbus_debug_print_lock ();
3977 g_print ("========================================================================\n"
3978 "GDBus-debug:Signal:\n"
3979 " <<<< RECEIVED SIGNAL %s.%s\n"
3981 " sent by name %s\n",
3982 g_dbus_message_get_interface (message),
3983 g_dbus_message_get_member (message),
3984 g_dbus_message_get_path (message),
3985 sender != NULL ? sender : "(none)");
3986 _g_dbus_debug_print_unlock ();
3989 /* collect subscribers that match on sender */
3992 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3993 if (signal_data_array != NULL)
3994 schedule_callbacks (connection, signal_data_array, message, sender);
3997 /* collect subscribers not matching on sender */
3998 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3999 if (signal_data_array != NULL)
4000 schedule_callbacks (connection, signal_data_array, message, sender);
4003 /* ---------------------------------------------------------------------------------------------------- */
4005 /* only called from finalize(), removes all subscriptions */
4007 purge_all_signal_subscriptions (GDBusConnection *connection)
4009 GHashTableIter iter;
4014 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4015 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4016 while (g_hash_table_iter_next (&iter, &key, NULL))
4018 guint subscription_id = GPOINTER_TO_UINT (key);
4019 g_array_append_val (ids, subscription_id);
4022 for (n = 0; n < ids->len; n++)
4024 guint subscription_id = g_array_index (ids, guint, n);
4025 unsubscribe_id_internal (connection, subscription_id);
4027 g_array_free (ids, TRUE);
4030 /* ---------------------------------------------------------------------------------------------------- */
4032 static GDBusInterfaceVTable *
4033 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4035 /* Don't waste memory by copying padding - remember to update this
4036 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4038 return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
4042 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4047 /* ---------------------------------------------------------------------------------------------------- */
4049 static GDBusSubtreeVTable *
4050 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4052 /* Don't waste memory by copying padding - remember to update this
4053 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4055 return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
4059 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4064 /* ---------------------------------------------------------------------------------------------------- */
4066 struct ExportedObject
4069 GDBusConnection *connection;
4071 /* maps gchar* -> ExportedInterface* */
4072 GHashTable *map_if_name_to_ei;
4075 /* only called with lock held */
4077 exported_object_free (ExportedObject *eo)
4079 g_free (eo->object_path);
4080 g_hash_table_unref (eo->map_if_name_to_ei);
4089 gchar *interface_name;
4090 GDBusInterfaceVTable *vtable;
4091 GDBusInterfaceInfo *interface_info;
4093 GMainContext *context;
4095 GDestroyNotify user_data_free_func;
4096 } ExportedInterface;
4098 /* called with lock held */
4100 exported_interface_free (ExportedInterface *ei)
4102 g_dbus_interface_info_cache_release (ei->interface_info);
4103 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4105 call_destroy_notify (ei->context,
4106 ei->user_data_free_func,
4109 g_main_context_unref (ei->context);
4111 g_free (ei->interface_name);
4112 _g_dbus_interface_vtable_free (ei->vtable);
4116 /* ---------------------------------------------------------------------------------------------------- */
4118 /* Convenience function to check if @registration_id (if not zero) or
4119 * @subtree_registration_id (if not zero) has been unregistered. If
4120 * so, returns %TRUE.
4122 * May be called by any thread. Caller must *not* hold lock.
4125 has_object_been_unregistered (GDBusConnection *connection,
4126 guint registration_id,
4127 guint subtree_registration_id)
4131 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4135 CONNECTION_LOCK (connection);
4136 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4137 GUINT_TO_POINTER (registration_id)) == NULL)
4141 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4142 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4146 CONNECTION_UNLOCK (connection);
4151 /* ---------------------------------------------------------------------------------------------------- */
4155 GDBusConnection *connection;
4156 GDBusMessage *message;
4158 const gchar *property_name;
4159 const GDBusInterfaceVTable *vtable;
4160 GDBusInterfaceInfo *interface_info;
4161 const GDBusPropertyInfo *property_info;
4162 guint registration_id;
4163 guint subtree_registration_id;
4167 property_data_free (PropertyData *data)
4169 g_object_unref (data->connection);
4170 g_object_unref (data->message);
4174 /* called in thread where object was registered - no locks held */
4176 invoke_get_property_in_idle_cb (gpointer _data)
4178 PropertyData *data = _data;
4181 GDBusMessage *reply;
4183 if (has_object_been_unregistered (data->connection,
4184 data->registration_id,
4185 data->subtree_registration_id))
4187 reply = g_dbus_message_new_method_error (data->message,
4188 "org.freedesktop.DBus.Error.UnknownMethod",
4189 _("No such interface “org.freedesktop.DBus.Properties” on object at path %s"),
4190 g_dbus_message_get_path (data->message));
4191 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4192 g_object_unref (reply);
4197 value = data->vtable->get_property (data->connection,
4198 g_dbus_message_get_sender (data->message),
4199 g_dbus_message_get_path (data->message),
4200 data->interface_info->name,
4201 data->property_name,
4208 g_assert_no_error (error);
4210 g_variant_take_ref (value);
4211 reply = g_dbus_message_new_method_reply (data->message);
4212 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4213 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4214 g_variant_unref (value);
4215 g_object_unref (reply);
4219 gchar *dbus_error_name;
4220 g_assert (error != NULL);
4221 dbus_error_name = g_dbus_error_encode_gerror (error);
4222 reply = g_dbus_message_new_method_error_literal (data->message,
4225 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4226 g_free (dbus_error_name);
4227 g_error_free (error);
4228 g_object_unref (reply);
4235 /* called in thread where object was registered - no locks held */
4237 invoke_set_property_in_idle_cb (gpointer _data)
4239 PropertyData *data = _data;
4241 GDBusMessage *reply;
4247 g_variant_get (g_dbus_message_get_body (data->message),
4253 if (!data->vtable->set_property (data->connection,
4254 g_dbus_message_get_sender (data->message),
4255 g_dbus_message_get_path (data->message),
4256 data->interface_info->name,
4257 data->property_name,
4262 gchar *dbus_error_name;
4263 g_assert (error != NULL);
4264 dbus_error_name = g_dbus_error_encode_gerror (error);
4265 reply = g_dbus_message_new_method_error_literal (data->message,
4268 g_free (dbus_error_name);
4269 g_error_free (error);
4273 reply = g_dbus_message_new_method_reply (data->message);
4276 g_assert (reply != NULL);
4277 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4278 g_object_unref (reply);
4279 g_variant_unref (value);
4284 /* called in any thread with connection's lock held */
4286 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4287 GDBusMessage *message,
4288 guint registration_id,
4289 guint subtree_registration_id,
4291 GDBusInterfaceInfo *interface_info,
4292 const GDBusInterfaceVTable *vtable,
4293 GMainContext *main_context,
4297 const char *interface_name;
4298 const char *property_name;
4299 const GDBusPropertyInfo *property_info;
4300 GSource *idle_source;
4301 PropertyData *property_data;
4302 GDBusMessage *reply;
4307 g_variant_get (g_dbus_message_get_body (message),
4312 g_variant_get (g_dbus_message_get_body (message),
4321 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4323 property_info = NULL;
4325 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4326 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4327 if (property_info == NULL)
4329 reply = g_dbus_message_new_method_error (message,
4330 "org.freedesktop.DBus.Error.InvalidArgs",
4331 _("No such property “%s”"),
4333 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4334 g_object_unref (reply);
4339 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4341 reply = g_dbus_message_new_method_error (message,
4342 "org.freedesktop.DBus.Error.InvalidArgs",
4343 _("Property “%s” is not readable"),
4345 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4346 g_object_unref (reply);
4350 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4352 reply = g_dbus_message_new_method_error (message,
4353 "org.freedesktop.DBus.Error.InvalidArgs",
4354 _("Property “%s” is not writable"),
4356 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4357 g_object_unref (reply);
4366 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4367 * of the given value is wrong
4369 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4370 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4372 reply = g_dbus_message_new_method_error (message,
4373 "org.freedesktop.DBus.Error.InvalidArgs",
4374 _("Error setting property “%s”: Expected type “%s” but got “%s”"),
4375 property_name, property_info->signature,
4376 g_variant_get_type_string (value));
4377 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4378 g_variant_unref (value);
4379 g_object_unref (reply);
4384 g_variant_unref (value);
4387 /* If the vtable pointer for get_property() resp. set_property() is
4388 * NULL then dispatch the call via the method_call() handler.
4392 if (vtable->get_property == NULL)
4394 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4395 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4396 vtable, main_context, user_data);
4403 if (vtable->set_property == NULL)
4405 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4406 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4407 vtable, main_context, user_data);
4413 /* ok, got the property info - call user code in an idle handler */
4414 property_data = g_new0 (PropertyData, 1);
4415 property_data->connection = g_object_ref (connection);
4416 property_data->message = g_object_ref (message);
4417 property_data->user_data = user_data;
4418 property_data->property_name = property_name;
4419 property_data->vtable = vtable;
4420 property_data->interface_info = interface_info;
4421 property_data->property_info = property_info;
4422 property_data->registration_id = registration_id;
4423 property_data->subtree_registration_id = subtree_registration_id;
4425 idle_source = g_idle_source_new ();
4426 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4427 g_source_set_callback (idle_source,
4428 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4430 (GDestroyNotify) property_data_free);
4432 g_source_set_static_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4434 g_source_set_static_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4435 g_source_attach (idle_source, main_context);
4436 g_source_unref (idle_source);
4444 /* called in GDBusWorker thread with connection's lock held */
4446 handle_getset_property (GDBusConnection *connection,
4448 GDBusMessage *message,
4451 ExportedInterface *ei;
4453 const char *interface_name;
4454 const char *property_name;
4459 g_variant_get (g_dbus_message_get_body (message),
4464 g_variant_get (g_dbus_message_get_body (message),
4470 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4471 * no such interface registered
4473 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4476 GDBusMessage *reply;
4477 reply = g_dbus_message_new_method_error (message,
4478 "org.freedesktop.DBus.Error.InvalidArgs",
4479 _("No such interface “%s”"),
4481 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4482 g_object_unref (reply);
4487 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4500 /* ---------------------------------------------------------------------------------------------------- */
4504 GDBusConnection *connection;
4505 GDBusMessage *message;
4507 const GDBusInterfaceVTable *vtable;
4508 GDBusInterfaceInfo *interface_info;
4509 guint registration_id;
4510 guint subtree_registration_id;
4511 } PropertyGetAllData;
4514 property_get_all_data_free (PropertyData *data)
4516 g_object_unref (data->connection);
4517 g_object_unref (data->message);
4521 /* called in thread where object was registered - no locks held */
4523 invoke_get_all_properties_in_idle_cb (gpointer _data)
4525 PropertyGetAllData *data = _data;
4526 GVariantBuilder builder;
4527 GDBusMessage *reply;
4530 if (has_object_been_unregistered (data->connection,
4531 data->registration_id,
4532 data->subtree_registration_id))
4534 reply = g_dbus_message_new_method_error (data->message,
4535 "org.freedesktop.DBus.Error.UnknownMethod",
4536 _("No such interface “org.freedesktop.DBus.Properties” on object at path %s"),
4537 g_dbus_message_get_path (data->message));
4538 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4539 g_object_unref (reply);
4543 /* TODO: Right now we never fail this call - we just omit values if
4544 * a get_property() call is failing.
4546 * We could fail the whole call if just a single get_property() call
4547 * returns an error. We need clarification in the D-Bus spec about this.
4549 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4550 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4551 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4553 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4556 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4559 value = data->vtable->get_property (data->connection,
4560 g_dbus_message_get_sender (data->message),
4561 g_dbus_message_get_path (data->message),
4562 data->interface_info->name,
4563 property_info->name,
4570 g_variant_take_ref (value);
4571 g_variant_builder_add (&builder,
4573 property_info->name,
4575 g_variant_unref (value);
4577 g_variant_builder_close (&builder);
4579 reply = g_dbus_message_new_method_reply (data->message);
4580 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4581 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4582 g_object_unref (reply);
4589 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4593 if (!interface_info->properties)
4596 for (i = 0; interface_info->properties[i]; i++)
4597 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4603 /* called in any thread with connection's lock held */
4605 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4606 GDBusMessage *message,
4607 guint registration_id,
4608 guint subtree_registration_id,
4609 GDBusInterfaceInfo *interface_info,
4610 const GDBusInterfaceVTable *vtable,
4611 GMainContext *main_context,
4615 GSource *idle_source;
4616 PropertyGetAllData *property_get_all_data;
4623 /* If the vtable pointer for get_property() is NULL but we have a
4624 * non-zero number of readable properties, then dispatch the call via
4625 * the method_call() handler.
4627 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4629 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4630 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4631 vtable, main_context, user_data);
4636 /* ok, got the property info - call user in an idle handler */
4637 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4638 property_get_all_data->connection = g_object_ref (connection);
4639 property_get_all_data->message = g_object_ref (message);
4640 property_get_all_data->user_data = user_data;
4641 property_get_all_data->vtable = vtable;
4642 property_get_all_data->interface_info = interface_info;
4643 property_get_all_data->registration_id = registration_id;
4644 property_get_all_data->subtree_registration_id = subtree_registration_id;
4646 idle_source = g_idle_source_new ();
4647 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4648 g_source_set_callback (idle_source,
4649 invoke_get_all_properties_in_idle_cb,
4650 property_get_all_data,
4651 (GDestroyNotify) property_get_all_data_free);
4652 g_source_set_static_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4653 g_source_attach (idle_source, main_context);
4654 g_source_unref (idle_source);
4662 /* called in GDBusWorker thread with connection's lock held */
4664 handle_get_all_properties (GDBusConnection *connection,
4666 GDBusMessage *message)
4668 ExportedInterface *ei;
4670 const char *interface_name;
4674 g_variant_get (g_dbus_message_get_body (message),
4678 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4679 * no such interface registered
4681 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4684 GDBusMessage *reply;
4685 reply = g_dbus_message_new_method_error (message,
4686 "org.freedesktop.DBus.Error.InvalidArgs",
4687 _("No such interface “%s”"),
4689 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4690 g_object_unref (reply);
4695 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4707 /* ---------------------------------------------------------------------------------------------------- */
4709 static const gchar introspect_header[] =
4710 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4711 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4712 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4715 static const gchar introspect_tail[] =
4718 static const gchar introspect_properties_interface[] =
4719 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4720 " <method name=\"Get\">\n"
4721 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4722 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4723 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4725 " <method name=\"GetAll\">\n"
4726 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4727 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4729 " <method name=\"Set\">\n"
4730 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4731 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4732 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4734 " <signal name=\"PropertiesChanged\">\n"
4735 " <arg type=\"s\" name=\"interface_name\"/>\n"
4736 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4737 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4741 static const gchar introspect_introspectable_interface[] =
4742 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4743 " <method name=\"Introspect\">\n"
4744 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4747 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4748 " <method name=\"Ping\"/>\n"
4749 " <method name=\"GetMachineId\">\n"
4750 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4755 introspect_append_header (GString *s)
4757 g_string_append (s, introspect_header);
4761 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4763 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4769 begin = object_path + path_len;
4770 end = strchr (begin, '/');
4772 s = g_strndup (begin, end - begin);
4774 s = g_strdup (begin);
4776 if (!g_hash_table_contains (set, s))
4777 g_hash_table_add (set, s);
4783 /* TODO: we want a nicer public interface for this */
4784 /* called in any thread with connection's lock held */
4786 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4791 GHashTableIter hash_iter;
4792 const gchar *object_path;
4798 CONNECTION_ENSURE_LOCK (connection);
4800 path_len = strlen (path);
4804 set = g_hash_table_new (g_str_hash, g_str_equal);
4806 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4807 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4808 maybe_add_path (path, path_len, object_path, set);
4810 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4811 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4812 maybe_add_path (path, path_len, object_path, set);
4814 p = g_ptr_array_new ();
4815 keys = g_hash_table_get_keys (set);
4816 for (l = keys; l != NULL; l = l->next)
4817 g_ptr_array_add (p, l->data);
4818 g_hash_table_unref (set);
4821 g_ptr_array_add (p, NULL);
4822 ret = (gchar **) g_ptr_array_free (p, FALSE);
4826 /* called in any thread with connection's lock not held */
4828 g_dbus_connection_list_registered (GDBusConnection *connection,
4832 CONNECTION_LOCK (connection);
4833 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4834 CONNECTION_UNLOCK (connection);
4838 /* called in GDBusWorker thread with connection's lock held */
4840 handle_introspect (GDBusConnection *connection,
4842 GDBusMessage *message)
4846 GDBusMessage *reply;
4847 GHashTableIter hash_iter;
4848 ExportedInterface *ei;
4851 /* first the header with the standard interfaces */
4852 s = g_string_sized_new (sizeof (introspect_header) +
4853 sizeof (introspect_properties_interface) +
4854 sizeof (introspect_introspectable_interface) +
4855 sizeof (introspect_tail));
4856 introspect_append_header (s);
4857 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4858 "org.freedesktop.DBus.Properties"))
4859 g_string_append (s, introspect_properties_interface);
4861 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4862 "org.freedesktop.DBus.Introspectable"))
4863 g_string_append (s, introspect_introspectable_interface);
4865 /* then include the registered interfaces */
4866 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4867 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4868 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4870 /* finally include nodes registered below us */
4871 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4872 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4873 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4874 g_strfreev (registered);
4875 g_string_append (s, introspect_tail);
4877 reply = g_dbus_message_new_method_reply (message);
4878 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4879 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4880 g_object_unref (reply);
4881 g_string_free (s, TRUE);
4886 /* called in thread where object was registered - no locks held */
4888 call_in_idle_cb (gpointer user_data)
4890 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4891 GDBusInterfaceVTable *vtable;
4892 guint registration_id;
4893 guint subtree_registration_id;
4895 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4896 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4898 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4900 subtree_registration_id))
4902 GDBusMessage *reply;
4903 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4904 "org.freedesktop.DBus.Error.UnknownMethod",
4905 _("No such interface “%s” on object at path %s"),
4906 g_dbus_method_invocation_get_interface_name (invocation),
4907 g_dbus_method_invocation_get_object_path (invocation));
4908 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4909 g_object_unref (reply);
4913 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4914 g_assert (vtable != NULL && vtable->method_call != NULL);
4916 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4917 g_dbus_method_invocation_get_sender (invocation),
4918 g_dbus_method_invocation_get_object_path (invocation),
4919 g_dbus_method_invocation_get_interface_name (invocation),
4920 g_dbus_method_invocation_get_method_name (invocation),
4921 g_dbus_method_invocation_get_parameters (invocation),
4922 g_object_ref (invocation),
4923 g_dbus_method_invocation_get_user_data (invocation));
4929 /* called in GDBusWorker thread with connection's lock held */
4931 schedule_method_call (GDBusConnection *connection,
4932 GDBusMessage *message,
4933 guint registration_id,
4934 guint subtree_registration_id,
4935 const GDBusInterfaceInfo *interface_info,
4936 const GDBusMethodInfo *method_info,
4937 const GDBusPropertyInfo *property_info,
4938 GVariant *parameters,
4939 const GDBusInterfaceVTable *vtable,
4940 GMainContext *main_context,
4943 GDBusMethodInvocation *invocation;
4944 GSource *idle_source;
4946 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4947 g_dbus_message_get_path (message),
4948 g_dbus_message_get_interface (message),
4949 g_dbus_message_get_member (message),
4957 /* TODO: would be nicer with a real MethodData like we already
4958 * have PropertyData and PropertyGetAllData... */
4959 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4960 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4961 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4963 idle_source = g_idle_source_new ();
4964 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4965 g_source_set_callback (idle_source,
4969 g_source_set_static_name (idle_source, "[gio, " __FILE__ "] call_in_idle_cb");
4970 g_source_attach (idle_source, main_context);
4971 g_source_unref (idle_source);
4974 /* called in GDBusWorker thread with connection's lock held */
4976 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4977 GDBusMessage *message,
4978 guint registration_id,
4979 guint subtree_registration_id,
4980 GDBusInterfaceInfo *interface_info,
4981 const GDBusInterfaceVTable *vtable,
4982 GMainContext *main_context,
4985 GDBusMethodInfo *method_info;
4986 GDBusMessage *reply;
4987 GVariant *parameters;
4989 GVariantType *in_type;
4993 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4994 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4996 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4997 * error to the caller
4999 if (method_info == NULL)
5001 reply = g_dbus_message_new_method_error (message,
5002 "org.freedesktop.DBus.Error.UnknownMethod",
5003 _("No such method “%s”"),
5004 g_dbus_message_get_member (message));
5005 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5006 g_object_unref (reply);
5011 parameters = g_dbus_message_get_body (message);
5012 if (parameters == NULL)
5014 parameters = g_variant_new ("()");
5015 g_variant_ref_sink (parameters);
5019 g_variant_ref (parameters);
5022 /* Check that the incoming args are of the right type - if they are not, return
5023 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5025 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5026 if (!g_variant_is_of_type (parameters, in_type))
5030 type_string = g_variant_type_dup_string (in_type);
5032 reply = g_dbus_message_new_method_error (message,
5033 "org.freedesktop.DBus.Error.InvalidArgs",
5034 _("Type of message, “%s”, does not match expected type “%s”"),
5035 g_variant_get_type_string (parameters),
5037 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5038 g_variant_type_free (in_type);
5039 g_variant_unref (parameters);
5040 g_object_unref (reply);
5041 g_free (type_string);
5045 g_variant_type_free (in_type);
5047 /* schedule the call in idle */
5048 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5049 interface_info, method_info, NULL, parameters,
5050 vtable, main_context, user_data);
5051 g_variant_unref (parameters);
5058 /* ---------------------------------------------------------------------------------------------------- */
5060 /* called in GDBusWorker thread with connection's lock held */
5062 obj_message_func (GDBusConnection *connection,
5064 GDBusMessage *message,
5065 gboolean *object_found)
5067 const gchar *interface_name;
5068 const gchar *member;
5069 const gchar *signature;
5074 interface_name = g_dbus_message_get_interface (message);
5075 member = g_dbus_message_get_member (message);
5076 signature = g_dbus_message_get_signature (message);
5078 /* see if we have an interface for handling this call */
5079 if (interface_name != NULL)
5081 ExportedInterface *ei;
5082 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5085 /* we do - invoke the handler in idle in the right thread */
5087 /* handle no vtable or handler being present */
5088 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5091 handled = validate_and_maybe_schedule_method_call (connection,
5103 *object_found = TRUE;
5107 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5108 g_strcmp0 (member, "Introspect") == 0 &&
5109 g_strcmp0 (signature, "") == 0)
5111 handled = handle_introspect (connection, eo, message);
5114 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5115 g_strcmp0 (member, "Get") == 0 &&
5116 g_strcmp0 (signature, "ss") == 0)
5118 handled = handle_getset_property (connection, eo, message, TRUE);
5121 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5122 g_strcmp0 (member, "Set") == 0 &&
5123 g_strcmp0 (signature, "ssv") == 0)
5125 handled = handle_getset_property (connection, eo, message, FALSE);
5128 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5129 g_strcmp0 (member, "GetAll") == 0 &&
5130 g_strcmp0 (signature, "s") == 0)
5132 handled = handle_get_all_properties (connection, eo, message);
5141 * g_dbus_connection_register_object:
5142 * @connection: a #GDBusConnection
5143 * @object_path: the object path to register at
5144 * @interface_info: introspection data for the interface
5145 * @vtable: (nullable): a #GDBusInterfaceVTable to call into or %NULL
5146 * @user_data: (nullable): data to pass to functions in @vtable
5147 * @user_data_free_func: function to call when the object path is unregistered
5148 * @error: return location for error or %NULL
5150 * Registers callbacks for exported objects at @object_path with the
5151 * D-Bus interface that is described in @interface_info.
5153 * Calls to functions in @vtable (and @user_data_free_func) will happen
5155 * [thread-default main context][g-main-context-push-thread-default]
5156 * of the thread you are calling this method from.
5158 * Note that all #GVariant values passed to functions in @vtable will match
5159 * the signature given in @interface_info - if a remote caller passes
5160 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5161 * is returned to the remote caller.
5163 * Additionally, if the remote caller attempts to invoke methods or
5164 * access properties not mentioned in @interface_info the
5165 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5166 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5167 * are returned to the caller.
5169 * It is considered a programming error if the
5170 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5171 * #GVariant of incorrect type.
5173 * If an existing callback is already registered at @object_path and
5174 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5176 * GDBus automatically implements the standard D-Bus interfaces
5177 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5178 * and org.freedesktop.Peer, so you don't have to implement those for the
5179 * objects you export. You can implement org.freedesktop.DBus.Properties
5180 * yourself, e.g. to handle getting and setting of properties asynchronously.
5182 * Note that the reference count on @interface_info will be
5183 * incremented by 1 (unless allocated statically, e.g. if the
5184 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5185 * as the object is exported. Also note that @vtable will be copied.
5187 * See this [server][gdbus-server] for an example of how to use this method.
5189 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5190 * that can be used with g_dbus_connection_unregister_object()
5195 g_dbus_connection_register_object (GDBusConnection *connection,
5196 const gchar *object_path,
5197 GDBusInterfaceInfo *interface_info,
5198 const GDBusInterfaceVTable *vtable,
5200 GDestroyNotify user_data_free_func,
5204 ExportedInterface *ei;
5207 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5208 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5209 g_return_val_if_fail (interface_info != NULL, 0);
5210 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5211 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5212 g_return_val_if_fail (check_initialized (connection), 0);
5216 CONNECTION_LOCK (connection);
5218 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5221 eo = g_new0 (ExportedObject, 1);
5222 eo->object_path = g_strdup (object_path);
5223 eo->connection = connection;
5224 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5227 (GDestroyNotify) exported_interface_free);
5228 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5231 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5237 _("An object is already exported for the interface %s at %s"),
5238 interface_info->name,
5243 ei = g_new0 (ExportedInterface, 1);
5244 ei->id = (guint) g_atomic_int_add (&_global_registration_id, 1); /* TODO: overflow etc. */
5246 ei->user_data = user_data;
5247 ei->user_data_free_func = user_data_free_func;
5248 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5249 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5250 g_dbus_interface_info_cache_build (ei->interface_info);
5251 ei->interface_name = g_strdup (interface_info->name);
5252 ei->context = g_main_context_ref_thread_default ();
5254 g_hash_table_insert (eo->map_if_name_to_ei,
5255 (gpointer) ei->interface_name,
5257 g_hash_table_insert (connection->map_id_to_ei,
5258 GUINT_TO_POINTER (ei->id),
5264 CONNECTION_UNLOCK (connection);
5270 * g_dbus_connection_unregister_object:
5271 * @connection: a #GDBusConnection
5272 * @registration_id: a registration id obtained from
5273 * g_dbus_connection_register_object()
5275 * Unregisters an object.
5277 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5282 g_dbus_connection_unregister_object (GDBusConnection *connection,
5283 guint registration_id)
5285 ExportedInterface *ei;
5289 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5290 g_return_val_if_fail (check_initialized (connection), FALSE);
5294 CONNECTION_LOCK (connection);
5296 ei = g_hash_table_lookup (connection->map_id_to_ei,
5297 GUINT_TO_POINTER (registration_id));
5303 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5304 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5305 /* unregister object path if we have no more exported interfaces */
5306 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5307 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5313 CONNECTION_UNLOCK (connection);
5319 GClosure *method_call_closure;
5320 GClosure *get_property_closure;
5321 GClosure *set_property_closure;
5322 } RegisterObjectData;
5324 static RegisterObjectData *
5325 register_object_data_new (GClosure *method_call_closure,
5326 GClosure *get_property_closure,
5327 GClosure *set_property_closure)
5329 RegisterObjectData *data;
5331 data = g_new0 (RegisterObjectData, 1);
5333 if (method_call_closure != NULL)
5335 data->method_call_closure = g_closure_ref (method_call_closure);
5336 g_closure_sink (method_call_closure);
5337 if (G_CLOSURE_NEEDS_MARSHAL (method_call_closure))
5338 g_closure_set_marshal (method_call_closure, g_cclosure_marshal_generic);
5341 if (get_property_closure != NULL)
5343 data->get_property_closure = g_closure_ref (get_property_closure);
5344 g_closure_sink (get_property_closure);
5345 if (G_CLOSURE_NEEDS_MARSHAL (get_property_closure))
5346 g_closure_set_marshal (get_property_closure, g_cclosure_marshal_generic);
5349 if (set_property_closure != NULL)
5351 data->set_property_closure = g_closure_ref (set_property_closure);
5352 g_closure_sink (set_property_closure);
5353 if (G_CLOSURE_NEEDS_MARSHAL (set_property_closure))
5354 g_closure_set_marshal (set_property_closure, g_cclosure_marshal_generic);
5361 register_object_free_func (gpointer user_data)
5363 RegisterObjectData *data = user_data;
5365 g_clear_pointer (&data->method_call_closure, g_closure_unref);
5366 g_clear_pointer (&data->get_property_closure, g_closure_unref);
5367 g_clear_pointer (&data->set_property_closure, g_closure_unref);
5373 register_with_closures_on_method_call (GDBusConnection *connection,
5374 const gchar *sender,
5375 const gchar *object_path,
5376 const gchar *interface_name,
5377 const gchar *method_name,
5378 GVariant *parameters,
5379 GDBusMethodInvocation *invocation,
5382 RegisterObjectData *data = user_data;
5383 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5385 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5386 g_value_set_object (¶ms[0], connection);
5388 g_value_init (¶ms[1], G_TYPE_STRING);
5389 g_value_set_string (¶ms[1], sender);
5391 g_value_init (¶ms[2], G_TYPE_STRING);
5392 g_value_set_string (¶ms[2], object_path);
5394 g_value_init (¶ms[3], G_TYPE_STRING);
5395 g_value_set_string (¶ms[3], interface_name);
5397 g_value_init (¶ms[4], G_TYPE_STRING);
5398 g_value_set_string (¶ms[4], method_name);
5400 g_value_init (¶ms[5], G_TYPE_VARIANT);
5401 g_value_set_variant (¶ms[5], parameters);
5403 g_value_init (¶ms[6], G_TYPE_DBUS_METHOD_INVOCATION);
5404 g_value_set_object (¶ms[6], invocation);
5406 g_closure_invoke (data->method_call_closure, NULL, G_N_ELEMENTS (params), params, NULL);
5408 g_value_unset (params + 0);
5409 g_value_unset (params + 1);
5410 g_value_unset (params + 2);
5411 g_value_unset (params + 3);
5412 g_value_unset (params + 4);
5413 g_value_unset (params + 5);
5414 g_value_unset (params + 6);
5418 register_with_closures_on_get_property (GDBusConnection *connection,
5419 const gchar *sender,
5420 const gchar *object_path,
5421 const gchar *interface_name,
5422 const gchar *property_name,
5426 RegisterObjectData *data = user_data;
5427 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5428 GValue result_value = G_VALUE_INIT;
5431 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5432 g_value_set_object (¶ms[0], connection);
5434 g_value_init (¶ms[1], G_TYPE_STRING);
5435 g_value_set_string (¶ms[1], sender);
5437 g_value_init (¶ms[2], G_TYPE_STRING);
5438 g_value_set_string (¶ms[2], object_path);
5440 g_value_init (¶ms[3], G_TYPE_STRING);
5441 g_value_set_string (¶ms[3], interface_name);
5443 g_value_init (¶ms[4], G_TYPE_STRING);
5444 g_value_set_string (¶ms[4], property_name);
5446 g_value_init (&result_value, G_TYPE_VARIANT);
5448 g_closure_invoke (data->get_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5450 result = g_value_get_variant (&result_value);
5452 g_variant_ref (result);
5454 g_value_unset (params + 0);
5455 g_value_unset (params + 1);
5456 g_value_unset (params + 2);
5457 g_value_unset (params + 3);
5458 g_value_unset (params + 4);
5459 g_value_unset (&result_value);
5462 g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5463 _("Unable to retrieve property %s.%s"),
5464 interface_name, property_name);
5470 register_with_closures_on_set_property (GDBusConnection *connection,
5471 const gchar *sender,
5472 const gchar *object_path,
5473 const gchar *interface_name,
5474 const gchar *property_name,
5479 RegisterObjectData *data = user_data;
5480 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5481 GValue result_value = G_VALUE_INIT;
5484 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5485 g_value_set_object (¶ms[0], connection);
5487 g_value_init (¶ms[1], G_TYPE_STRING);
5488 g_value_set_string (¶ms[1], sender);
5490 g_value_init (¶ms[2], G_TYPE_STRING);
5491 g_value_set_string (¶ms[2], object_path);
5493 g_value_init (¶ms[3], G_TYPE_STRING);
5494 g_value_set_string (¶ms[3], interface_name);
5496 g_value_init (¶ms[4], G_TYPE_STRING);
5497 g_value_set_string (¶ms[4], property_name);
5499 g_value_init (¶ms[5], G_TYPE_VARIANT);
5500 g_value_set_variant (¶ms[5], value);
5502 g_value_init (&result_value, G_TYPE_BOOLEAN);
5504 g_closure_invoke (data->set_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5506 result = g_value_get_boolean (&result_value);
5508 g_value_unset (params + 0);
5509 g_value_unset (params + 1);
5510 g_value_unset (params + 2);
5511 g_value_unset (params + 3);
5512 g_value_unset (params + 4);
5513 g_value_unset (params + 5);
5514 g_value_unset (&result_value);
5518 G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5519 _("Unable to set property %s.%s"),
5520 interface_name, property_name);
5526 * g_dbus_connection_register_object_with_closures: (rename-to g_dbus_connection_register_object)
5527 * @connection: A #GDBusConnection.
5528 * @object_path: The object path to register at.
5529 * @interface_info: Introspection data for the interface.
5530 * @method_call_closure: (nullable): #GClosure for handling incoming method calls.
5531 * @get_property_closure: (nullable): #GClosure for getting a property.
5532 * @set_property_closure: (nullable): #GClosure for setting a property.
5533 * @error: Return location for error or %NULL.
5535 * Version of g_dbus_connection_register_object() using closures instead of a
5536 * #GDBusInterfaceVTable for easier binding in other languages.
5538 * Returns: 0 if @error is set, otherwise a registration ID (never 0)
5539 * that can be used with g_dbus_connection_unregister_object() .
5544 g_dbus_connection_register_object_with_closures (GDBusConnection *connection,
5545 const gchar *object_path,
5546 GDBusInterfaceInfo *interface_info,
5547 GClosure *method_call_closure,
5548 GClosure *get_property_closure,
5549 GClosure *set_property_closure,
5552 RegisterObjectData *data;
5553 GDBusInterfaceVTable vtable =
5555 method_call_closure != NULL ? register_with_closures_on_method_call : NULL,
5556 get_property_closure != NULL ? register_with_closures_on_get_property : NULL,
5557 set_property_closure != NULL ? register_with_closures_on_set_property : NULL,
5561 data = register_object_data_new (method_call_closure, get_property_closure, set_property_closure);
5563 return g_dbus_connection_register_object (connection,
5568 register_object_free_func,
5572 /* ---------------------------------------------------------------------------------------------------- */
5575 * g_dbus_connection_emit_signal:
5576 * @connection: a #GDBusConnection
5577 * @destination_bus_name: (nullable): the unique bus name for the destination
5578 * for the signal or %NULL to emit to all listeners
5579 * @object_path: path of remote object
5580 * @interface_name: D-Bus interface to emit a signal on
5581 * @signal_name: the name of the signal to emit
5582 * @parameters: (nullable): a #GVariant tuple with parameters for the signal
5583 * or %NULL if not passing parameters
5584 * @error: Return location for error or %NULL
5588 * If the parameters GVariant is floating, it is consumed.
5590 * This can only fail if @parameters is not compatible with the D-Bus protocol
5591 * (%G_IO_ERROR_INVALID_ARGUMENT), or if @connection has been closed
5592 * (%G_IO_ERROR_CLOSED).
5594 * Returns: %TRUE unless @error is set
5599 g_dbus_connection_emit_signal (GDBusConnection *connection,
5600 const gchar *destination_bus_name,
5601 const gchar *object_path,
5602 const gchar *interface_name,
5603 const gchar *signal_name,
5604 GVariant *parameters,
5607 GDBusMessage *message;
5613 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5614 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5615 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5616 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5617 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5618 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5619 g_return_val_if_fail (check_initialized (connection), FALSE);
5621 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5623 _g_dbus_debug_print_lock ();
5624 g_print ("========================================================================\n"
5625 "GDBus-debug:Emission:\n"
5626 " >>>> SIGNAL EMISSION %s.%s()\n"
5628 " destination %s\n",
5629 interface_name, signal_name,
5631 destination_bus_name != NULL ? destination_bus_name : "(none)");
5632 _g_dbus_debug_print_unlock ();
5635 message = g_dbus_message_new_signal (object_path,
5639 if (destination_bus_name != NULL)
5640 g_dbus_message_set_header (message,
5641 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5642 g_variant_new_string (destination_bus_name));
5644 if (parameters != NULL)
5645 g_dbus_message_set_body (message, parameters);
5647 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5648 g_object_unref (message);
5654 add_call_flags (GDBusMessage *message,
5655 GDBusCallFlags flags)
5657 GDBusMessageFlags msg_flags = 0;
5659 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5660 msg_flags |= G_DBUS_MESSAGE_FLAGS_NO_AUTO_START;
5661 if (flags & G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
5662 msg_flags |= G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION;
5664 g_dbus_message_set_flags (message, msg_flags);
5668 decode_method_reply (GDBusMessage *reply,
5669 const gchar *method_name,
5670 const GVariantType *reply_type,
5671 GUnixFDList **out_fd_list,
5677 switch (g_dbus_message_get_message_type (reply))
5679 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5680 result = g_dbus_message_get_body (reply);
5683 result = g_variant_new ("()");
5684 g_variant_ref_sink (result);
5688 g_variant_ref (result);
5691 if (!g_variant_is_of_type (result, reply_type))
5693 gchar *type_string = g_variant_type_dup_string (reply_type);
5697 G_IO_ERROR_INVALID_ARGUMENT,
5698 _("Method “%s” returned type “%s”, but expected “%s”"),
5699 method_name, g_variant_get_type_string (result), type_string);
5701 g_variant_unref (result);
5702 g_free (type_string);
5709 if (out_fd_list != NULL)
5711 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5712 if (*out_fd_list != NULL)
5713 g_object_ref (*out_fd_list);
5719 case G_DBUS_MESSAGE_TYPE_ERROR:
5720 g_dbus_message_to_gerror (reply, error);
5724 g_assert_not_reached ();
5734 GVariantType *reply_type;
5735 gchar *method_name; /* for error message */
5737 GUnixFDList *fd_list;
5741 call_state_free (CallState *state)
5743 g_variant_type_free (state->reply_type);
5744 g_free (state->method_name);
5746 if (state->fd_list != NULL)
5747 g_object_unref (state->fd_list);
5748 g_slice_free (CallState, state);
5751 /* called in any thread, with the connection's lock not held */
5753 g_dbus_connection_call_done (GObject *source,
5754 GAsyncResult *result,
5757 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5758 GTask *task = user_data;
5759 CallState *state = g_task_get_task_data (task);
5760 GError *error = NULL;
5761 GDBusMessage *reply;
5762 GVariant *value = NULL;
5764 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5768 if (G_UNLIKELY (_g_dbus_debug_call ()))
5770 _g_dbus_debug_print_lock ();
5771 g_print ("========================================================================\n"
5772 "GDBus-debug:Call:\n"
5773 " <<<< ASYNC COMPLETE %s()",
5774 state->method_name);
5778 g_print (" (serial %d)\n"
5780 g_dbus_message_get_reply_serial (reply));
5788 _g_dbus_debug_print_unlock ();
5792 value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5795 g_task_return_error (task, error);
5797 g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5799 g_clear_object (&reply);
5800 g_object_unref (task);
5803 /* called in any thread, with the connection's lock not held */
5805 g_dbus_connection_call_internal (GDBusConnection *connection,
5806 const gchar *bus_name,
5807 const gchar *object_path,
5808 const gchar *interface_name,
5809 const gchar *method_name,
5810 GVariant *parameters,
5811 const GVariantType *reply_type,
5812 GDBusCallFlags flags,
5814 GUnixFDList *fd_list,
5815 GCancellable *cancellable,
5816 GAsyncReadyCallback callback,
5819 GDBusMessage *message;
5822 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5823 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5824 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5825 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5826 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5827 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5828 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5829 g_return_if_fail (check_initialized (connection));
5831 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5833 g_return_if_fail (fd_list == NULL);
5836 message = g_dbus_message_new_method_call (bus_name,
5840 add_call_flags (message, flags);
5841 if (parameters != NULL)
5842 g_dbus_message_set_body (message, parameters);
5845 if (fd_list != NULL)
5846 g_dbus_message_set_unix_fd_list (message, fd_list);
5849 /* If the user has no callback then we can just send the message with
5850 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5851 * the logic for processing the reply. If the service sends the reply
5852 * anyway then it will just be ignored.
5854 if (callback != NULL)
5859 state = g_slice_new0 (CallState);
5860 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5862 if (reply_type == NULL)
5863 reply_type = G_VARIANT_TYPE_ANY;
5865 state->reply_type = g_variant_type_copy (reply_type);
5867 task = g_task_new (connection, cancellable, callback, user_data);
5868 g_task_set_source_tag (task, g_dbus_connection_call_internal);
5869 g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5871 g_dbus_connection_send_message_with_reply (connection,
5873 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5877 g_dbus_connection_call_done,
5882 GDBusMessageFlags flags;
5884 flags = g_dbus_message_get_flags (message);
5885 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5886 g_dbus_message_set_flags (message, flags);
5888 g_dbus_connection_send_message (connection,
5890 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5894 if (G_UNLIKELY (_g_dbus_debug_call ()))
5896 _g_dbus_debug_print_lock ();
5897 g_print ("========================================================================\n"
5898 "GDBus-debug:Call:\n"
5899 " >>>> ASYNC %s.%s()\n"
5901 " owned by name %s (serial %d)\n",
5905 bus_name != NULL ? bus_name : "(none)",
5907 _g_dbus_debug_print_unlock ();
5910 if (message != NULL)
5911 g_object_unref (message);
5914 /* called in any thread, with the connection's lock not held */
5916 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5917 GUnixFDList **out_fd_list,
5925 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5926 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5927 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5929 task = G_TASK (res);
5930 state = g_task_get_task_data (task);
5932 ret = g_task_propagate_pointer (task, error);
5936 if (out_fd_list != NULL)
5937 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5941 /* called in any user thread, with the connection's lock not held */
5943 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5944 const gchar *bus_name,
5945 const gchar *object_path,
5946 const gchar *interface_name,
5947 const gchar *method_name,
5948 GVariant *parameters,
5949 const GVariantType *reply_type,
5950 GDBusCallFlags flags,
5952 GUnixFDList *fd_list,
5953 GUnixFDList **out_fd_list,
5954 GCancellable *cancellable,
5957 GDBusMessage *message;
5958 GDBusMessage *reply;
5960 GError *local_error;
5961 GDBusSendMessageFlags send_flags;
5967 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5968 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5969 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5970 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5971 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5972 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5973 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5975 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5977 g_return_val_if_fail (fd_list == NULL, NULL);
5979 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5981 if (!(flags & CALL_FLAGS_INITIALIZING))
5982 g_return_val_if_fail (check_initialized (connection), FALSE);
5984 if (reply_type == NULL)
5985 reply_type = G_VARIANT_TYPE_ANY;
5987 message = g_dbus_message_new_method_call (bus_name,
5991 add_call_flags (message, flags);
5992 if (parameters != NULL)
5993 g_dbus_message_set_body (message, parameters);
5996 if (fd_list != NULL)
5997 g_dbus_message_set_unix_fd_list (message, fd_list);
6000 if (G_UNLIKELY (_g_dbus_debug_call ()))
6002 _g_dbus_debug_print_lock ();
6003 g_print ("========================================================================\n"
6004 "GDBus-debug:Call:\n"
6005 " >>>> SYNC %s.%s()\n"
6007 " owned by name %s\n",
6011 bus_name != NULL ? bus_name : "(none)");
6012 _g_dbus_debug_print_unlock ();
6017 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6019 /* translate from one flavour of flags to another... */
6020 if (flags & CALL_FLAGS_INITIALIZING)
6021 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6023 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6027 NULL, /* guint32 *out_serial */
6031 if (G_UNLIKELY (_g_dbus_debug_call ()))
6033 _g_dbus_debug_print_lock ();
6034 g_print ("========================================================================\n"
6035 "GDBus-debug:Call:\n"
6036 " <<<< SYNC COMPLETE %s.%s()\n"
6042 g_print ("SUCCESS\n");
6046 g_print ("FAILED: %s\n",
6047 local_error->message);
6049 _g_dbus_debug_print_unlock ();
6055 *error = local_error;
6057 g_error_free (local_error);
6061 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6064 if (message != NULL)
6065 g_object_unref (message);
6067 g_object_unref (reply);
6072 /* ---------------------------------------------------------------------------------------------------- */
6075 * g_dbus_connection_call:
6076 * @connection: a #GDBusConnection
6077 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6078 * @connection is not a message bus connection
6079 * @object_path: path of remote object
6080 * @interface_name: D-Bus interface to invoke method on
6081 * @method_name: the name of the method to invoke
6082 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6083 * or %NULL if not passing parameters
6084 * @reply_type: (nullable): the expected type of the reply (which will be a
6086 * @flags: flags from the #GDBusCallFlags enumeration
6087 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6088 * timeout or %G_MAXINT for no timeout
6089 * @cancellable: (nullable): a #GCancellable or %NULL
6090 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
6091 * is satisfied or %NULL if you don't care about the result of the
6093 * @user_data: the data to pass to @callback
6095 * Asynchronously invokes the @method_name method on the
6096 * @interface_name D-Bus interface on the remote object at
6097 * @object_path owned by @bus_name.
6099 * If @connection is closed then the operation will fail with
6100 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6101 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6102 * not compatible with the D-Bus protocol, the operation fails with
6103 * %G_IO_ERROR_INVALID_ARGUMENT.
6105 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6106 * error will be raised if it does not match. Said another way, if you give a @reply_type
6107 * then any non-%NULL return value will be of this type. Unless it’s
6108 * %G_VARIANT_TYPE_UNIT, the @reply_type will be a tuple containing one or more
6111 * If the @parameters #GVariant is floating, it is consumed. This allows
6112 * convenient 'inline' use of g_variant_new(), e.g.:
6113 * |[<!-- language="C" -->
6114 * g_dbus_connection_call (connection,
6115 * "org.freedesktop.StringThings",
6116 * "/org/freedesktop/StringThings",
6117 * "org.freedesktop.StringThings",
6119 * g_variant_new ("(ss)",
6123 * G_DBUS_CALL_FLAGS_NONE,
6126 * (GAsyncReadyCallback) two_strings_done,
6130 * This is an asynchronous method. When the operation is finished,
6131 * @callback will be invoked in the
6132 * [thread-default main context][g-main-context-push-thread-default]
6133 * of the thread you are calling this method from. You can then call
6134 * g_dbus_connection_call_finish() to get the result of the operation.
6135 * See g_dbus_connection_call_sync() for the synchronous version of this
6138 * If @callback is %NULL then the D-Bus method call message will be sent with
6139 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6144 g_dbus_connection_call (GDBusConnection *connection,
6145 const gchar *bus_name,
6146 const gchar *object_path,
6147 const gchar *interface_name,
6148 const gchar *method_name,
6149 GVariant *parameters,
6150 const GVariantType *reply_type,
6151 GDBusCallFlags flags,
6153 GCancellable *cancellable,
6154 GAsyncReadyCallback callback,
6157 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);
6161 * g_dbus_connection_call_finish:
6162 * @connection: a #GDBusConnection
6163 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6164 * @error: return location for error or %NULL
6166 * Finishes an operation started with g_dbus_connection_call().
6168 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6169 * #GVariant tuple with return values. Free with g_variant_unref().
6174 g_dbus_connection_call_finish (GDBusConnection *connection,
6178 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6182 * g_dbus_connection_call_sync:
6183 * @connection: a #GDBusConnection
6184 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6185 * @connection is not a message bus connection
6186 * @object_path: path of remote object
6187 * @interface_name: D-Bus interface to invoke method on
6188 * @method_name: the name of the method to invoke
6189 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6190 * or %NULL if not passing parameters
6191 * @reply_type: (nullable): the expected type of the reply, or %NULL
6192 * @flags: flags from the #GDBusCallFlags enumeration
6193 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6194 * timeout or %G_MAXINT for no timeout
6195 * @cancellable: (nullable): a #GCancellable or %NULL
6196 * @error: return location for error or %NULL
6198 * Synchronously invokes the @method_name method on the
6199 * @interface_name D-Bus interface on the remote object at
6200 * @object_path owned by @bus_name.
6202 * If @connection is closed then the operation will fail with
6203 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6204 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6205 * contains a value not compatible with the D-Bus protocol, the operation
6206 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6208 * If @reply_type is non-%NULL then the reply will be checked for having
6209 * this type and an error will be raised if it does not match. Said
6210 * another way, if you give a @reply_type then any non-%NULL return
6211 * value will be of this type.
6213 * If the @parameters #GVariant is floating, it is consumed.
6214 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6215 * |[<!-- language="C" -->
6216 * g_dbus_connection_call_sync (connection,
6217 * "org.freedesktop.StringThings",
6218 * "/org/freedesktop/StringThings",
6219 * "org.freedesktop.StringThings",
6221 * g_variant_new ("(ss)",
6225 * G_DBUS_CALL_FLAGS_NONE,
6231 * The calling thread is blocked until a reply is received. See
6232 * g_dbus_connection_call() for the asynchronous version of
6235 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6236 * #GVariant tuple with return values. Free with g_variant_unref().
6241 g_dbus_connection_call_sync (GDBusConnection *connection,
6242 const gchar *bus_name,
6243 const gchar *object_path,
6244 const gchar *interface_name,
6245 const gchar *method_name,
6246 GVariant *parameters,
6247 const GVariantType *reply_type,
6248 GDBusCallFlags flags,
6250 GCancellable *cancellable,
6253 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);
6256 /* ---------------------------------------------------------------------------------------------------- */
6261 * g_dbus_connection_call_with_unix_fd_list:
6262 * @connection: a #GDBusConnection
6263 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6264 * @connection is not a message bus connection
6265 * @object_path: path of remote object
6266 * @interface_name: D-Bus interface to invoke method on
6267 * @method_name: the name of the method to invoke
6268 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6269 * or %NULL if not passing parameters
6270 * @reply_type: (nullable): the expected type of the reply, or %NULL
6271 * @flags: flags from the #GDBusCallFlags enumeration
6272 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6273 * timeout or %G_MAXINT for no timeout
6274 * @fd_list: (nullable): a #GUnixFDList or %NULL
6275 * @cancellable: (nullable): a #GCancellable or %NULL
6276 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
6277 * satisfied or %NULL if you don't * care about the result of the
6279 * @user_data: The data to pass to @callback.
6281 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6283 * The file descriptors normally correspond to %G_VARIANT_TYPE_HANDLE
6284 * values in the body of the message. For example, if a message contains
6285 * two file descriptors, @fd_list would have length 2, and
6286 * `g_variant_new_handle (0)` and `g_variant_new_handle (1)` would appear
6287 * somewhere in the body of the message (not necessarily in that order!)
6288 * to represent the file descriptors at indexes 0 and 1 respectively.
6290 * When designing D-Bus APIs that are intended to be interoperable,
6291 * please note that non-GDBus implementations of D-Bus can usually only
6292 * access file descriptors if they are referenced in this way by a
6293 * value of type %G_VARIANT_TYPE_HANDLE in the body of the message.
6295 * This method is only available on UNIX.
6300 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6301 const gchar *bus_name,
6302 const gchar *object_path,
6303 const gchar *interface_name,
6304 const gchar *method_name,
6305 GVariant *parameters,
6306 const GVariantType *reply_type,
6307 GDBusCallFlags flags,
6309 GUnixFDList *fd_list,
6310 GCancellable *cancellable,
6311 GAsyncReadyCallback callback,
6314 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);
6318 * g_dbus_connection_call_with_unix_fd_list_finish:
6319 * @connection: a #GDBusConnection
6320 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6321 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6322 * g_dbus_connection_call_with_unix_fd_list()
6323 * @error: return location for error or %NULL
6325 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6327 * The file descriptors normally correspond to %G_VARIANT_TYPE_HANDLE
6328 * values in the body of the message. For example,
6329 * if g_variant_get_handle() returns 5, that is intended to be a reference
6330 * to the file descriptor that can be accessed by
6331 * `g_unix_fd_list_get (*out_fd_list, 5, ...)`.
6333 * When designing D-Bus APIs that are intended to be interoperable,
6334 * please note that non-GDBus implementations of D-Bus can usually only
6335 * access file descriptors if they are referenced in this way by a
6336 * value of type %G_VARIANT_TYPE_HANDLE in the body of the message.
6338 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6339 * #GVariant tuple with return values. Free with g_variant_unref().
6344 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6345 GUnixFDList **out_fd_list,
6349 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6353 * g_dbus_connection_call_with_unix_fd_list_sync:
6354 * @connection: a #GDBusConnection
6355 * @bus_name: (nullable): a unique or well-known bus name or %NULL
6356 * if @connection is not a message bus connection
6357 * @object_path: path of remote object
6358 * @interface_name: D-Bus interface to invoke method on
6359 * @method_name: the name of the method to invoke
6360 * @parameters: (nullable): a #GVariant tuple with parameters for
6361 * the method or %NULL if not passing parameters
6362 * @reply_type: (nullable): the expected type of the reply, or %NULL
6363 * @flags: flags from the #GDBusCallFlags enumeration
6364 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6365 * timeout or %G_MAXINT for no timeout
6366 * @fd_list: (nullable): a #GUnixFDList or %NULL
6367 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6368 * @cancellable: (nullable): a #GCancellable or %NULL
6369 * @error: return location for error or %NULL
6371 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6372 * See g_dbus_connection_call_with_unix_fd_list() and
6373 * g_dbus_connection_call_with_unix_fd_list_finish() for more details.
6375 * This method is only available on UNIX.
6377 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6378 * #GVariant tuple with return values. Free with g_variant_unref().
6383 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6384 const gchar *bus_name,
6385 const gchar *object_path,
6386 const gchar *interface_name,
6387 const gchar *method_name,
6388 GVariant *parameters,
6389 const GVariantType *reply_type,
6390 GDBusCallFlags flags,
6392 GUnixFDList *fd_list,
6393 GUnixFDList **out_fd_list,
6394 GCancellable *cancellable,
6397 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);
6400 #endif /* G_OS_UNIX */
6402 /* ---------------------------------------------------------------------------------------------------- */
6404 struct ExportedSubtree
6408 GDBusConnection *connection;
6409 GDBusSubtreeVTable *vtable;
6410 GDBusSubtreeFlags flags;
6412 GMainContext *context;
6414 GDestroyNotify user_data_free_func;
6418 exported_subtree_free (ExportedSubtree *es)
6420 call_destroy_notify (es->context,
6421 es->user_data_free_func,
6424 g_main_context_unref (es->context);
6426 _g_dbus_subtree_vtable_free (es->vtable);
6427 g_free (es->object_path);
6431 /* called without lock held in the thread where the caller registered
6435 handle_subtree_introspect (GDBusConnection *connection,
6436 ExportedSubtree *es,
6437 GDBusMessage *message)
6441 GDBusMessage *reply;
6444 const gchar *sender;
6445 const gchar *requested_object_path;
6446 const gchar *requested_node;
6447 GDBusInterfaceInfo **interfaces;
6449 gchar **subnode_paths;
6450 gboolean has_properties_interface;
6451 gboolean has_introspectable_interface;
6455 requested_object_path = g_dbus_message_get_path (message);
6456 sender = g_dbus_message_get_sender (message);
6457 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6459 s = g_string_new (NULL);
6460 introspect_append_header (s);
6462 /* Strictly we don't need the children in dynamic mode, but we avoid the
6463 * conditionals to preserve code clarity
6465 children = es->vtable->enumerate (es->connection,
6472 requested_node = strrchr (requested_object_path, '/') + 1;
6474 /* Assert existence of object if we are not dynamic */
6475 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6476 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6481 requested_node = NULL;
6484 interfaces = es->vtable->introspect (es->connection,
6489 if (interfaces != NULL)
6491 has_properties_interface = FALSE;
6492 has_introspectable_interface = FALSE;
6494 for (n = 0; interfaces[n] != NULL; n++)
6496 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6497 has_properties_interface = TRUE;
6498 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6499 has_introspectable_interface = TRUE;
6501 if (!has_properties_interface)
6502 g_string_append (s, introspect_properties_interface);
6503 if (!has_introspectable_interface)
6504 g_string_append (s, introspect_introspectable_interface);
6506 for (n = 0; interfaces[n] != NULL; n++)
6508 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6509 g_dbus_interface_info_unref (interfaces[n]);
6511 g_free (interfaces);
6514 /* then include <node> entries from the Subtree for the root */
6517 for (n = 0; children != NULL && children[n] != NULL; n++)
6518 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6521 /* finally include nodes registered below us */
6522 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6523 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6524 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6525 g_strfreev (subnode_paths);
6527 g_string_append (s, "</node>\n");
6529 reply = g_dbus_message_new_method_reply (message);
6530 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6531 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6532 g_object_unref (reply);
6537 g_string_free (s, TRUE);
6538 g_strfreev (children);
6542 /* called without lock held in the thread where the caller registered
6546 handle_subtree_method_invocation (GDBusConnection *connection,
6547 ExportedSubtree *es,
6548 GDBusMessage *message)
6551 const gchar *sender;
6552 const gchar *interface_name;
6553 const gchar *member;
6554 const gchar *signature;
6555 const gchar *requested_object_path;
6556 const gchar *requested_node;
6558 GDBusInterfaceInfo *interface_info;
6559 const GDBusInterfaceVTable *interface_vtable;
6560 gpointer interface_user_data;
6562 GDBusInterfaceInfo **interfaces;
6563 gboolean is_property_get;
6564 gboolean is_property_set;
6565 gboolean is_property_get_all;
6570 requested_object_path = g_dbus_message_get_path (message);
6571 sender = g_dbus_message_get_sender (message);
6572 interface_name = g_dbus_message_get_interface (message);
6573 member = g_dbus_message_get_member (message);
6574 signature = g_dbus_message_get_signature (message);
6575 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6577 is_property_get = FALSE;
6578 is_property_set = FALSE;
6579 is_property_get_all = FALSE;
6580 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6582 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6583 is_property_get = TRUE;
6584 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6585 is_property_set = TRUE;
6586 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6587 is_property_get_all = TRUE;
6592 requested_node = strrchr (requested_object_path, '/') + 1;
6594 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6596 /* We don't want to dispatch to unenumerated
6597 * nodes, so ensure that the child exists.
6602 children = es->vtable->enumerate (es->connection,
6607 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6608 g_strfreev (children);
6616 requested_node = NULL;
6619 /* get introspection data for the node */
6620 interfaces = es->vtable->introspect (es->connection,
6622 requested_object_path,
6626 if (interfaces == NULL)
6629 interface_info = NULL;
6630 for (n = 0; interfaces[n] != NULL; n++)
6632 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6633 interface_info = interfaces[n];
6636 /* dispatch the call if the user wants to handle it */
6637 if (interface_info != NULL)
6639 /* figure out where to dispatch the method call */
6640 interface_user_data = NULL;
6641 interface_vtable = es->vtable->dispatch (es->connection,
6646 &interface_user_data,
6648 if (interface_vtable == NULL)
6651 CONNECTION_LOCK (connection);
6652 handled = validate_and_maybe_schedule_method_call (es->connection,
6659 interface_user_data);
6660 CONNECTION_UNLOCK (connection);
6662 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6663 else if (is_property_get || is_property_set || is_property_get_all)
6665 if (is_property_get)
6666 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6667 else if (is_property_set)
6668 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6669 else if (is_property_get_all)
6670 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6672 g_assert_not_reached ();
6674 /* see if the object supports this interface at all */
6675 for (n = 0; interfaces[n] != NULL; n++)
6677 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6678 interface_info = interfaces[n];
6681 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6682 * claims it won't support the interface
6684 if (interface_info == NULL)
6686 GDBusMessage *reply;
6687 reply = g_dbus_message_new_method_error (message,
6688 "org.freedesktop.DBus.Error.InvalidArgs",
6689 _("No such interface “%s”"),
6691 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6692 g_object_unref (reply);
6697 /* figure out where to dispatch the property get/set/getall calls */
6698 interface_user_data = NULL;
6699 interface_vtable = es->vtable->dispatch (es->connection,
6704 &interface_user_data,
6706 if (interface_vtable == NULL)
6708 g_warning ("The subtree introspection function indicates that '%s' "
6709 "is a valid interface name, but calling the dispatch "
6710 "function on that interface gave us NULL", interface_name);
6714 if (is_property_get || is_property_set)
6716 CONNECTION_LOCK (connection);
6717 handled = validate_and_maybe_schedule_property_getset (es->connection,
6725 interface_user_data);
6726 CONNECTION_UNLOCK (connection);
6728 else if (is_property_get_all)
6730 CONNECTION_LOCK (connection);
6731 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6738 interface_user_data);
6739 CONNECTION_UNLOCK (connection);
6744 if (interfaces != NULL)
6746 for (n = 0; interfaces[n] != NULL; n++)
6747 g_dbus_interface_info_unref (interfaces[n]);
6748 g_free (interfaces);
6756 GDBusMessage *message;
6757 ExportedSubtree *es;
6758 } SubtreeDeferredData;
6761 subtree_deferred_data_free (SubtreeDeferredData *data)
6763 g_object_unref (data->message);
6767 /* called without lock held in the thread where the caller registered the subtree */
6769 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6771 SubtreeDeferredData *data = _data;
6776 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6777 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6778 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6779 handled = handle_subtree_introspect (data->es->connection,
6783 handled = handle_subtree_method_invocation (data->es->connection,
6789 CONNECTION_LOCK (data->es->connection);
6790 handled = handle_generic_unlocked (data->es->connection, data->message);
6791 CONNECTION_UNLOCK (data->es->connection);
6794 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6797 GDBusMessage *reply;
6798 reply = g_dbus_message_new_method_error (data->message,
6799 "org.freedesktop.DBus.Error.UnknownMethod",
6800 _("Method “%s” on interface “%s” with signature “%s” does not exist"),
6801 g_dbus_message_get_member (data->message),
6802 g_dbus_message_get_interface (data->message),
6803 g_dbus_message_get_signature (data->message));
6804 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6805 g_object_unref (reply);
6811 /* called in GDBusWorker thread with connection's lock held */
6813 subtree_message_func (GDBusConnection *connection,
6814 ExportedSubtree *es,
6815 GDBusMessage *message)
6817 GSource *idle_source;
6818 SubtreeDeferredData *data;
6820 data = g_new0 (SubtreeDeferredData, 1);
6821 data->message = g_object_ref (message);
6824 /* defer this call to an idle handler in the right thread */
6825 idle_source = g_idle_source_new ();
6826 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6827 g_source_set_callback (idle_source,
6828 process_subtree_vtable_message_in_idle_cb,
6830 (GDestroyNotify) subtree_deferred_data_free);
6831 g_source_set_static_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6832 g_source_attach (idle_source, es->context);
6833 g_source_unref (idle_source);
6835 /* since we own the entire subtree, handlers for objects not in the subtree have been
6836 * tried already by libdbus-1 - so we just need to ensure that we're always going
6837 * to reply to the message
6843 * g_dbus_connection_register_subtree:
6844 * @connection: a #GDBusConnection
6845 * @object_path: the object path to register the subtree at
6846 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6847 * dispatch nodes in the subtree
6848 * @flags: flags used to fine tune the behavior of the subtree
6849 * @user_data: data to pass to functions in @vtable
6850 * @user_data_free_func: function to call when the subtree is unregistered
6851 * @error: return location for error or %NULL
6853 * Registers a whole subtree of dynamic objects.
6855 * The @enumerate and @introspection functions in @vtable are used to
6856 * convey, to remote callers, what nodes exist in the subtree rooted
6859 * When handling remote calls into any node in the subtree, first the
6860 * @enumerate function is used to check if the node exists. If the node exists
6861 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6862 * the @introspection function is used to check if the node supports the
6863 * requested method. If so, the @dispatch function is used to determine
6864 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6865 * #gpointer will be used to call into the interface vtable for processing
6868 * All calls into user-provided code will be invoked in the
6869 * [thread-default main context][g-main-context-push-thread-default]
6870 * of the thread you are calling this method from.
6872 * If an existing subtree is already registered at @object_path or
6873 * then @error is set to #G_IO_ERROR_EXISTS.
6875 * Note that it is valid to register regular objects (using
6876 * g_dbus_connection_register_object()) in a subtree registered with
6877 * g_dbus_connection_register_subtree() - if so, the subtree handler
6878 * is tried as the last resort. One way to think about a subtree
6879 * handler is to consider it a fallback handler for object paths not
6880 * registered via g_dbus_connection_register_object() or other bindings.
6882 * Note that @vtable will be copied so you cannot change it after
6885 * See this [server][gdbus-subtree-server] for an example of how to use
6888 * Returns: 0 if @error is set, otherwise a subtree registration ID (never 0)
6889 * that can be used with g_dbus_connection_unregister_subtree()
6894 g_dbus_connection_register_subtree (GDBusConnection *connection,
6895 const gchar *object_path,
6896 const GDBusSubtreeVTable *vtable,
6897 GDBusSubtreeFlags flags,
6899 GDestroyNotify user_data_free_func,
6903 ExportedSubtree *es;
6905 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6906 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6907 g_return_val_if_fail (vtable != NULL, 0);
6908 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6909 g_return_val_if_fail (check_initialized (connection), 0);
6913 CONNECTION_LOCK (connection);
6915 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6921 _("A subtree is already exported for %s"),
6926 es = g_new0 (ExportedSubtree, 1);
6927 es->object_path = g_strdup (object_path);
6928 es->connection = connection;
6930 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6932 es->id = (guint) g_atomic_int_add (&_global_subtree_registration_id, 1); /* TODO: overflow etc. */
6933 es->user_data = user_data;
6934 es->user_data_free_func = user_data_free_func;
6935 es->context = g_main_context_ref_thread_default ();
6937 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6938 g_hash_table_insert (connection->map_id_to_es,
6939 GUINT_TO_POINTER (es->id),
6945 CONNECTION_UNLOCK (connection);
6950 /* ---------------------------------------------------------------------------------------------------- */
6953 * g_dbus_connection_unregister_subtree:
6954 * @connection: a #GDBusConnection
6955 * @registration_id: a subtree registration id obtained from
6956 * g_dbus_connection_register_subtree()
6958 * Unregisters a subtree.
6960 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6965 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6966 guint registration_id)
6968 ExportedSubtree *es;
6971 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6972 g_return_val_if_fail (check_initialized (connection), FALSE);
6976 CONNECTION_LOCK (connection);
6978 es = g_hash_table_lookup (connection->map_id_to_es,
6979 GUINT_TO_POINTER (registration_id));
6983 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6984 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6989 CONNECTION_UNLOCK (connection);
6994 /* ---------------------------------------------------------------------------------------------------- */
6996 /* may be called in any thread, with connection's lock held */
6998 handle_generic_ping_unlocked (GDBusConnection *connection,
6999 const gchar *object_path,
7000 GDBusMessage *message)
7002 GDBusMessage *reply;
7003 reply = g_dbus_message_new_method_reply (message);
7004 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7005 g_object_unref (reply);
7008 /* may be called in any thread, with connection's lock held */
7010 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7011 const gchar *object_path,
7012 GDBusMessage *message)
7014 GDBusMessage *reply;
7017 if (connection->machine_id == NULL)
7022 connection->machine_id = _g_dbus_get_machine_id (&error);
7023 if (connection->machine_id == NULL)
7025 reply = g_dbus_message_new_method_error_literal (message,
7026 "org.freedesktop.DBus.Error.Failed",
7028 g_error_free (error);
7034 reply = g_dbus_message_new_method_reply (message);
7035 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7037 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7038 g_object_unref (reply);
7041 /* may be called in any thread, with connection's lock held */
7043 handle_generic_introspect_unlocked (GDBusConnection *connection,
7044 const gchar *object_path,
7045 GDBusMessage *message)
7050 GDBusMessage *reply;
7052 /* first the header */
7053 s = g_string_new (NULL);
7054 introspect_append_header (s);
7056 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7057 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7058 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7059 g_strfreev (registered);
7060 g_string_append (s, "</node>\n");
7062 reply = g_dbus_message_new_method_reply (message);
7063 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7064 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7065 g_object_unref (reply);
7066 g_string_free (s, TRUE);
7069 /* may be called in any thread, with connection's lock held */
7071 handle_generic_unlocked (GDBusConnection *connection,
7072 GDBusMessage *message)
7075 const gchar *interface_name;
7076 const gchar *member;
7077 const gchar *signature;
7080 CONNECTION_ENSURE_LOCK (connection);
7084 interface_name = g_dbus_message_get_interface (message);
7085 member = g_dbus_message_get_member (message);
7086 signature = g_dbus_message_get_signature (message);
7087 path = g_dbus_message_get_path (message);
7089 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7090 g_strcmp0 (member, "Introspect") == 0 &&
7091 g_strcmp0 (signature, "") == 0)
7093 handle_generic_introspect_unlocked (connection, path, message);
7096 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7097 g_strcmp0 (member, "Ping") == 0 &&
7098 g_strcmp0 (signature, "") == 0)
7100 handle_generic_ping_unlocked (connection, path, message);
7103 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7104 g_strcmp0 (member, "GetMachineId") == 0 &&
7105 g_strcmp0 (signature, "") == 0)
7107 handle_generic_get_machine_id_unlocked (connection, path, message);
7114 /* ---------------------------------------------------------------------------------------------------- */
7116 /* called in GDBusWorker thread with connection's lock held */
7118 distribute_method_call (GDBusConnection *connection,
7119 GDBusMessage *message)
7121 GDBusMessage *reply;
7123 ExportedSubtree *es;
7124 const gchar *object_path;
7125 const gchar *interface_name;
7126 const gchar *member;
7128 gchar *subtree_path;
7130 gboolean object_found = FALSE;
7132 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7134 interface_name = g_dbus_message_get_interface (message);
7135 member = g_dbus_message_get_member (message);
7136 path = g_dbus_message_get_path (message);
7137 subtree_path = g_strdup (path);
7138 needle = strrchr (subtree_path, '/');
7139 if (needle != NULL && needle != subtree_path)
7145 g_free (subtree_path);
7146 subtree_path = NULL;
7150 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7152 _g_dbus_debug_print_lock ();
7153 g_print ("========================================================================\n"
7154 "GDBus-debug:Incoming:\n"
7155 " <<<< METHOD INVOCATION %s.%s()\n"
7157 " invoked by name %s\n"
7159 interface_name, member,
7161 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7162 g_dbus_message_get_serial (message));
7163 _g_dbus_debug_print_unlock ();
7166 object_path = g_dbus_message_get_path (message);
7167 g_assert (object_path != NULL);
7169 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7172 if (obj_message_func (connection, eo, message, &object_found))
7176 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7179 if (subtree_message_func (connection, es, message))
7183 if (subtree_path != NULL)
7185 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7188 if (subtree_message_func (connection, es, message))
7193 if (handle_generic_unlocked (connection, message))
7196 /* if we end up here, the message has not been not handled - so return an error saying this */
7197 if (object_found == TRUE)
7199 reply = g_dbus_message_new_method_error (message,
7200 "org.freedesktop.DBus.Error.UnknownMethod",
7201 _("No such interface “%s” on object at path %s"),
7207 reply = g_dbus_message_new_method_error (message,
7208 "org.freedesktop.DBus.Error.UnknownMethod",
7209 _("Object does not exist at path “%s”"),
7213 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7214 g_object_unref (reply);
7217 g_free (subtree_path);
7220 /* ---------------------------------------------------------------------------------------------------- */
7222 /* Called in any user thread, with the message_bus_lock held. */
7224 message_bus_get_singleton (GBusType bus_type,
7228 const gchar *starter_bus;
7234 case G_BUS_TYPE_SESSION:
7235 ret = &the_session_bus;
7238 case G_BUS_TYPE_SYSTEM:
7239 ret = &the_system_bus;
7242 case G_BUS_TYPE_STARTER:
7243 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7244 if (g_strcmp0 (starter_bus, "session") == 0)
7246 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7249 else if (g_strcmp0 (starter_bus, "system") == 0)
7251 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7256 if (starter_bus != NULL)
7260 G_IO_ERROR_INVALID_ARGUMENT,
7261 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7262 " — unknown value “%s”"),
7267 g_set_error_literal (error,
7269 G_IO_ERROR_INVALID_ARGUMENT,
7270 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7271 "variable is not set"));
7277 g_assert_not_reached ();
7285 /* Called in any user thread, without holding locks. */
7286 static GDBusConnection *
7287 get_uninitialized_connection (GBusType bus_type,
7288 GCancellable *cancellable,
7291 GWeakRef *singleton;
7292 GDBusConnection *ret;
7296 G_LOCK (message_bus_lock);
7297 singleton = message_bus_get_singleton (bus_type, error);
7298 if (singleton == NULL)
7301 ret = g_weak_ref_get (singleton);
7306 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7307 if (address == NULL)
7309 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7311 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7312 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7313 "exit-on-close", TRUE,
7316 g_weak_ref_set (singleton, ret);
7320 g_assert (ret != NULL);
7323 G_UNLOCK (message_bus_lock);
7327 /* May be called from any thread. Must not hold message_bus_lock. */
7329 _g_bus_get_singleton_if_exists (GBusType bus_type)
7331 GWeakRef *singleton;
7332 GDBusConnection *ret = NULL;
7334 G_LOCK (message_bus_lock);
7335 singleton = message_bus_get_singleton (bus_type, NULL);
7336 if (singleton == NULL)
7339 ret = g_weak_ref_get (singleton);
7342 G_UNLOCK (message_bus_lock);
7346 /* May be called from any thread. Must not hold message_bus_lock. */
7348 _g_bus_forget_singleton (GBusType bus_type)
7350 GWeakRef *singleton;
7352 G_LOCK (message_bus_lock);
7354 singleton = message_bus_get_singleton (bus_type, NULL);
7356 if (singleton != NULL)
7357 g_weak_ref_set (singleton, NULL);
7359 G_UNLOCK (message_bus_lock);
7364 * @bus_type: a #GBusType
7365 * @cancellable: (nullable): a #GCancellable or %NULL
7366 * @error: return location for error or %NULL
7368 * Synchronously connects to the message bus specified by @bus_type.
7369 * Note that the returned object may shared with other callers,
7370 * e.g. if two separate parts of a process calls this function with
7371 * the same @bus_type, they will share the same object.
7373 * This is a synchronous failable function. See g_bus_get() and
7374 * g_bus_get_finish() for the asynchronous version.
7376 * The returned object is a singleton, that is, shared with other
7377 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7378 * event that you need a private message bus connection, use
7379 * g_dbus_address_get_for_bus_sync() and
7380 * g_dbus_connection_new_for_address().
7382 * Note that the returned #GDBusConnection object will (usually) have
7383 * the #GDBusConnection:exit-on-close property set to %TRUE.
7385 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7386 * Free with g_object_unref().
7391 g_bus_get_sync (GBusType bus_type,
7392 GCancellable *cancellable,
7395 GDBusConnection *connection;
7397 _g_dbus_initialize ();
7399 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7401 connection = get_uninitialized_connection (bus_type, cancellable, error);
7402 if (connection == NULL)
7405 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7407 g_object_unref (connection);
7416 bus_get_async_initable_cb (GObject *source_object,
7420 GTask *task = user_data;
7421 GError *error = NULL;
7423 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7427 g_assert (error != NULL);
7428 g_task_return_error (task, error);
7429 g_object_unref (source_object);
7433 g_task_return_pointer (task, source_object, g_object_unref);
7435 g_object_unref (task);
7440 * @bus_type: a #GBusType
7441 * @cancellable: (nullable): a #GCancellable or %NULL
7442 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7443 * @user_data: the data to pass to @callback
7445 * Asynchronously connects to the message bus specified by @bus_type.
7447 * When the operation is finished, @callback will be invoked. You can
7448 * then call g_bus_get_finish() to get the result of the operation.
7450 * This is an asynchronous failable function. See g_bus_get_sync() for
7451 * the synchronous version.
7456 g_bus_get (GBusType bus_type,
7457 GCancellable *cancellable,
7458 GAsyncReadyCallback callback,
7461 GDBusConnection *connection;
7463 GError *error = NULL;
7465 _g_dbus_initialize ();
7467 task = g_task_new (NULL, cancellable, callback, user_data);
7468 g_task_set_source_tag (task, g_bus_get);
7470 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7471 if (connection == NULL)
7473 g_assert (error != NULL);
7474 g_task_return_error (task, error);
7475 g_object_unref (task);
7479 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7482 bus_get_async_initable_cb,
7489 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7491 * @error: return location for error or %NULL
7493 * Finishes an operation started with g_bus_get().
7495 * The returned object is a singleton, that is, shared with other
7496 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7497 * event that you need a private message bus connection, use
7498 * g_dbus_address_get_for_bus_sync() and
7499 * g_dbus_connection_new_for_address().
7501 * Note that the returned #GDBusConnection object will (usually) have
7502 * the #GDBusConnection:exit-on-close property set to %TRUE.
7504 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7505 * Free with g_object_unref().
7510 g_bus_get_finish (GAsyncResult *res,
7513 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7514 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7516 return g_task_propagate_pointer (G_TASK (res), error);
7519 /* ---------------------------------------------------------------------------------------------------- */