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://git.gnome.org/browse/glib/tree/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://git.gnome.org/browse/glib/tree/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://git.gnome.org/browse/glib/tree/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://git.gnome.org/browse/glib/tree/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_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 authenticed as a client or
390 * the GUID to use if authenticating as a server.
391 * Read-only after initable_init(), so it may be read if you either
392 * hold @init_lock or check for initialization first.
396 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
397 * Inspect @initialization_error to see whether it succeeded or failed.
399 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
401 * FLAG_CLOSED is the closed property. It may be read at any time, but
402 * may only be written while holding @lock.
404 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
907 g_object_class_install_property (gobject_class,
909 g_param_spec_string ("guid",
911 P_("GUID of the server peer"),
915 G_PARAM_CONSTRUCT_ONLY |
916 G_PARAM_STATIC_NAME |
917 G_PARAM_STATIC_BLURB |
918 G_PARAM_STATIC_NICK));
921 * GDBusConnection:unique-name:
923 * The unique name as assigned by the message bus or %NULL if the
924 * connection is not open or not a message bus connection.
928 g_object_class_install_property (gobject_class,
930 g_param_spec_string ("unique-name",
932 P_("Unique name of bus connection"),
935 G_PARAM_STATIC_NAME |
936 G_PARAM_STATIC_BLURB |
937 G_PARAM_STATIC_NICK));
940 * GDBusConnection:closed:
942 * A boolean specifying whether the connection has been closed.
946 g_object_class_install_property (gobject_class,
948 g_param_spec_boolean ("closed",
950 P_("Whether the connection is closed"),
953 G_PARAM_STATIC_NAME |
954 G_PARAM_STATIC_BLURB |
955 G_PARAM_STATIC_NICK));
958 * GDBusConnection:exit-on-close:
960 * A boolean specifying whether the process will be terminated (by
961 * calling `raise(SIGTERM)`) if the connection is closed by the
964 * Note that #GDBusConnection objects returned by g_bus_get_finish()
965 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
969 g_object_class_install_property (gobject_class,
971 g_param_spec_boolean ("exit-on-close",
973 P_("Whether the process is terminated when the connection is closed"),
977 G_PARAM_STATIC_NAME |
978 G_PARAM_STATIC_BLURB |
979 G_PARAM_STATIC_NICK));
982 * GDBusConnection:capabilities:
984 * Flags from the #GDBusCapabilityFlags enumeration
985 * representing connection features negotiated with the other peer.
989 g_object_class_install_property (gobject_class,
990 PROP_CAPABILITY_FLAGS,
991 g_param_spec_flags ("capabilities",
994 G_TYPE_DBUS_CAPABILITY_FLAGS,
995 G_DBUS_CAPABILITY_FLAGS_NONE,
997 G_PARAM_STATIC_NAME |
998 G_PARAM_STATIC_BLURB |
999 G_PARAM_STATIC_NICK));
1002 * GDBusConnection:authentication-observer:
1004 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1008 g_object_class_install_property (gobject_class,
1009 PROP_AUTHENTICATION_OBSERVER,
1010 g_param_spec_object ("authentication-observer",
1011 P_("Authentication Observer"),
1012 P_("Object used to assist in the authentication process"),
1013 G_TYPE_DBUS_AUTH_OBSERVER,
1015 G_PARAM_CONSTRUCT_ONLY |
1016 G_PARAM_STATIC_NAME |
1017 G_PARAM_STATIC_BLURB |
1018 G_PARAM_STATIC_NICK));
1021 * GDBusConnection::closed:
1022 * @connection: the #GDBusConnection emitting the signal
1023 * @remote_peer_vanished: %TRUE if @connection is closed because the
1024 * remote peer closed its end of the connection
1025 * @error: (nullable): a #GError with more details about the event or %NULL
1027 * Emitted when the connection is closed.
1029 * The cause of this event can be
1031 * - If g_dbus_connection_close() is called. In this case
1032 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1034 * - If the remote peer closes the connection. In this case
1035 * @remote_peer_vanished is set to %TRUE and @error is set.
1037 * - If the remote peer sends invalid or malformed data. In this
1038 * case @remote_peer_vanished is set to %FALSE and @error is set.
1040 * Upon receiving this signal, you should give up your reference to
1041 * @connection. You are guaranteed that this signal is emitted only
1046 signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1047 G_TYPE_DBUS_CONNECTION,
1049 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1052 _g_cclosure_marshal_VOID__BOOLEAN_BOXED,
1057 g_signal_set_va_marshaller (signals[CLOSED_SIGNAL],
1058 G_TYPE_FROM_CLASS (klass),
1059 _g_cclosure_marshal_VOID__BOOLEAN_BOXEDv);
1063 g_dbus_connection_init (GDBusConnection *connection)
1065 g_mutex_init (&connection->lock);
1066 g_mutex_init (&connection->init_lock);
1068 connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1070 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1072 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1074 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1077 (GDestroyNotify) g_ptr_array_unref);
1079 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1082 (GDestroyNotify) exported_object_free);
1084 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1087 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1090 (GDestroyNotify) exported_subtree_free);
1092 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1095 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1098 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1100 connection->filters = g_ptr_array_new ();
1104 * g_dbus_connection_get_stream:
1105 * @connection: a #GDBusConnection
1107 * Gets the underlying stream used for IO.
1109 * While the #GDBusConnection is active, it will interact with this
1110 * stream from a worker thread, so it is not safe to interact with
1111 * the stream directly.
1113 * Returns: (transfer none) (not nullable): the stream used for IO
1118 g_dbus_connection_get_stream (GDBusConnection *connection)
1120 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1122 /* do not use g_return_val_if_fail(), we want the memory barrier */
1123 if (!check_initialized (connection))
1126 return connection->stream;
1130 * g_dbus_connection_start_message_processing:
1131 * @connection: a #GDBusConnection
1133 * If @connection was created with
1134 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1135 * starts processing messages. Does nothing on if @connection wasn't
1136 * created with this flag or if the method has already been called.
1141 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1143 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1145 /* do not use g_return_val_if_fail(), we want the memory barrier */
1146 if (!check_initialized (connection))
1149 g_assert (connection->worker != NULL);
1150 _g_dbus_worker_unfreeze (connection->worker);
1154 * g_dbus_connection_is_closed:
1155 * @connection: a #GDBusConnection
1157 * Gets whether @connection is closed.
1159 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1164 g_dbus_connection_is_closed (GDBusConnection *connection)
1168 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1170 flags = g_atomic_int_get (&connection->atomic_flags);
1172 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1176 * g_dbus_connection_get_capabilities:
1177 * @connection: a #GDBusConnection
1179 * Gets the capabilities negotiated with the remote peer
1181 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1185 GDBusCapabilityFlags
1186 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1188 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1190 /* do not use g_return_val_if_fail(), we want the memory barrier */
1191 if (!check_initialized (connection))
1192 return G_DBUS_CAPABILITY_FLAGS_NONE;
1194 return connection->capabilities;
1198 * g_dbus_connection_get_flags:
1199 * @connection: a #GDBusConnection
1201 * Gets the flags used to construct this connection
1203 * Returns: zero or more flags from the #GDBusConnectionFlags enumeration
1207 GDBusConnectionFlags
1208 g_dbus_connection_get_flags (GDBusConnection *connection)
1210 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CONNECTION_FLAGS_NONE);
1212 /* do not use g_return_val_if_fail(), we want the memory barrier */
1213 if (!check_initialized (connection))
1214 return G_DBUS_CONNECTION_FLAGS_NONE;
1216 return connection->flags;
1219 /* ---------------------------------------------------------------------------------------------------- */
1221 /* Called in a temporary thread without holding locks. */
1223 flush_in_thread_func (GTask *task,
1224 gpointer source_object,
1226 GCancellable *cancellable)
1228 GError *error = NULL;
1230 if (g_dbus_connection_flush_sync (source_object,
1233 g_task_return_boolean (task, TRUE);
1235 g_task_return_error (task, error);
1239 * g_dbus_connection_flush:
1240 * @connection: a #GDBusConnection
1241 * @cancellable: (nullable): a #GCancellable or %NULL
1242 * @callback: (nullable): a #GAsyncReadyCallback to call when the
1243 * request is satisfied or %NULL if you don't care about the result
1244 * @user_data: The data to pass to @callback
1246 * Asynchronously flushes @connection, that is, writes all queued
1247 * outgoing message to the transport and then flushes the transport
1248 * (using g_output_stream_flush_async()). This is useful in programs
1249 * that wants to emit a D-Bus signal and then exit immediately. Without
1250 * flushing the connection, there is no guaranteed that the message has
1251 * been sent to the networking buffers in the OS kernel.
1253 * This is an asynchronous method. When the operation is finished,
1254 * @callback will be invoked in the
1255 * [thread-default main context][g-main-context-push-thread-default]
1256 * of the thread you are calling this method from. You can
1257 * then call g_dbus_connection_flush_finish() to get the result of the
1258 * operation. See g_dbus_connection_flush_sync() for the synchronous
1264 g_dbus_connection_flush (GDBusConnection *connection,
1265 GCancellable *cancellable,
1266 GAsyncReadyCallback callback,
1271 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1273 task = g_task_new (connection, cancellable, callback, user_data);
1274 g_task_set_source_tag (task, g_dbus_connection_flush);
1275 g_task_run_in_thread (task, flush_in_thread_func);
1276 g_object_unref (task);
1280 * g_dbus_connection_flush_finish:
1281 * @connection: a #GDBusConnection
1282 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1283 * to g_dbus_connection_flush()
1284 * @error: return location for error or %NULL
1286 * Finishes an operation started with g_dbus_connection_flush().
1288 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1293 g_dbus_connection_flush_finish (GDBusConnection *connection,
1297 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1298 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1299 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1301 return g_task_propagate_boolean (G_TASK (res), error);
1305 * g_dbus_connection_flush_sync:
1306 * @connection: a #GDBusConnection
1307 * @cancellable: (nullable): a #GCancellable or %NULL
1308 * @error: return location for error or %NULL
1310 * Synchronously flushes @connection. The calling thread is blocked
1311 * until this is done. See g_dbus_connection_flush() for the
1312 * asynchronous version of this method and more details about what it
1315 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1320 g_dbus_connection_flush_sync (GDBusConnection *connection,
1321 GCancellable *cancellable,
1326 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1327 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1331 /* This is only a best-effort attempt to see whether the connection is
1332 * closed, so it doesn't need the lock. If the connection closes just
1333 * after this check, but before scheduling the flush operation, the
1334 * result will be more or less the same as if the connection closed while
1335 * the flush operation was pending - it'll fail with either CLOSED or
1338 if (!check_unclosed (connection, 0, error))
1341 g_assert (connection->worker != NULL);
1343 ret = _g_dbus_worker_flush_sync (connection->worker,
1351 /* ---------------------------------------------------------------------------------------------------- */
1355 GDBusConnection *connection;
1357 gboolean remote_peer_vanished;
1361 emit_closed_data_free (EmitClosedData *data)
1363 g_object_unref (data->connection);
1364 if (data->error != NULL)
1365 g_error_free (data->error);
1369 /* Called in a user thread that has acquired the main context that was
1370 * thread-default when the object was constructed
1373 emit_closed_in_idle (gpointer user_data)
1375 EmitClosedData *data = user_data;
1378 g_object_notify (G_OBJECT (data->connection), "closed");
1379 g_signal_emit (data->connection,
1380 signals[CLOSED_SIGNAL],
1382 data->remote_peer_vanished,
1388 /* Can be called from any thread, must hold lock.
1389 * FLAG_CLOSED must already have been set.
1392 schedule_closed_unlocked (GDBusConnection *connection,
1393 gboolean remote_peer_vanished,
1396 GSource *idle_source;
1397 EmitClosedData *data;
1399 CONNECTION_ENSURE_LOCK (connection);
1401 data = g_new0 (EmitClosedData, 1);
1402 data->connection = g_object_ref (connection);
1403 data->remote_peer_vanished = remote_peer_vanished;
1404 data->error = error != NULL ? g_error_copy (error) : NULL;
1406 idle_source = g_idle_source_new ();
1407 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1408 g_source_set_callback (idle_source,
1409 emit_closed_in_idle,
1411 (GDestroyNotify) emit_closed_data_free);
1412 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1413 g_source_attach (idle_source, connection->main_context_at_construction);
1414 g_source_unref (idle_source);
1417 /* ---------------------------------------------------------------------------------------------------- */
1420 * g_dbus_connection_close:
1421 * @connection: a #GDBusConnection
1422 * @cancellable: (nullable): a #GCancellable or %NULL
1423 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1424 * satisfied or %NULL if you don't care about the result
1425 * @user_data: The data to pass to @callback
1427 * Closes @connection. Note that this never causes the process to
1428 * exit (this might only happen if the other end of a shared message
1429 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1431 * Once the connection is closed, operations such as sending a message
1432 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1433 * will not automatically flush the connection so queued messages may
1434 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1436 * If @connection is already closed, this method fails with
1437 * %G_IO_ERROR_CLOSED.
1439 * When @connection has been closed, the #GDBusConnection::closed
1440 * signal is emitted in the
1441 * [thread-default main context][g-main-context-push-thread-default]
1442 * of the thread that @connection was constructed in.
1444 * This is an asynchronous method. When the operation is finished,
1445 * @callback will be invoked in the
1446 * [thread-default main context][g-main-context-push-thread-default]
1447 * of the thread you are calling this method from. You can
1448 * then call g_dbus_connection_close_finish() to get the result of the
1449 * operation. See g_dbus_connection_close_sync() for the synchronous
1455 g_dbus_connection_close (GDBusConnection *connection,
1456 GCancellable *cancellable,
1457 GAsyncReadyCallback callback,
1462 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1464 /* do not use g_return_val_if_fail(), we want the memory barrier */
1465 if (!check_initialized (connection))
1468 g_assert (connection->worker != NULL);
1470 task = g_task_new (connection, cancellable, callback, user_data);
1471 g_task_set_source_tag (task, g_dbus_connection_close);
1472 _g_dbus_worker_close (connection->worker, task);
1473 g_object_unref (task);
1477 * g_dbus_connection_close_finish:
1478 * @connection: a #GDBusConnection
1479 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1480 * to g_dbus_connection_close()
1481 * @error: return location for error or %NULL
1483 * Finishes an operation started with g_dbus_connection_close().
1485 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1490 g_dbus_connection_close_finish (GDBusConnection *connection,
1494 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1495 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1496 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1498 return g_task_propagate_boolean (G_TASK (res), error);
1503 GAsyncResult *result;
1506 /* Can be called by any thread, without the connection lock */
1508 sync_close_cb (GObject *source_object,
1512 SyncCloseData *data = user_data;
1514 data->result = g_object_ref (res);
1515 g_main_loop_quit (data->loop);
1519 * g_dbus_connection_close_sync:
1520 * @connection: a #GDBusConnection
1521 * @cancellable: (nullable): a #GCancellable or %NULL
1522 * @error: return location for error or %NULL
1524 * Synchronously closes @connection. The calling thread is blocked
1525 * until this is done. See g_dbus_connection_close() for the
1526 * asynchronous version of this method and more details about what it
1529 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1534 g_dbus_connection_close_sync (GDBusConnection *connection,
1535 GCancellable *cancellable,
1540 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1541 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1545 if (check_unclosed (connection, 0, error))
1547 GMainContext *context;
1550 context = g_main_context_new ();
1551 g_main_context_push_thread_default (context);
1552 data.loop = g_main_loop_new (context, TRUE);
1555 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1556 g_main_loop_run (data.loop);
1557 ret = g_dbus_connection_close_finish (connection, data.result, error);
1559 g_object_unref (data.result);
1560 g_main_loop_unref (data.loop);
1561 g_main_context_pop_thread_default (context);
1562 g_main_context_unref (context);
1568 /* ---------------------------------------------------------------------------------------------------- */
1571 * g_dbus_connection_get_last_serial:
1572 * @connection: a #GDBusConnection
1574 * Retrieves the last serial number assigned to a #GDBusMessage on
1575 * the current thread. This includes messages sent via both low-level
1576 * API such as g_dbus_connection_send_message() as well as
1577 * high-level API such as g_dbus_connection_emit_signal(),
1578 * g_dbus_connection_call() or g_dbus_proxy_call().
1580 * Returns: the last used serial or zero when no message has been sent
1581 * within the current thread
1586 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1590 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1592 CONNECTION_LOCK (connection);
1593 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1595 CONNECTION_UNLOCK (connection);
1600 /* ---------------------------------------------------------------------------------------------------- */
1602 /* Can be called by any thread, with the connection lock held */
1604 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1605 GDBusMessage *message,
1606 GDBusSendMessageFlags flags,
1607 guint32 *out_serial,
1612 guint32 serial_to_use;
1615 CONNECTION_ENSURE_LOCK (connection);
1617 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1618 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1620 /* TODO: check all necessary headers are present */
1625 if (out_serial != NULL)
1628 /* If we're in initable_init(), don't check for being initialized, to avoid
1629 * chicken-and-egg problems. initable_init() is responsible for setting up
1630 * our prerequisites (mainly connection->worker), and only calling us
1631 * from its own thread (so no memory barrier is needed).
1633 if (!check_unclosed (connection,
1634 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1638 blob = g_dbus_message_to_blob (message,
1640 connection->capabilities,
1645 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1646 serial_to_use = g_dbus_message_get_serial (message);
1648 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1653 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1656 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1659 g_assert_not_reached ();
1664 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1665 blob_size, serial_to_use, connection);
1666 g_printerr ("----\n");
1667 hexdump (blob, blob_size);
1668 g_printerr ("----\n");
1671 /* TODO: use connection->auth to encode the blob */
1673 if (out_serial != NULL)
1674 *out_serial = serial_to_use;
1676 /* store used serial for the current thread */
1677 /* TODO: watch the thread disposal and remove associated record
1679 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1681 g_hash_table_replace (connection->map_thread_to_last_serial,
1683 GUINT_TO_POINTER (serial_to_use));
1685 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1686 g_dbus_message_set_serial (message, serial_to_use);
1688 g_dbus_message_lock (message);
1689 _g_dbus_worker_send_message (connection->worker,
1693 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
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_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;
2205 /* requires CONNECTION_LOCK */
2206 static FilterData **
2207 copy_filter_list (GPtrArray *filters)
2212 copy = g_new (FilterData *, filters->len + 1);
2213 for (n = 0; n < filters->len; n++)
2215 copy[n] = filters->pdata[n];
2216 copy[n]->ref_count++;
2223 /* requires CONNECTION_LOCK */
2225 free_filter_list (FilterData **filters)
2229 for (n = 0; filters[n]; n++)
2231 filters[n]->ref_count--;
2232 if (filters[n]->ref_count == 0)
2234 call_destroy_notify (filters[n]->context,
2235 filters[n]->user_data_free_func,
2236 filters[n]->user_data);
2237 g_main_context_unref (filters[n]->context);
2238 g_free (filters[n]);
2244 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2246 on_worker_message_received (GDBusWorker *worker,
2247 GDBusMessage *message,
2250 GDBusConnection *connection;
2251 FilterData **filters;
2255 G_LOCK (message_bus_lock);
2256 alive = g_hash_table_contains (alive_connections, user_data);
2259 G_UNLOCK (message_bus_lock);
2262 connection = G_DBUS_CONNECTION (user_data);
2263 g_object_ref (connection);
2264 G_UNLOCK (message_bus_lock);
2266 //g_debug ("in on_worker_message_received");
2268 g_object_ref (message);
2269 g_dbus_message_lock (message);
2271 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2273 /* First collect the set of callback functions */
2274 CONNECTION_LOCK (connection);
2275 filters = copy_filter_list (connection->filters);
2276 CONNECTION_UNLOCK (connection);
2278 /* then call the filters in order (without holding the lock) */
2279 for (n = 0; filters[n]; n++)
2281 message = filters[n]->filter_function (connection,
2284 filters[n]->user_data);
2285 if (message == NULL)
2287 g_dbus_message_lock (message);
2290 CONNECTION_LOCK (connection);
2291 free_filter_list (filters);
2292 CONNECTION_UNLOCK (connection);
2294 /* Standard dispatch unless the filter ate the message - no need to
2295 * do anything if the message was altered
2297 if (message != NULL)
2299 GDBusMessageType message_type;
2301 message_type = g_dbus_message_get_message_type (message);
2302 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2304 guint32 reply_serial;
2307 reply_serial = g_dbus_message_get_reply_serial (message);
2308 CONNECTION_LOCK (connection);
2309 task = g_hash_table_lookup (connection->map_method_serial_to_task,
2310 GUINT_TO_POINTER (reply_serial));
2313 /* This removes @task from @map_method_serial_to_task. */
2314 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2315 send_message_data_deliver_reply_unlocked (task, message);
2319 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2321 CONNECTION_UNLOCK (connection);
2323 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2325 CONNECTION_LOCK (connection);
2326 distribute_signals (connection, message);
2327 CONNECTION_UNLOCK (connection);
2329 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2331 CONNECTION_LOCK (connection);
2332 distribute_method_call (connection, message);
2333 CONNECTION_UNLOCK (connection);
2337 if (message != NULL)
2338 g_object_unref (message);
2339 g_object_unref (connection);
2342 /* Called in GDBusWorker's thread, lock is not held */
2343 static GDBusMessage *
2344 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2345 GDBusMessage *message,
2348 GDBusConnection *connection;
2349 FilterData **filters;
2353 G_LOCK (message_bus_lock);
2354 alive = g_hash_table_contains (alive_connections, user_data);
2357 G_UNLOCK (message_bus_lock);
2360 connection = G_DBUS_CONNECTION (user_data);
2361 g_object_ref (connection);
2362 G_UNLOCK (message_bus_lock);
2364 //g_debug ("in on_worker_message_about_to_be_sent");
2366 /* First collect the set of callback functions */
2367 CONNECTION_LOCK (connection);
2368 filters = copy_filter_list (connection->filters);
2369 CONNECTION_UNLOCK (connection);
2371 /* then call the filters in order (without holding the lock) */
2372 for (n = 0; filters[n]; n++)
2374 g_dbus_message_lock (message);
2375 message = filters[n]->filter_function (connection,
2378 filters[n]->user_data);
2379 if (message == NULL)
2383 CONNECTION_LOCK (connection);
2384 free_filter_list (filters);
2385 CONNECTION_UNLOCK (connection);
2387 g_object_unref (connection);
2392 /* called with connection lock held, in GDBusWorker thread */
2394 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2396 GTask *task = value;
2397 SendMessageData *data = g_task_get_task_data (task);
2399 if (data->delivered)
2402 g_task_return_new_error (task,
2405 _("The connection is closed"));
2407 /* Ask send_message_with_reply_cleanup not to remove the element from the
2408 * hash table - we're in the middle of a foreach; that would be unsafe.
2409 * Instead, return TRUE from this function so that it gets removed safely.
2411 send_message_with_reply_cleanup (task, FALSE);
2415 /* Called in GDBusWorker's thread - we must not block - without lock held */
2417 on_worker_closed (GDBusWorker *worker,
2418 gboolean remote_peer_vanished,
2422 GDBusConnection *connection;
2424 guint old_atomic_flags;
2426 G_LOCK (message_bus_lock);
2427 alive = g_hash_table_contains (alive_connections, user_data);
2430 G_UNLOCK (message_bus_lock);
2433 connection = G_DBUS_CONNECTION (user_data);
2434 g_object_ref (connection);
2435 G_UNLOCK (message_bus_lock);
2437 //g_debug ("in on_worker_closed: %s", error->message);
2439 CONNECTION_LOCK (connection);
2440 /* Even though this is atomic, we do it inside the lock to avoid breaking
2441 * assumptions in remove_match_rule(). We'd need the lock in a moment
2442 * anyway, so, no loss.
2444 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2446 if (!(old_atomic_flags & FLAG_CLOSED))
2448 g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2449 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2451 CONNECTION_UNLOCK (connection);
2453 g_object_unref (connection);
2456 /* ---------------------------------------------------------------------------------------------------- */
2458 /* Determines the biggest set of capabilities we can support on this
2461 * Called with the init_lock held.
2463 static GDBusCapabilityFlags
2464 get_offered_capabilities_max (GDBusConnection *connection)
2466 GDBusCapabilityFlags ret;
2467 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2469 if (G_IS_UNIX_CONNECTION (connection->stream))
2470 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2475 /* Called in a user thread, lock is not held */
2477 initable_init (GInitable *initable,
2478 GCancellable *cancellable,
2481 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2484 /* This method needs to be idempotent to work with the singleton
2485 * pattern. See the docs for g_initable_init(). We implement this by
2488 * Unfortunately we can't use the main lock since the on_worker_*()
2489 * callbacks above needs the lock during initialization (for message
2490 * bus connections we do a synchronous Hello() call on the bus).
2492 g_mutex_lock (&connection->init_lock);
2496 /* Make this a no-op if we're already initialized (successfully or
2499 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2501 ret = (connection->initialization_error == NULL);
2505 /* Because of init_lock, we can't get here twice in different threads */
2506 g_assert (connection->initialization_error == NULL);
2508 /* The user can pass multiple (but mutally exclusive) construct
2511 * - stream (of type GIOStream)
2512 * - address (of type gchar*)
2514 * At the end of the day we end up with a non-NULL GIOStream
2515 * object in connection->stream.
2517 if (connection->address != NULL)
2519 g_assert (connection->stream == NULL);
2521 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2522 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS) ||
2523 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER))
2525 g_set_error_literal (&connection->initialization_error,
2527 G_IO_ERROR_INVALID_ARGUMENT,
2528 _("Unsupported flags encountered when constructing a client-side connection"));
2532 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2533 NULL, /* TODO: out_guid */
2535 &connection->initialization_error);
2536 if (connection->stream == NULL)
2539 else if (connection->stream != NULL)
2545 g_assert_not_reached ();
2548 /* Authenticate the connection */
2549 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2551 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2552 g_assert (connection->guid != NULL);
2553 connection->auth = _g_dbus_auth_new (connection->stream);
2554 if (!_g_dbus_auth_run_server (connection->auth,
2555 connection->authentication_observer,
2557 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2558 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER),
2559 get_offered_capabilities_max (connection),
2560 &connection->capabilities,
2561 &connection->credentials,
2563 &connection->initialization_error))
2566 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2568 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2569 g_assert (connection->guid == NULL);
2570 connection->auth = _g_dbus_auth_new (connection->stream);
2571 connection->guid = _g_dbus_auth_run_client (connection->auth,
2572 connection->authentication_observer,
2573 get_offered_capabilities_max (connection),
2574 &connection->capabilities,
2576 &connection->initialization_error);
2577 if (connection->guid == NULL)
2581 if (connection->authentication_observer != NULL)
2583 g_object_unref (connection->authentication_observer);
2584 connection->authentication_observer = NULL;
2587 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2589 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2592 /* We want all IO operations to be non-blocking since they happen in
2593 * the worker thread which is shared by _all_ connections.
2595 if (G_IS_SOCKET_CONNECTION (connection->stream))
2597 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2601 G_LOCK (message_bus_lock);
2602 if (alive_connections == NULL)
2603 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2604 g_hash_table_add (alive_connections, connection);
2605 G_UNLOCK (message_bus_lock);
2607 connection->worker = _g_dbus_worker_new (connection->stream,
2608 connection->capabilities,
2609 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2610 on_worker_message_received,
2611 on_worker_message_about_to_be_sent,
2615 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2616 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2618 GVariant *hello_result;
2620 /* we could lift this restriction by adding code in gdbusprivate.c */
2621 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2623 g_set_error_literal (&connection->initialization_error,
2626 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2630 hello_result = g_dbus_connection_call_sync (connection,
2631 "org.freedesktop.DBus", /* name */
2632 "/org/freedesktop/DBus", /* path */
2633 "org.freedesktop.DBus", /* interface */
2635 NULL, /* parameters */
2636 G_VARIANT_TYPE ("(s)"),
2637 CALL_FLAGS_INITIALIZING,
2639 NULL, /* TODO: cancellable */
2640 &connection->initialization_error);
2641 if (hello_result == NULL)
2644 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2645 g_variant_unref (hello_result);
2646 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2653 g_assert (connection->initialization_error != NULL);
2654 g_propagate_error (error, g_error_copy (connection->initialization_error));
2657 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2658 g_mutex_unlock (&connection->init_lock);
2664 initable_iface_init (GInitableIface *initable_iface)
2666 initable_iface->init = initable_init;
2669 /* ---------------------------------------------------------------------------------------------------- */
2672 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2677 /* ---------------------------------------------------------------------------------------------------- */
2680 * g_dbus_connection_new:
2681 * @stream: a #GIOStream
2682 * @guid: (nullable): the GUID to use if authenticating as a server or %NULL
2683 * @flags: flags describing how to make the connection
2684 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2685 * @cancellable: (nullable): a #GCancellable or %NULL
2686 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2687 * @user_data: the data to pass to @callback
2689 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2690 * with the end represented by @stream.
2692 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2693 * will be put into non-blocking mode.
2695 * The D-Bus connection will interact with @stream from a worker thread.
2696 * As a result, the caller should not interact with @stream after this
2697 * method has been called, except by calling g_object_unref() on it.
2699 * If @observer is not %NULL it may be used to control the
2700 * authentication process.
2702 * When the operation is finished, @callback will be invoked. You can
2703 * then call g_dbus_connection_new_finish() to get the result of the
2706 * This is an asynchronous failable constructor. See
2707 * g_dbus_connection_new_sync() for the synchronous
2713 g_dbus_connection_new (GIOStream *stream,
2715 GDBusConnectionFlags flags,
2716 GDBusAuthObserver *observer,
2717 GCancellable *cancellable,
2718 GAsyncReadyCallback callback,
2721 _g_dbus_initialize ();
2723 g_return_if_fail (G_IS_IO_STREAM (stream));
2724 g_return_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0);
2726 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2734 "authentication-observer", observer,
2739 * g_dbus_connection_new_finish:
2740 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2741 * passed to g_dbus_connection_new().
2742 * @error: return location for error or %NULL
2744 * Finishes an operation started with g_dbus_connection_new().
2746 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set. Free
2747 * with g_object_unref().
2752 g_dbus_connection_new_finish (GAsyncResult *res,
2756 GObject *source_object;
2758 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2759 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2761 source_object = g_async_result_get_source_object (res);
2762 g_assert (source_object != NULL);
2763 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2766 g_object_unref (source_object);
2768 return G_DBUS_CONNECTION (object);
2774 * g_dbus_connection_new_sync:
2775 * @stream: a #GIOStream
2776 * @guid: (nullable): the GUID to use if authenticating as a server or %NULL
2777 * @flags: flags describing how to make the connection
2778 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2779 * @cancellable: (nullable): a #GCancellable or %NULL
2780 * @error: return location for error or %NULL
2782 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2783 * with the end represented by @stream.
2785 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2786 * will be put into non-blocking mode.
2788 * The D-Bus connection will interact with @stream from a worker thread.
2789 * As a result, the caller should not interact with @stream after this
2790 * method has been called, except by calling g_object_unref() on it.
2792 * If @observer is not %NULL it may be used to control the
2793 * authentication process.
2795 * This is a synchronous failable constructor. See
2796 * g_dbus_connection_new() for the asynchronous version.
2798 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
2799 * Free with g_object_unref().
2804 g_dbus_connection_new_sync (GIOStream *stream,
2806 GDBusConnectionFlags flags,
2807 GDBusAuthObserver *observer,
2808 GCancellable *cancellable,
2811 _g_dbus_initialize ();
2812 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2813 g_return_val_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0, NULL);
2814 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2815 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2821 "authentication-observer", observer,
2825 /* ---------------------------------------------------------------------------------------------------- */
2828 * g_dbus_connection_new_for_address:
2829 * @address: a D-Bus address
2830 * @flags: flags describing how to make the connection
2831 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2832 * @cancellable: (nullable): a #GCancellable or %NULL
2833 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2834 * @user_data: the data to pass to @callback
2836 * Asynchronously connects and sets up a D-Bus client connection for
2837 * exchanging D-Bus messages with an endpoint specified by @address
2838 * which must be in the
2839 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2841 * This constructor can only be used to initiate client-side
2842 * connections - use g_dbus_connection_new() if you need to act as the
2843 * server. In particular, @flags cannot contain the
2844 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER,
2845 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS or
2846 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER flags.
2848 * When the operation is finished, @callback will be invoked. You can
2849 * then call g_dbus_connection_new_for_address_finish() to get the result of
2852 * If @observer is not %NULL it may be used to control the
2853 * authentication process.
2855 * This is an asynchronous failable constructor. See
2856 * g_dbus_connection_new_for_address_sync() for the synchronous
2862 g_dbus_connection_new_for_address (const gchar *address,
2863 GDBusConnectionFlags flags,
2864 GDBusAuthObserver *observer,
2865 GCancellable *cancellable,
2866 GAsyncReadyCallback callback,
2869 _g_dbus_initialize ();
2871 g_return_if_fail (address != NULL);
2872 g_return_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0);
2874 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2881 "authentication-observer", observer,
2886 * g_dbus_connection_new_for_address_finish:
2887 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2888 * to g_dbus_connection_new()
2889 * @error: return location for error or %NULL
2891 * Finishes an operation started with g_dbus_connection_new_for_address().
2893 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
2894 * Free with g_object_unref().
2899 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2903 GObject *source_object;
2905 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2906 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2908 source_object = g_async_result_get_source_object (res);
2909 g_assert (source_object != NULL);
2910 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2913 g_object_unref (source_object);
2915 return G_DBUS_CONNECTION (object);
2921 * g_dbus_connection_new_for_address_sync:
2922 * @address: a D-Bus address
2923 * @flags: flags describing how to make the connection
2924 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2925 * @cancellable: (nullable): a #GCancellable or %NULL
2926 * @error: return location for error or %NULL
2928 * Synchronously connects and sets up a D-Bus client connection for
2929 * exchanging D-Bus messages with an endpoint specified by @address
2930 * which must be in the
2931 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2933 * This constructor can only be used to initiate client-side
2934 * connections - use g_dbus_connection_new_sync() if you need to act
2935 * as the server. In particular, @flags cannot contain the
2936 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER,
2937 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS or
2938 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_REQUIRE_SAME_USER flags.
2940 * This is a synchronous failable constructor. See
2941 * g_dbus_connection_new_for_address() for the asynchronous version.
2943 * If @observer is not %NULL it may be used to control the
2944 * authentication process.
2946 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
2947 * Free with g_object_unref().
2952 g_dbus_connection_new_for_address_sync (const gchar *address,
2953 GDBusConnectionFlags flags,
2954 GDBusAuthObserver *observer,
2955 GCancellable *cancellable,
2958 _g_dbus_initialize ();
2960 g_return_val_if_fail (address != NULL, NULL);
2961 g_return_val_if_fail ((flags & ~G_DBUS_CONNECTION_FLAGS_ALL) == 0, NULL);
2962 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2963 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2968 "authentication-observer", observer,
2972 /* ---------------------------------------------------------------------------------------------------- */
2975 * g_dbus_connection_set_exit_on_close:
2976 * @connection: a #GDBusConnection
2977 * @exit_on_close: whether the process should be terminated
2978 * when @connection is closed by the remote peer
2980 * Sets whether the process should be terminated when @connection is
2981 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2984 * Note that this function should be used with care. Most modern UNIX
2985 * desktops tie the notion of a user session with the session bus, and expect
2986 * all of a user's applications to quit when their bus connection goes away.
2987 * If you are setting @exit_on_close to %FALSE for the shared session
2988 * bus connection, you should make sure that your application exits
2989 * when the user session ends.
2994 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2995 gboolean exit_on_close)
2997 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3000 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3002 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3007 * g_dbus_connection_get_exit_on_close:
3008 * @connection: a #GDBusConnection
3010 * Gets whether the process is terminated when @connection is
3011 * closed by the remote peer. See
3012 * #GDBusConnection:exit-on-close for more details.
3014 * Returns: whether the process is terminated when @connection is
3015 * closed by the remote peer
3020 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3022 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3024 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3031 * g_dbus_connection_get_guid:
3032 * @connection: a #GDBusConnection
3034 * The GUID of the peer performing the role of server when
3035 * authenticating. See #GDBusConnection:guid for more details.
3037 * Returns: (not nullable): The GUID. Do not free this string, it is owned by
3043 g_dbus_connection_get_guid (GDBusConnection *connection)
3045 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3046 return connection->guid;
3050 * g_dbus_connection_get_unique_name:
3051 * @connection: a #GDBusConnection
3053 * Gets the unique name of @connection as assigned by the message
3054 * bus. This can also be used to figure out if @connection is a
3055 * message bus connection.
3057 * Returns: (nullable): the unique name or %NULL if @connection is not a message
3058 * bus connection. Do not free this string, it is owned by
3064 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3066 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3068 /* do not use g_return_val_if_fail(), we want the memory barrier */
3069 if (!check_initialized (connection))
3072 return connection->bus_unique_name;
3076 * g_dbus_connection_get_peer_credentials:
3077 * @connection: a #GDBusConnection
3079 * Gets the credentials of the authenticated peer. This will always
3080 * return %NULL unless @connection acted as a server
3081 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3082 * when set up and the client passed credentials as part of the
3083 * authentication process.
3085 * In a message bus setup, the message bus is always the server and
3086 * each application is a client. So this method will always return
3087 * %NULL for message bus clients.
3089 * Returns: (transfer none) (nullable): a #GCredentials or %NULL if not
3090 * available. Do not free this object, it is owned by @connection.
3095 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3097 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3099 /* do not use g_return_val_if_fail(), we want the memory barrier */
3100 if (!check_initialized (connection))
3103 return connection->credentials;
3106 /* ---------------------------------------------------------------------------------------------------- */
3108 static guint _global_filter_id = 1; /* (atomic) */
3111 * g_dbus_connection_add_filter:
3112 * @connection: a #GDBusConnection
3113 * @filter_function: a filter function
3114 * @user_data: user data to pass to @filter_function
3115 * @user_data_free_func: function to free @user_data with when filter
3116 * is removed or %NULL
3118 * Adds a message filter. Filters are handlers that are run on all
3119 * incoming and outgoing messages, prior to standard dispatch. Filters
3120 * are run in the order that they were added. The same handler can be
3121 * added as a filter more than once, in which case it will be run more
3122 * than once. Filters added during a filter callback won't be run on
3123 * the message being processed. Filter functions are allowed to modify
3124 * and even drop messages.
3126 * Note that filters are run in a dedicated message handling thread so
3127 * they can't block and, generally, can't do anything but signal a
3128 * worker thread. Also note that filters are rarely needed - use API
3129 * such as g_dbus_connection_send_message_with_reply(),
3130 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3132 * If a filter consumes an incoming message the message is not
3133 * dispatched anywhere else - not even the standard dispatch machinery
3134 * (that API such as g_dbus_connection_signal_subscribe() and
3135 * g_dbus_connection_send_message_with_reply() relies on) will see the
3136 * message. Similarly, if a filter consumes an outgoing message, the
3137 * message will not be sent to the other peer.
3139 * If @user_data_free_func is non-%NULL, it will be called (in the
3140 * thread-default main context of the thread you are calling this
3141 * method from) at some point after @user_data is no longer
3142 * needed. (It is not guaranteed to be called synchronously when the
3143 * filter is removed, and may be called after @connection has been
3146 * Returns: a filter identifier that can be used with
3147 * g_dbus_connection_remove_filter()
3152 g_dbus_connection_add_filter (GDBusConnection *connection,
3153 GDBusMessageFilterFunction filter_function,
3155 GDestroyNotify user_data_free_func)
3159 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3160 g_return_val_if_fail (filter_function != NULL, 0);
3161 g_return_val_if_fail (check_initialized (connection), 0);
3163 CONNECTION_LOCK (connection);
3164 data = g_new0 (FilterData, 1);
3165 data->id = (guint) g_atomic_int_add (&_global_filter_id, 1); /* TODO: overflow etc. */
3166 data->ref_count = 1;
3167 data->filter_function = filter_function;
3168 data->user_data = user_data;
3169 data->user_data_free_func = user_data_free_func;
3170 data->context = g_main_context_ref_thread_default ();
3171 g_ptr_array_add (connection->filters, data);
3172 CONNECTION_UNLOCK (connection);
3177 /* only called from finalize(), removes all filters */
3179 purge_all_filters (GDBusConnection *connection)
3182 for (n = 0; n < connection->filters->len; n++)
3184 FilterData *data = connection->filters->pdata[n];
3186 call_destroy_notify (data->context,
3187 data->user_data_free_func,
3189 g_main_context_unref (data->context);
3195 * g_dbus_connection_remove_filter:
3196 * @connection: a #GDBusConnection
3197 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3201 * Note that since filters run in a different thread, there is a race
3202 * condition where it is possible that the filter will be running even
3203 * after calling g_dbus_connection_remove_filter(), so you cannot just
3204 * free data that the filter might be using. Instead, you should pass
3205 * a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
3206 * called when it is guaranteed that the data is no longer needed.
3211 g_dbus_connection_remove_filter (GDBusConnection *connection,
3216 FilterData *to_destroy;
3218 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3219 g_return_if_fail (check_initialized (connection));
3221 CONNECTION_LOCK (connection);
3224 for (n = 0; n < connection->filters->len; n++)
3226 FilterData *data = connection->filters->pdata[n];
3227 if (data->id == filter_id)
3230 g_ptr_array_remove_index (connection->filters, n);
3232 if (data->ref_count == 0)
3237 CONNECTION_UNLOCK (connection);
3239 /* do free without holding lock */
3240 if (to_destroy != NULL)
3242 if (to_destroy->user_data_free_func != NULL)
3243 to_destroy->user_data_free_func (to_destroy->user_data);
3244 g_main_context_unref (to_destroy->context);
3245 g_free (to_destroy);
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
3731 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3732 guint subscription_id)
3734 guint n_subscribers_removed G_GNUC_UNUSED /* when compiling with G_DISABLE_ASSERT */;
3736 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3737 g_return_if_fail (check_initialized (connection));
3739 CONNECTION_LOCK (connection);
3740 n_subscribers_removed = unsubscribe_id_internal (connection, subscription_id);
3741 CONNECTION_UNLOCK (connection);
3744 g_assert (n_subscribers_removed == 0 || n_subscribers_removed == 1);
3747 /* ---------------------------------------------------------------------------------------------------- */
3751 SignalSubscriber *subscriber; /* (owned) */
3752 GDBusMessage *message;
3753 GDBusConnection *connection;
3754 const gchar *sender; /* (nullable) for peer-to-peer connections */
3756 const gchar *interface;
3757 const gchar *member;
3760 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3764 emit_signal_instance_in_idle_cb (gpointer data)
3766 SignalInstance *signal_instance = data;
3767 GVariant *parameters;
3768 gboolean has_subscription;
3770 parameters = g_dbus_message_get_body (signal_instance->message);
3771 if (parameters == NULL)
3773 parameters = g_variant_new ("()");
3774 g_variant_ref_sink (parameters);
3778 g_variant_ref_sink (parameters);
3782 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3783 signal_instance->subscriber->id,
3784 signal_instance->sender,
3785 signal_instance->path,
3786 signal_instance->interface,
3787 signal_instance->member,
3788 g_variant_print (parameters, TRUE));
3791 /* Careful here, don't do the callback if we no longer has the subscription */
3792 CONNECTION_LOCK (signal_instance->connection);
3793 has_subscription = FALSE;
3794 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3795 GUINT_TO_POINTER (signal_instance->subscriber->id)) != NULL)
3796 has_subscription = TRUE;
3797 CONNECTION_UNLOCK (signal_instance->connection);
3799 if (has_subscription)
3800 signal_instance->subscriber->callback (signal_instance->connection,
3801 signal_instance->sender,
3802 signal_instance->path,
3803 signal_instance->interface,
3804 signal_instance->member,
3806 signal_instance->subscriber->user_data);
3808 g_variant_unref (parameters);
3814 signal_instance_free (SignalInstance *signal_instance)
3816 g_object_unref (signal_instance->message);
3817 g_object_unref (signal_instance->connection);
3818 signal_subscriber_unref (signal_instance->subscriber);
3819 g_free (signal_instance);
3823 namespace_rule_matches (const gchar *namespace,
3829 len_namespace = strlen (namespace);
3830 len_name = strlen (name);
3832 if (len_name < len_namespace)
3835 if (memcmp (namespace, name, len_namespace) != 0)
3838 return len_namespace == len_name || name[len_namespace] == '.';
3842 path_rule_matches (const gchar *path_a,
3843 const gchar *path_b)
3847 len_a = strlen (path_a);
3848 len_b = strlen (path_b);
3850 if (len_a < len_b && (len_a == 0 || path_a[len_a - 1] != '/'))
3853 if (len_b < len_a && (len_b == 0 || path_b[len_b - 1] != '/'))
3856 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3859 /* called in GDBusWorker thread WITH lock held
3861 * @sender is (nullable) for peer-to-peer connections */
3863 schedule_callbacks (GDBusConnection *connection,
3864 GPtrArray *signal_data_array,
3865 GDBusMessage *message,
3866 const gchar *sender)
3869 const gchar *interface;
3870 const gchar *member;
3879 interface = g_dbus_message_get_interface (message);
3880 member = g_dbus_message_get_member (message);
3881 path = g_dbus_message_get_path (message);
3882 arg0 = g_dbus_message_get_arg0 (message);
3885 g_print ("In schedule_callbacks:\n"
3887 " interface = '%s'\n"
3898 /* TODO: if this is slow, then we can change signal_data_array into
3899 * map_object_path_to_signal_data_array or something.
3901 for (n = 0; n < signal_data_array->len; n++)
3903 SignalData *signal_data = signal_data_array->pdata[n];
3905 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3908 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3911 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3914 if (signal_data->arg0 != NULL)
3919 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3921 if (!namespace_rule_matches (signal_data->arg0, arg0))
3924 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3926 if (!path_rule_matches (signal_data->arg0, arg0))
3929 else if (!g_str_equal (signal_data->arg0, arg0))
3933 for (m = 0; m < signal_data->subscribers->len; m++)
3935 SignalSubscriber *subscriber = signal_data->subscribers->pdata[m];
3936 GSource *idle_source;
3937 SignalInstance *signal_instance;
3939 signal_instance = g_new0 (SignalInstance, 1);
3940 signal_instance->subscriber = signal_subscriber_ref (subscriber);
3941 signal_instance->message = g_object_ref (message);
3942 signal_instance->connection = g_object_ref (connection);
3943 signal_instance->sender = sender;
3944 signal_instance->path = path;
3945 signal_instance->interface = interface;
3946 signal_instance->member = member;
3948 idle_source = g_idle_source_new ();
3949 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3950 g_source_set_callback (idle_source,
3951 emit_signal_instance_in_idle_cb,
3953 (GDestroyNotify) signal_instance_free);
3954 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3955 g_source_attach (idle_source, subscriber->context);
3956 g_source_unref (idle_source);
3961 /* called in GDBusWorker thread with lock held */
3963 distribute_signals (GDBusConnection *connection,
3964 GDBusMessage *message)
3966 GPtrArray *signal_data_array;
3967 const gchar *sender;
3969 sender = g_dbus_message_get_sender (message);
3971 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3973 _g_dbus_debug_print_lock ();
3974 g_print ("========================================================================\n"
3975 "GDBus-debug:Signal:\n"
3976 " <<<< RECEIVED SIGNAL %s.%s\n"
3978 " sent by name %s\n",
3979 g_dbus_message_get_interface (message),
3980 g_dbus_message_get_member (message),
3981 g_dbus_message_get_path (message),
3982 sender != NULL ? sender : "(none)");
3983 _g_dbus_debug_print_unlock ();
3986 /* collect subscribers that match on sender */
3989 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3990 if (signal_data_array != NULL)
3991 schedule_callbacks (connection, signal_data_array, message, sender);
3994 /* collect subscribers not matching on sender */
3995 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3996 if (signal_data_array != NULL)
3997 schedule_callbacks (connection, signal_data_array, message, sender);
4000 /* ---------------------------------------------------------------------------------------------------- */
4002 /* only called from finalize(), removes all subscriptions */
4004 purge_all_signal_subscriptions (GDBusConnection *connection)
4006 GHashTableIter iter;
4011 ids = g_array_new (FALSE, FALSE, sizeof (guint));
4012 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
4013 while (g_hash_table_iter_next (&iter, &key, NULL))
4015 guint subscription_id = GPOINTER_TO_UINT (key);
4016 g_array_append_val (ids, subscription_id);
4019 for (n = 0; n < ids->len; n++)
4021 guint subscription_id = g_array_index (ids, guint, n);
4022 unsubscribe_id_internal (connection, subscription_id);
4024 g_array_free (ids, TRUE);
4027 /* ---------------------------------------------------------------------------------------------------- */
4029 static GDBusInterfaceVTable *
4030 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4032 /* Don't waste memory by copying padding - remember to update this
4033 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4035 return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
4039 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4044 /* ---------------------------------------------------------------------------------------------------- */
4046 static GDBusSubtreeVTable *
4047 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4049 /* Don't waste memory by copying padding - remember to update this
4050 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4052 return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
4056 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4061 /* ---------------------------------------------------------------------------------------------------- */
4063 struct ExportedObject
4066 GDBusConnection *connection;
4068 /* maps gchar* -> ExportedInterface* */
4069 GHashTable *map_if_name_to_ei;
4072 /* only called with lock held */
4074 exported_object_free (ExportedObject *eo)
4076 g_free (eo->object_path);
4077 g_hash_table_unref (eo->map_if_name_to_ei);
4086 gchar *interface_name;
4087 GDBusInterfaceVTable *vtable;
4088 GDBusInterfaceInfo *interface_info;
4090 GMainContext *context;
4092 GDestroyNotify user_data_free_func;
4093 } ExportedInterface;
4095 /* called with lock held */
4097 exported_interface_free (ExportedInterface *ei)
4099 g_dbus_interface_info_cache_release (ei->interface_info);
4100 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4102 call_destroy_notify (ei->context,
4103 ei->user_data_free_func,
4106 g_main_context_unref (ei->context);
4108 g_free (ei->interface_name);
4109 _g_dbus_interface_vtable_free (ei->vtable);
4113 /* ---------------------------------------------------------------------------------------------------- */
4115 /* Convenience function to check if @registration_id (if not zero) or
4116 * @subtree_registration_id (if not zero) has been unregistered. If
4117 * so, returns %TRUE.
4119 * May be called by any thread. Caller must *not* hold lock.
4122 has_object_been_unregistered (GDBusConnection *connection,
4123 guint registration_id,
4124 guint subtree_registration_id)
4128 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4132 CONNECTION_LOCK (connection);
4133 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4134 GUINT_TO_POINTER (registration_id)) == NULL)
4138 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4139 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4143 CONNECTION_UNLOCK (connection);
4148 /* ---------------------------------------------------------------------------------------------------- */
4152 GDBusConnection *connection;
4153 GDBusMessage *message;
4155 const gchar *property_name;
4156 const GDBusInterfaceVTable *vtable;
4157 GDBusInterfaceInfo *interface_info;
4158 const GDBusPropertyInfo *property_info;
4159 guint registration_id;
4160 guint subtree_registration_id;
4164 property_data_free (PropertyData *data)
4166 g_object_unref (data->connection);
4167 g_object_unref (data->message);
4171 /* called in thread where object was registered - no locks held */
4173 invoke_get_property_in_idle_cb (gpointer _data)
4175 PropertyData *data = _data;
4178 GDBusMessage *reply;
4180 if (has_object_been_unregistered (data->connection,
4181 data->registration_id,
4182 data->subtree_registration_id))
4184 reply = g_dbus_message_new_method_error (data->message,
4185 "org.freedesktop.DBus.Error.UnknownMethod",
4186 _("No such interface “org.freedesktop.DBus.Properties” on object at path %s"),
4187 g_dbus_message_get_path (data->message));
4188 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4189 g_object_unref (reply);
4194 value = data->vtable->get_property (data->connection,
4195 g_dbus_message_get_sender (data->message),
4196 g_dbus_message_get_path (data->message),
4197 data->interface_info->name,
4198 data->property_name,
4205 g_assert_no_error (error);
4207 g_variant_take_ref (value);
4208 reply = g_dbus_message_new_method_reply (data->message);
4209 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4210 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4211 g_variant_unref (value);
4212 g_object_unref (reply);
4216 gchar *dbus_error_name;
4217 g_assert (error != NULL);
4218 dbus_error_name = g_dbus_error_encode_gerror (error);
4219 reply = g_dbus_message_new_method_error_literal (data->message,
4222 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4223 g_free (dbus_error_name);
4224 g_error_free (error);
4225 g_object_unref (reply);
4232 /* called in thread where object was registered - no locks held */
4234 invoke_set_property_in_idle_cb (gpointer _data)
4236 PropertyData *data = _data;
4238 GDBusMessage *reply;
4244 g_variant_get (g_dbus_message_get_body (data->message),
4250 if (!data->vtable->set_property (data->connection,
4251 g_dbus_message_get_sender (data->message),
4252 g_dbus_message_get_path (data->message),
4253 data->interface_info->name,
4254 data->property_name,
4259 gchar *dbus_error_name;
4260 g_assert (error != NULL);
4261 dbus_error_name = g_dbus_error_encode_gerror (error);
4262 reply = g_dbus_message_new_method_error_literal (data->message,
4265 g_free (dbus_error_name);
4266 g_error_free (error);
4270 reply = g_dbus_message_new_method_reply (data->message);
4273 g_assert (reply != NULL);
4274 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4275 g_object_unref (reply);
4276 g_variant_unref (value);
4281 /* called in any thread with connection's lock held */
4283 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4284 GDBusMessage *message,
4285 guint registration_id,
4286 guint subtree_registration_id,
4288 GDBusInterfaceInfo *interface_info,
4289 const GDBusInterfaceVTable *vtable,
4290 GMainContext *main_context,
4294 const char *interface_name;
4295 const char *property_name;
4296 const GDBusPropertyInfo *property_info;
4297 GSource *idle_source;
4298 PropertyData *property_data;
4299 GDBusMessage *reply;
4304 g_variant_get (g_dbus_message_get_body (message),
4309 g_variant_get (g_dbus_message_get_body (message),
4318 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4320 property_info = NULL;
4322 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4323 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4324 if (property_info == NULL)
4326 reply = g_dbus_message_new_method_error (message,
4327 "org.freedesktop.DBus.Error.InvalidArgs",
4328 _("No such property “%s”"),
4330 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4331 g_object_unref (reply);
4336 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4338 reply = g_dbus_message_new_method_error (message,
4339 "org.freedesktop.DBus.Error.InvalidArgs",
4340 _("Property “%s” is not readable"),
4342 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4343 g_object_unref (reply);
4347 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4349 reply = g_dbus_message_new_method_error (message,
4350 "org.freedesktop.DBus.Error.InvalidArgs",
4351 _("Property “%s” is not writable"),
4353 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4354 g_object_unref (reply);
4363 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4364 * of the given value is wrong
4366 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4367 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4369 reply = g_dbus_message_new_method_error (message,
4370 "org.freedesktop.DBus.Error.InvalidArgs",
4371 _("Error setting property “%s”: Expected type “%s” but got “%s”"),
4372 property_name, property_info->signature,
4373 g_variant_get_type_string (value));
4374 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4375 g_variant_unref (value);
4376 g_object_unref (reply);
4381 g_variant_unref (value);
4384 /* If the vtable pointer for get_property() resp. set_property() is
4385 * NULL then dispatch the call via the method_call() handler.
4389 if (vtable->get_property == NULL)
4391 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4392 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4393 vtable, main_context, user_data);
4400 if (vtable->set_property == NULL)
4402 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4403 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4404 vtable, main_context, user_data);
4410 /* ok, got the property info - call user code in an idle handler */
4411 property_data = g_new0 (PropertyData, 1);
4412 property_data->connection = g_object_ref (connection);
4413 property_data->message = g_object_ref (message);
4414 property_data->user_data = user_data;
4415 property_data->property_name = property_name;
4416 property_data->vtable = vtable;
4417 property_data->interface_info = interface_info;
4418 property_data->property_info = property_info;
4419 property_data->registration_id = registration_id;
4420 property_data->subtree_registration_id = subtree_registration_id;
4422 idle_source = g_idle_source_new ();
4423 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4424 g_source_set_callback (idle_source,
4425 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4427 (GDestroyNotify) property_data_free);
4429 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4431 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4432 g_source_attach (idle_source, main_context);
4433 g_source_unref (idle_source);
4441 /* called in GDBusWorker thread with connection's lock held */
4443 handle_getset_property (GDBusConnection *connection,
4445 GDBusMessage *message,
4448 ExportedInterface *ei;
4450 const char *interface_name;
4451 const char *property_name;
4456 g_variant_get (g_dbus_message_get_body (message),
4461 g_variant_get (g_dbus_message_get_body (message),
4467 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4468 * no such interface registered
4470 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4473 GDBusMessage *reply;
4474 reply = g_dbus_message_new_method_error (message,
4475 "org.freedesktop.DBus.Error.InvalidArgs",
4476 _("No such interface “%s”"),
4478 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4479 g_object_unref (reply);
4484 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4497 /* ---------------------------------------------------------------------------------------------------- */
4501 GDBusConnection *connection;
4502 GDBusMessage *message;
4504 const GDBusInterfaceVTable *vtable;
4505 GDBusInterfaceInfo *interface_info;
4506 guint registration_id;
4507 guint subtree_registration_id;
4508 } PropertyGetAllData;
4511 property_get_all_data_free (PropertyData *data)
4513 g_object_unref (data->connection);
4514 g_object_unref (data->message);
4518 /* called in thread where object was registered - no locks held */
4520 invoke_get_all_properties_in_idle_cb (gpointer _data)
4522 PropertyGetAllData *data = _data;
4523 GVariantBuilder builder;
4524 GDBusMessage *reply;
4527 if (has_object_been_unregistered (data->connection,
4528 data->registration_id,
4529 data->subtree_registration_id))
4531 reply = g_dbus_message_new_method_error (data->message,
4532 "org.freedesktop.DBus.Error.UnknownMethod",
4533 _("No such interface “org.freedesktop.DBus.Properties” on object at path %s"),
4534 g_dbus_message_get_path (data->message));
4535 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4536 g_object_unref (reply);
4540 /* TODO: Right now we never fail this call - we just omit values if
4541 * a get_property() call is failing.
4543 * We could fail the whole call if just a single get_property() call
4544 * returns an error. We need clarification in the D-Bus spec about this.
4546 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4547 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4548 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4550 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4553 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4556 value = data->vtable->get_property (data->connection,
4557 g_dbus_message_get_sender (data->message),
4558 g_dbus_message_get_path (data->message),
4559 data->interface_info->name,
4560 property_info->name,
4567 g_variant_take_ref (value);
4568 g_variant_builder_add (&builder,
4570 property_info->name,
4572 g_variant_unref (value);
4574 g_variant_builder_close (&builder);
4576 reply = g_dbus_message_new_method_reply (data->message);
4577 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4578 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4579 g_object_unref (reply);
4586 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4590 if (!interface_info->properties)
4593 for (i = 0; interface_info->properties[i]; i++)
4594 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4600 /* called in any thread with connection's lock held */
4602 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4603 GDBusMessage *message,
4604 guint registration_id,
4605 guint subtree_registration_id,
4606 GDBusInterfaceInfo *interface_info,
4607 const GDBusInterfaceVTable *vtable,
4608 GMainContext *main_context,
4612 GSource *idle_source;
4613 PropertyGetAllData *property_get_all_data;
4620 /* If the vtable pointer for get_property() is NULL but we have a
4621 * non-zero number of readable properties, then dispatch the call via
4622 * the method_call() handler.
4624 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4626 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4627 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4628 vtable, main_context, user_data);
4633 /* ok, got the property info - call user in an idle handler */
4634 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4635 property_get_all_data->connection = g_object_ref (connection);
4636 property_get_all_data->message = g_object_ref (message);
4637 property_get_all_data->user_data = user_data;
4638 property_get_all_data->vtable = vtable;
4639 property_get_all_data->interface_info = interface_info;
4640 property_get_all_data->registration_id = registration_id;
4641 property_get_all_data->subtree_registration_id = subtree_registration_id;
4643 idle_source = g_idle_source_new ();
4644 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4645 g_source_set_callback (idle_source,
4646 invoke_get_all_properties_in_idle_cb,
4647 property_get_all_data,
4648 (GDestroyNotify) property_get_all_data_free);
4649 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4650 g_source_attach (idle_source, main_context);
4651 g_source_unref (idle_source);
4659 /* called in GDBusWorker thread with connection's lock held */
4661 handle_get_all_properties (GDBusConnection *connection,
4663 GDBusMessage *message)
4665 ExportedInterface *ei;
4667 const char *interface_name;
4671 g_variant_get (g_dbus_message_get_body (message),
4675 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4676 * no such interface registered
4678 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4681 GDBusMessage *reply;
4682 reply = g_dbus_message_new_method_error (message,
4683 "org.freedesktop.DBus.Error.InvalidArgs",
4684 _("No such interface “%s”"),
4686 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4687 g_object_unref (reply);
4692 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4704 /* ---------------------------------------------------------------------------------------------------- */
4706 static const gchar introspect_header[] =
4707 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4708 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4709 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4712 static const gchar introspect_tail[] =
4715 static const gchar introspect_properties_interface[] =
4716 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4717 " <method name=\"Get\">\n"
4718 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4719 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4720 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4722 " <method name=\"GetAll\">\n"
4723 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4724 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4726 " <method name=\"Set\">\n"
4727 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4728 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4729 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4731 " <signal name=\"PropertiesChanged\">\n"
4732 " <arg type=\"s\" name=\"interface_name\"/>\n"
4733 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4734 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4738 static const gchar introspect_introspectable_interface[] =
4739 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4740 " <method name=\"Introspect\">\n"
4741 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4744 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4745 " <method name=\"Ping\"/>\n"
4746 " <method name=\"GetMachineId\">\n"
4747 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4752 introspect_append_header (GString *s)
4754 g_string_append (s, introspect_header);
4758 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4760 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4766 begin = object_path + path_len;
4767 end = strchr (begin, '/');
4769 s = g_strndup (begin, end - begin);
4771 s = g_strdup (begin);
4773 if (!g_hash_table_contains (set, s))
4774 g_hash_table_add (set, s);
4780 /* TODO: we want a nicer public interface for this */
4781 /* called in any thread with connection's lock held */
4783 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4788 GHashTableIter hash_iter;
4789 const gchar *object_path;
4795 CONNECTION_ENSURE_LOCK (connection);
4797 path_len = strlen (path);
4801 set = g_hash_table_new (g_str_hash, g_str_equal);
4803 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4804 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4805 maybe_add_path (path, path_len, object_path, set);
4807 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4808 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4809 maybe_add_path (path, path_len, object_path, set);
4811 p = g_ptr_array_new ();
4812 keys = g_hash_table_get_keys (set);
4813 for (l = keys; l != NULL; l = l->next)
4814 g_ptr_array_add (p, l->data);
4815 g_hash_table_unref (set);
4818 g_ptr_array_add (p, NULL);
4819 ret = (gchar **) g_ptr_array_free (p, FALSE);
4823 /* called in any thread with connection's lock not held */
4825 g_dbus_connection_list_registered (GDBusConnection *connection,
4829 CONNECTION_LOCK (connection);
4830 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4831 CONNECTION_UNLOCK (connection);
4835 /* called in GDBusWorker thread with connection's lock held */
4837 handle_introspect (GDBusConnection *connection,
4839 GDBusMessage *message)
4843 GDBusMessage *reply;
4844 GHashTableIter hash_iter;
4845 ExportedInterface *ei;
4848 /* first the header with the standard interfaces */
4849 s = g_string_sized_new (sizeof (introspect_header) +
4850 sizeof (introspect_properties_interface) +
4851 sizeof (introspect_introspectable_interface) +
4852 sizeof (introspect_tail));
4853 introspect_append_header (s);
4854 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4855 "org.freedesktop.DBus.Properties"))
4856 g_string_append (s, introspect_properties_interface);
4858 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4859 "org.freedesktop.DBus.Introspectable"))
4860 g_string_append (s, introspect_introspectable_interface);
4862 /* then include the registered interfaces */
4863 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4864 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4865 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4867 /* finally include nodes registered below us */
4868 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4869 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4870 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4871 g_strfreev (registered);
4872 g_string_append (s, introspect_tail);
4874 reply = g_dbus_message_new_method_reply (message);
4875 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4876 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4877 g_object_unref (reply);
4878 g_string_free (s, TRUE);
4883 /* called in thread where object was registered - no locks held */
4885 call_in_idle_cb (gpointer user_data)
4887 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4888 GDBusInterfaceVTable *vtable;
4889 guint registration_id;
4890 guint subtree_registration_id;
4892 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4893 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4895 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4897 subtree_registration_id))
4899 GDBusMessage *reply;
4900 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4901 "org.freedesktop.DBus.Error.UnknownMethod",
4902 _("No such interface “%s” on object at path %s"),
4903 g_dbus_method_invocation_get_interface_name (invocation),
4904 g_dbus_method_invocation_get_object_path (invocation));
4905 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4906 g_object_unref (reply);
4910 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4911 g_assert (vtable != NULL && vtable->method_call != NULL);
4913 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4914 g_dbus_method_invocation_get_sender (invocation),
4915 g_dbus_method_invocation_get_object_path (invocation),
4916 g_dbus_method_invocation_get_interface_name (invocation),
4917 g_dbus_method_invocation_get_method_name (invocation),
4918 g_dbus_method_invocation_get_parameters (invocation),
4919 g_object_ref (invocation),
4920 g_dbus_method_invocation_get_user_data (invocation));
4926 /* called in GDBusWorker thread with connection's lock held */
4928 schedule_method_call (GDBusConnection *connection,
4929 GDBusMessage *message,
4930 guint registration_id,
4931 guint subtree_registration_id,
4932 const GDBusInterfaceInfo *interface_info,
4933 const GDBusMethodInfo *method_info,
4934 const GDBusPropertyInfo *property_info,
4935 GVariant *parameters,
4936 const GDBusInterfaceVTable *vtable,
4937 GMainContext *main_context,
4940 GDBusMethodInvocation *invocation;
4941 GSource *idle_source;
4943 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4944 g_dbus_message_get_path (message),
4945 g_dbus_message_get_interface (message),
4946 g_dbus_message_get_member (message),
4954 /* TODO: would be nicer with a real MethodData like we already
4955 * have PropertyData and PropertyGetAllData... */
4956 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4957 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4958 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4960 idle_source = g_idle_source_new ();
4961 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4962 g_source_set_callback (idle_source,
4966 g_source_set_name (idle_source, "[gio, " __FILE__ "] call_in_idle_cb");
4967 g_source_attach (idle_source, main_context);
4968 g_source_unref (idle_source);
4971 /* called in GDBusWorker thread with connection's lock held */
4973 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4974 GDBusMessage *message,
4975 guint registration_id,
4976 guint subtree_registration_id,
4977 GDBusInterfaceInfo *interface_info,
4978 const GDBusInterfaceVTable *vtable,
4979 GMainContext *main_context,
4982 GDBusMethodInfo *method_info;
4983 GDBusMessage *reply;
4984 GVariant *parameters;
4986 GVariantType *in_type;
4990 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4991 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4993 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4994 * error to the caller
4996 if (method_info == NULL)
4998 reply = g_dbus_message_new_method_error (message,
4999 "org.freedesktop.DBus.Error.UnknownMethod",
5000 _("No such method “%s”"),
5001 g_dbus_message_get_member (message));
5002 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5003 g_object_unref (reply);
5008 parameters = g_dbus_message_get_body (message);
5009 if (parameters == NULL)
5011 parameters = g_variant_new ("()");
5012 g_variant_ref_sink (parameters);
5016 g_variant_ref (parameters);
5019 /* Check that the incoming args are of the right type - if they are not, return
5020 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5022 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5023 if (!g_variant_is_of_type (parameters, in_type))
5027 type_string = g_variant_type_dup_string (in_type);
5029 reply = g_dbus_message_new_method_error (message,
5030 "org.freedesktop.DBus.Error.InvalidArgs",
5031 _("Type of message, “%s”, does not match expected type “%s”"),
5032 g_variant_get_type_string (parameters),
5034 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5035 g_variant_type_free (in_type);
5036 g_variant_unref (parameters);
5037 g_object_unref (reply);
5038 g_free (type_string);
5042 g_variant_type_free (in_type);
5044 /* schedule the call in idle */
5045 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5046 interface_info, method_info, NULL, parameters,
5047 vtable, main_context, user_data);
5048 g_variant_unref (parameters);
5055 /* ---------------------------------------------------------------------------------------------------- */
5057 /* called in GDBusWorker thread with connection's lock held */
5059 obj_message_func (GDBusConnection *connection,
5061 GDBusMessage *message)
5063 const gchar *interface_name;
5064 const gchar *member;
5065 const gchar *signature;
5070 interface_name = g_dbus_message_get_interface (message);
5071 member = g_dbus_message_get_member (message);
5072 signature = g_dbus_message_get_signature (message);
5074 /* see if we have an interface for handling this call */
5075 if (interface_name != NULL)
5077 ExportedInterface *ei;
5078 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5081 /* we do - invoke the handler in idle in the right thread */
5083 /* handle no vtable or handler being present */
5084 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5087 handled = validate_and_maybe_schedule_method_call (connection,
5099 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5100 g_strcmp0 (member, "Introspect") == 0 &&
5101 g_strcmp0 (signature, "") == 0)
5103 handled = handle_introspect (connection, eo, message);
5106 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5107 g_strcmp0 (member, "Get") == 0 &&
5108 g_strcmp0 (signature, "ss") == 0)
5110 handled = handle_getset_property (connection, eo, message, TRUE);
5113 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5114 g_strcmp0 (member, "Set") == 0 &&
5115 g_strcmp0 (signature, "ssv") == 0)
5117 handled = handle_getset_property (connection, eo, message, FALSE);
5120 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5121 g_strcmp0 (member, "GetAll") == 0 &&
5122 g_strcmp0 (signature, "s") == 0)
5124 handled = handle_get_all_properties (connection, eo, message);
5133 * g_dbus_connection_register_object:
5134 * @connection: a #GDBusConnection
5135 * @object_path: the object path to register at
5136 * @interface_info: introspection data for the interface
5137 * @vtable: (nullable): a #GDBusInterfaceVTable to call into or %NULL
5138 * @user_data: (nullable): data to pass to functions in @vtable
5139 * @user_data_free_func: function to call when the object path is unregistered
5140 * @error: return location for error or %NULL
5142 * Registers callbacks for exported objects at @object_path with the
5143 * D-Bus interface that is described in @interface_info.
5145 * Calls to functions in @vtable (and @user_data_free_func) will happen
5147 * [thread-default main context][g-main-context-push-thread-default]
5148 * of the thread you are calling this method from.
5150 * Note that all #GVariant values passed to functions in @vtable will match
5151 * the signature given in @interface_info - if a remote caller passes
5152 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5153 * is returned to the remote caller.
5155 * Additionally, if the remote caller attempts to invoke methods or
5156 * access properties not mentioned in @interface_info the
5157 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5158 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5159 * are returned to the caller.
5161 * It is considered a programming error if the
5162 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5163 * #GVariant of incorrect type.
5165 * If an existing callback is already registered at @object_path and
5166 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5168 * GDBus automatically implements the standard D-Bus interfaces
5169 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5170 * and org.freedesktop.Peer, so you don't have to implement those for the
5171 * objects you export. You can implement org.freedesktop.DBus.Properties
5172 * yourself, e.g. to handle getting and setting of properties asynchronously.
5174 * Note that the reference count on @interface_info will be
5175 * incremented by 1 (unless allocated statically, e.g. if the
5176 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5177 * as the object is exported. Also note that @vtable will be copied.
5179 * See this [server][gdbus-server] for an example of how to use this method.
5181 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5182 * that can be used with g_dbus_connection_unregister_object()
5187 g_dbus_connection_register_object (GDBusConnection *connection,
5188 const gchar *object_path,
5189 GDBusInterfaceInfo *interface_info,
5190 const GDBusInterfaceVTable *vtable,
5192 GDestroyNotify user_data_free_func,
5196 ExportedInterface *ei;
5199 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5200 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5201 g_return_val_if_fail (interface_info != NULL, 0);
5202 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5203 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5204 g_return_val_if_fail (check_initialized (connection), 0);
5208 CONNECTION_LOCK (connection);
5210 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5213 eo = g_new0 (ExportedObject, 1);
5214 eo->object_path = g_strdup (object_path);
5215 eo->connection = connection;
5216 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5219 (GDestroyNotify) exported_interface_free);
5220 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5223 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5229 _("An object is already exported for the interface %s at %s"),
5230 interface_info->name,
5235 ei = g_new0 (ExportedInterface, 1);
5236 ei->id = (guint) g_atomic_int_add (&_global_registration_id, 1); /* TODO: overflow etc. */
5238 ei->user_data = user_data;
5239 ei->user_data_free_func = user_data_free_func;
5240 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5241 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5242 g_dbus_interface_info_cache_build (ei->interface_info);
5243 ei->interface_name = g_strdup (interface_info->name);
5244 ei->context = g_main_context_ref_thread_default ();
5246 g_hash_table_insert (eo->map_if_name_to_ei,
5247 (gpointer) ei->interface_name,
5249 g_hash_table_insert (connection->map_id_to_ei,
5250 GUINT_TO_POINTER (ei->id),
5256 CONNECTION_UNLOCK (connection);
5262 * g_dbus_connection_unregister_object:
5263 * @connection: a #GDBusConnection
5264 * @registration_id: a registration id obtained from
5265 * g_dbus_connection_register_object()
5267 * Unregisters an object.
5269 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5274 g_dbus_connection_unregister_object (GDBusConnection *connection,
5275 guint registration_id)
5277 ExportedInterface *ei;
5281 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5282 g_return_val_if_fail (check_initialized (connection), FALSE);
5286 CONNECTION_LOCK (connection);
5288 ei = g_hash_table_lookup (connection->map_id_to_ei,
5289 GUINT_TO_POINTER (registration_id));
5295 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5296 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5297 /* unregister object path if we have no more exported interfaces */
5298 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5299 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5305 CONNECTION_UNLOCK (connection);
5311 GClosure *method_call_closure;
5312 GClosure *get_property_closure;
5313 GClosure *set_property_closure;
5314 } RegisterObjectData;
5316 static RegisterObjectData *
5317 register_object_data_new (GClosure *method_call_closure,
5318 GClosure *get_property_closure,
5319 GClosure *set_property_closure)
5321 RegisterObjectData *data;
5323 data = g_new0 (RegisterObjectData, 1);
5325 if (method_call_closure != NULL)
5327 data->method_call_closure = g_closure_ref (method_call_closure);
5328 g_closure_sink (method_call_closure);
5329 if (G_CLOSURE_NEEDS_MARSHAL (method_call_closure))
5330 g_closure_set_marshal (method_call_closure, g_cclosure_marshal_generic);
5333 if (get_property_closure != NULL)
5335 data->get_property_closure = g_closure_ref (get_property_closure);
5336 g_closure_sink (get_property_closure);
5337 if (G_CLOSURE_NEEDS_MARSHAL (get_property_closure))
5338 g_closure_set_marshal (get_property_closure, g_cclosure_marshal_generic);
5341 if (set_property_closure != NULL)
5343 data->set_property_closure = g_closure_ref (set_property_closure);
5344 g_closure_sink (set_property_closure);
5345 if (G_CLOSURE_NEEDS_MARSHAL (set_property_closure))
5346 g_closure_set_marshal (set_property_closure, g_cclosure_marshal_generic);
5353 register_object_free_func (gpointer user_data)
5355 RegisterObjectData *data = user_data;
5357 g_clear_pointer (&data->method_call_closure, g_closure_unref);
5358 g_clear_pointer (&data->get_property_closure, g_closure_unref);
5359 g_clear_pointer (&data->set_property_closure, g_closure_unref);
5365 register_with_closures_on_method_call (GDBusConnection *connection,
5366 const gchar *sender,
5367 const gchar *object_path,
5368 const gchar *interface_name,
5369 const gchar *method_name,
5370 GVariant *parameters,
5371 GDBusMethodInvocation *invocation,
5374 RegisterObjectData *data = user_data;
5375 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5377 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5378 g_value_set_object (¶ms[0], connection);
5380 g_value_init (¶ms[1], G_TYPE_STRING);
5381 g_value_set_string (¶ms[1], sender);
5383 g_value_init (¶ms[2], G_TYPE_STRING);
5384 g_value_set_string (¶ms[2], object_path);
5386 g_value_init (¶ms[3], G_TYPE_STRING);
5387 g_value_set_string (¶ms[3], interface_name);
5389 g_value_init (¶ms[4], G_TYPE_STRING);
5390 g_value_set_string (¶ms[4], method_name);
5392 g_value_init (¶ms[5], G_TYPE_VARIANT);
5393 g_value_set_variant (¶ms[5], parameters);
5395 g_value_init (¶ms[6], G_TYPE_DBUS_METHOD_INVOCATION);
5396 g_value_set_object (¶ms[6], invocation);
5398 g_closure_invoke (data->method_call_closure, NULL, G_N_ELEMENTS (params), params, NULL);
5400 g_value_unset (params + 0);
5401 g_value_unset (params + 1);
5402 g_value_unset (params + 2);
5403 g_value_unset (params + 3);
5404 g_value_unset (params + 4);
5405 g_value_unset (params + 5);
5406 g_value_unset (params + 6);
5410 register_with_closures_on_get_property (GDBusConnection *connection,
5411 const gchar *sender,
5412 const gchar *object_path,
5413 const gchar *interface_name,
5414 const gchar *property_name,
5418 RegisterObjectData *data = user_data;
5419 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5420 GValue result_value = G_VALUE_INIT;
5423 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5424 g_value_set_object (¶ms[0], connection);
5426 g_value_init (¶ms[1], G_TYPE_STRING);
5427 g_value_set_string (¶ms[1], sender);
5429 g_value_init (¶ms[2], G_TYPE_STRING);
5430 g_value_set_string (¶ms[2], object_path);
5432 g_value_init (¶ms[3], G_TYPE_STRING);
5433 g_value_set_string (¶ms[3], interface_name);
5435 g_value_init (¶ms[4], G_TYPE_STRING);
5436 g_value_set_string (¶ms[4], property_name);
5438 g_value_init (&result_value, G_TYPE_VARIANT);
5440 g_closure_invoke (data->get_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5442 result = g_value_get_variant (&result_value);
5444 g_variant_ref (result);
5446 g_value_unset (params + 0);
5447 g_value_unset (params + 1);
5448 g_value_unset (params + 2);
5449 g_value_unset (params + 3);
5450 g_value_unset (params + 4);
5451 g_value_unset (&result_value);
5454 g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5455 _("Unable to retrieve property %s.%s"),
5456 interface_name, property_name);
5462 register_with_closures_on_set_property (GDBusConnection *connection,
5463 const gchar *sender,
5464 const gchar *object_path,
5465 const gchar *interface_name,
5466 const gchar *property_name,
5471 RegisterObjectData *data = user_data;
5472 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5473 GValue result_value = G_VALUE_INIT;
5476 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5477 g_value_set_object (¶ms[0], connection);
5479 g_value_init (¶ms[1], G_TYPE_STRING);
5480 g_value_set_string (¶ms[1], sender);
5482 g_value_init (¶ms[2], G_TYPE_STRING);
5483 g_value_set_string (¶ms[2], object_path);
5485 g_value_init (¶ms[3], G_TYPE_STRING);
5486 g_value_set_string (¶ms[3], interface_name);
5488 g_value_init (¶ms[4], G_TYPE_STRING);
5489 g_value_set_string (¶ms[4], property_name);
5491 g_value_init (¶ms[5], G_TYPE_VARIANT);
5492 g_value_set_variant (¶ms[5], value);
5494 g_value_init (&result_value, G_TYPE_BOOLEAN);
5496 g_closure_invoke (data->set_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5498 result = g_value_get_boolean (&result_value);
5500 g_value_unset (params + 0);
5501 g_value_unset (params + 1);
5502 g_value_unset (params + 2);
5503 g_value_unset (params + 3);
5504 g_value_unset (params + 4);
5505 g_value_unset (params + 5);
5506 g_value_unset (&result_value);
5510 G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5511 _("Unable to set property %s.%s"),
5512 interface_name, property_name);
5518 * g_dbus_connection_register_object_with_closures: (rename-to g_dbus_connection_register_object)
5519 * @connection: A #GDBusConnection.
5520 * @object_path: The object path to register at.
5521 * @interface_info: Introspection data for the interface.
5522 * @method_call_closure: (nullable): #GClosure for handling incoming method calls.
5523 * @get_property_closure: (nullable): #GClosure for getting a property.
5524 * @set_property_closure: (nullable): #GClosure for setting a property.
5525 * @error: Return location for error or %NULL.
5527 * Version of g_dbus_connection_register_object() using closures instead of a
5528 * #GDBusInterfaceVTable for easier binding in other languages.
5530 * Returns: 0 if @error is set, otherwise a registration ID (never 0)
5531 * that can be used with g_dbus_connection_unregister_object() .
5536 g_dbus_connection_register_object_with_closures (GDBusConnection *connection,
5537 const gchar *object_path,
5538 GDBusInterfaceInfo *interface_info,
5539 GClosure *method_call_closure,
5540 GClosure *get_property_closure,
5541 GClosure *set_property_closure,
5544 RegisterObjectData *data;
5545 GDBusInterfaceVTable vtable =
5547 method_call_closure != NULL ? register_with_closures_on_method_call : NULL,
5548 get_property_closure != NULL ? register_with_closures_on_get_property : NULL,
5549 set_property_closure != NULL ? register_with_closures_on_set_property : NULL,
5553 data = register_object_data_new (method_call_closure, get_property_closure, set_property_closure);
5555 return g_dbus_connection_register_object (connection,
5560 register_object_free_func,
5564 /* ---------------------------------------------------------------------------------------------------- */
5567 * g_dbus_connection_emit_signal:
5568 * @connection: a #GDBusConnection
5569 * @destination_bus_name: (nullable): the unique bus name for the destination
5570 * for the signal or %NULL to emit to all listeners
5571 * @object_path: path of remote object
5572 * @interface_name: D-Bus interface to emit a signal on
5573 * @signal_name: the name of the signal to emit
5574 * @parameters: (nullable): a #GVariant tuple with parameters for the signal
5575 * or %NULL if not passing parameters
5576 * @error: Return location for error or %NULL
5580 * If the parameters GVariant is floating, it is consumed.
5582 * This can only fail if @parameters is not compatible with the D-Bus protocol
5583 * (%G_IO_ERROR_INVALID_ARGUMENT), or if @connection has been closed
5584 * (%G_IO_ERROR_CLOSED).
5586 * Returns: %TRUE unless @error is set
5591 g_dbus_connection_emit_signal (GDBusConnection *connection,
5592 const gchar *destination_bus_name,
5593 const gchar *object_path,
5594 const gchar *interface_name,
5595 const gchar *signal_name,
5596 GVariant *parameters,
5599 GDBusMessage *message;
5605 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5606 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5607 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5608 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5609 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5610 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5611 g_return_val_if_fail (check_initialized (connection), FALSE);
5613 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5615 _g_dbus_debug_print_lock ();
5616 g_print ("========================================================================\n"
5617 "GDBus-debug:Emission:\n"
5618 " >>>> SIGNAL EMISSION %s.%s()\n"
5620 " destination %s\n",
5621 interface_name, signal_name,
5623 destination_bus_name != NULL ? destination_bus_name : "(none)");
5624 _g_dbus_debug_print_unlock ();
5627 message = g_dbus_message_new_signal (object_path,
5631 if (destination_bus_name != NULL)
5632 g_dbus_message_set_header (message,
5633 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5634 g_variant_new_string (destination_bus_name));
5636 if (parameters != NULL)
5637 g_dbus_message_set_body (message, parameters);
5639 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5640 g_object_unref (message);
5646 add_call_flags (GDBusMessage *message,
5647 GDBusCallFlags flags)
5649 GDBusMessageFlags msg_flags = 0;
5651 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5652 msg_flags |= G_DBUS_MESSAGE_FLAGS_NO_AUTO_START;
5653 if (flags & G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
5654 msg_flags |= G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION;
5656 g_dbus_message_set_flags (message, msg_flags);
5660 decode_method_reply (GDBusMessage *reply,
5661 const gchar *method_name,
5662 const GVariantType *reply_type,
5663 GUnixFDList **out_fd_list,
5669 switch (g_dbus_message_get_message_type (reply))
5671 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5672 result = g_dbus_message_get_body (reply);
5675 result = g_variant_new ("()");
5676 g_variant_ref_sink (result);
5680 g_variant_ref (result);
5683 if (!g_variant_is_of_type (result, reply_type))
5685 gchar *type_string = g_variant_type_dup_string (reply_type);
5689 G_IO_ERROR_INVALID_ARGUMENT,
5690 _("Method “%s” returned type “%s”, but expected “%s”"),
5691 method_name, g_variant_get_type_string (result), type_string);
5693 g_variant_unref (result);
5694 g_free (type_string);
5701 if (out_fd_list != NULL)
5703 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5704 if (*out_fd_list != NULL)
5705 g_object_ref (*out_fd_list);
5711 case G_DBUS_MESSAGE_TYPE_ERROR:
5712 g_dbus_message_to_gerror (reply, error);
5716 g_assert_not_reached ();
5726 GVariantType *reply_type;
5727 gchar *method_name; /* for error message */
5729 GUnixFDList *fd_list;
5733 call_state_free (CallState *state)
5735 g_variant_type_free (state->reply_type);
5736 g_free (state->method_name);
5738 if (state->fd_list != NULL)
5739 g_object_unref (state->fd_list);
5740 g_slice_free (CallState, state);
5743 /* called in any thread, with the connection's lock not held */
5745 g_dbus_connection_call_done (GObject *source,
5746 GAsyncResult *result,
5749 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5750 GTask *task = user_data;
5751 CallState *state = g_task_get_task_data (task);
5752 GError *error = NULL;
5753 GDBusMessage *reply;
5754 GVariant *value = NULL;
5756 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5760 if (G_UNLIKELY (_g_dbus_debug_call ()))
5762 _g_dbus_debug_print_lock ();
5763 g_print ("========================================================================\n"
5764 "GDBus-debug:Call:\n"
5765 " <<<< ASYNC COMPLETE %s()",
5766 state->method_name);
5770 g_print (" (serial %d)\n"
5772 g_dbus_message_get_reply_serial (reply));
5780 _g_dbus_debug_print_unlock ();
5784 value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5787 g_task_return_error (task, error);
5789 g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5791 g_clear_object (&reply);
5792 g_object_unref (task);
5795 /* called in any thread, with the connection's lock not held */
5797 g_dbus_connection_call_internal (GDBusConnection *connection,
5798 const gchar *bus_name,
5799 const gchar *object_path,
5800 const gchar *interface_name,
5801 const gchar *method_name,
5802 GVariant *parameters,
5803 const GVariantType *reply_type,
5804 GDBusCallFlags flags,
5806 GUnixFDList *fd_list,
5807 GCancellable *cancellable,
5808 GAsyncReadyCallback callback,
5811 GDBusMessage *message;
5814 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5815 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5816 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5817 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5818 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5819 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5820 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5821 g_return_if_fail (check_initialized (connection));
5823 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5825 g_return_if_fail (fd_list == NULL);
5828 message = g_dbus_message_new_method_call (bus_name,
5832 add_call_flags (message, flags);
5833 if (parameters != NULL)
5834 g_dbus_message_set_body (message, parameters);
5837 if (fd_list != NULL)
5838 g_dbus_message_set_unix_fd_list (message, fd_list);
5841 /* If the user has no callback then we can just send the message with
5842 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5843 * the logic for processing the reply. If the service sends the reply
5844 * anyway then it will just be ignored.
5846 if (callback != NULL)
5851 state = g_slice_new0 (CallState);
5852 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5854 if (reply_type == NULL)
5855 reply_type = G_VARIANT_TYPE_ANY;
5857 state->reply_type = g_variant_type_copy (reply_type);
5859 task = g_task_new (connection, cancellable, callback, user_data);
5860 g_task_set_source_tag (task, g_dbus_connection_call_internal);
5861 g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5863 g_dbus_connection_send_message_with_reply (connection,
5865 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5869 g_dbus_connection_call_done,
5874 GDBusMessageFlags flags;
5876 flags = g_dbus_message_get_flags (message);
5877 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5878 g_dbus_message_set_flags (message, flags);
5880 g_dbus_connection_send_message (connection,
5882 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5886 if (G_UNLIKELY (_g_dbus_debug_call ()))
5888 _g_dbus_debug_print_lock ();
5889 g_print ("========================================================================\n"
5890 "GDBus-debug:Call:\n"
5891 " >>>> ASYNC %s.%s()\n"
5893 " owned by name %s (serial %d)\n",
5897 bus_name != NULL ? bus_name : "(none)",
5899 _g_dbus_debug_print_unlock ();
5902 if (message != NULL)
5903 g_object_unref (message);
5906 /* called in any thread, with the connection's lock not held */
5908 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5909 GUnixFDList **out_fd_list,
5917 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5918 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5919 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5921 task = G_TASK (res);
5922 state = g_task_get_task_data (task);
5924 ret = g_task_propagate_pointer (task, error);
5928 if (out_fd_list != NULL)
5929 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5933 /* called in any user thread, with the connection's lock not held */
5935 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5936 const gchar *bus_name,
5937 const gchar *object_path,
5938 const gchar *interface_name,
5939 const gchar *method_name,
5940 GVariant *parameters,
5941 const GVariantType *reply_type,
5942 GDBusCallFlags flags,
5944 GUnixFDList *fd_list,
5945 GUnixFDList **out_fd_list,
5946 GCancellable *cancellable,
5949 GDBusMessage *message;
5950 GDBusMessage *reply;
5952 GError *local_error;
5953 GDBusSendMessageFlags send_flags;
5959 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5960 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5961 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5962 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5963 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5964 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5965 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5967 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5969 g_return_val_if_fail (fd_list == NULL, NULL);
5971 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5973 if (!(flags & CALL_FLAGS_INITIALIZING))
5974 g_return_val_if_fail (check_initialized (connection), FALSE);
5976 if (reply_type == NULL)
5977 reply_type = G_VARIANT_TYPE_ANY;
5979 message = g_dbus_message_new_method_call (bus_name,
5983 add_call_flags (message, flags);
5984 if (parameters != NULL)
5985 g_dbus_message_set_body (message, parameters);
5988 if (fd_list != NULL)
5989 g_dbus_message_set_unix_fd_list (message, fd_list);
5992 if (G_UNLIKELY (_g_dbus_debug_call ()))
5994 _g_dbus_debug_print_lock ();
5995 g_print ("========================================================================\n"
5996 "GDBus-debug:Call:\n"
5997 " >>>> SYNC %s.%s()\n"
5999 " owned by name %s\n",
6003 bus_name != NULL ? bus_name : "(none)");
6004 _g_dbus_debug_print_unlock ();
6009 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
6011 /* translate from one flavour of flags to another... */
6012 if (flags & CALL_FLAGS_INITIALIZING)
6013 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
6015 reply = g_dbus_connection_send_message_with_reply_sync (connection,
6019 NULL, /* guint32 *out_serial */
6023 if (G_UNLIKELY (_g_dbus_debug_call ()))
6025 _g_dbus_debug_print_lock ();
6026 g_print ("========================================================================\n"
6027 "GDBus-debug:Call:\n"
6028 " <<<< SYNC COMPLETE %s.%s()\n"
6034 g_print ("SUCCESS\n");
6038 g_print ("FAILED: %s\n",
6039 local_error->message);
6041 _g_dbus_debug_print_unlock ();
6047 *error = local_error;
6049 g_error_free (local_error);
6053 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6056 if (message != NULL)
6057 g_object_unref (message);
6059 g_object_unref (reply);
6064 /* ---------------------------------------------------------------------------------------------------- */
6067 * g_dbus_connection_call:
6068 * @connection: a #GDBusConnection
6069 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6070 * @connection is not a message bus connection
6071 * @object_path: path of remote object
6072 * @interface_name: D-Bus interface to invoke method on
6073 * @method_name: the name of the method to invoke
6074 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6075 * or %NULL if not passing parameters
6076 * @reply_type: (nullable): the expected type of the reply (which will be a
6078 * @flags: flags from the #GDBusCallFlags enumeration
6079 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6080 * timeout or %G_MAXINT for no timeout
6081 * @cancellable: (nullable): a #GCancellable or %NULL
6082 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
6083 * is satisfied or %NULL if you don't care about the result of the
6085 * @user_data: the data to pass to @callback
6087 * Asynchronously invokes the @method_name method on the
6088 * @interface_name D-Bus interface on the remote object at
6089 * @object_path owned by @bus_name.
6091 * If @connection is closed then the operation will fail with
6092 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6093 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6094 * not compatible with the D-Bus protocol, the operation fails with
6095 * %G_IO_ERROR_INVALID_ARGUMENT.
6097 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6098 * error will be raised if it does not match. Said another way, if you give a @reply_type
6099 * then any non-%NULL return value will be of this type. Unless it’s
6100 * %G_VARIANT_TYPE_UNIT, the @reply_type will be a tuple containing one or more
6103 * If the @parameters #GVariant is floating, it is consumed. This allows
6104 * convenient 'inline' use of g_variant_new(), e.g.:
6105 * |[<!-- language="C" -->
6106 * g_dbus_connection_call (connection,
6107 * "org.freedesktop.StringThings",
6108 * "/org/freedesktop/StringThings",
6109 * "org.freedesktop.StringThings",
6111 * g_variant_new ("(ss)",
6115 * G_DBUS_CALL_FLAGS_NONE,
6118 * (GAsyncReadyCallback) two_strings_done,
6122 * This is an asynchronous method. When the operation is finished,
6123 * @callback will be invoked in the
6124 * [thread-default main context][g-main-context-push-thread-default]
6125 * of the thread you are calling this method from. You can then call
6126 * g_dbus_connection_call_finish() to get the result of the operation.
6127 * See g_dbus_connection_call_sync() for the synchronous version of this
6130 * If @callback is %NULL then the D-Bus method call message will be sent with
6131 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6136 g_dbus_connection_call (GDBusConnection *connection,
6137 const gchar *bus_name,
6138 const gchar *object_path,
6139 const gchar *interface_name,
6140 const gchar *method_name,
6141 GVariant *parameters,
6142 const GVariantType *reply_type,
6143 GDBusCallFlags flags,
6145 GCancellable *cancellable,
6146 GAsyncReadyCallback callback,
6149 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);
6153 * g_dbus_connection_call_finish:
6154 * @connection: a #GDBusConnection
6155 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6156 * @error: return location for error or %NULL
6158 * Finishes an operation started with g_dbus_connection_call().
6160 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6161 * #GVariant tuple with return values. Free with g_variant_unref().
6166 g_dbus_connection_call_finish (GDBusConnection *connection,
6170 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6174 * g_dbus_connection_call_sync:
6175 * @connection: a #GDBusConnection
6176 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6177 * @connection is not a message bus connection
6178 * @object_path: path of remote object
6179 * @interface_name: D-Bus interface to invoke method on
6180 * @method_name: the name of the method to invoke
6181 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6182 * or %NULL if not passing parameters
6183 * @reply_type: (nullable): the expected type of the reply, or %NULL
6184 * @flags: flags from the #GDBusCallFlags enumeration
6185 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6186 * timeout or %G_MAXINT for no timeout
6187 * @cancellable: (nullable): a #GCancellable or %NULL
6188 * @error: return location for error or %NULL
6190 * Synchronously invokes the @method_name method on the
6191 * @interface_name D-Bus interface on the remote object at
6192 * @object_path owned by @bus_name.
6194 * If @connection is closed then the operation will fail with
6195 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6196 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6197 * contains a value not compatible with the D-Bus protocol, the operation
6198 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6200 * If @reply_type is non-%NULL then the reply will be checked for having
6201 * this type and an error will be raised if it does not match. Said
6202 * another way, if you give a @reply_type then any non-%NULL return
6203 * value will be of this type.
6205 * If the @parameters #GVariant is floating, it is consumed.
6206 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6207 * |[<!-- language="C" -->
6208 * g_dbus_connection_call_sync (connection,
6209 * "org.freedesktop.StringThings",
6210 * "/org/freedesktop/StringThings",
6211 * "org.freedesktop.StringThings",
6213 * g_variant_new ("(ss)",
6217 * G_DBUS_CALL_FLAGS_NONE,
6223 * The calling thread is blocked until a reply is received. See
6224 * g_dbus_connection_call() for the asynchronous version of
6227 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6228 * #GVariant tuple with return values. Free with g_variant_unref().
6233 g_dbus_connection_call_sync (GDBusConnection *connection,
6234 const gchar *bus_name,
6235 const gchar *object_path,
6236 const gchar *interface_name,
6237 const gchar *method_name,
6238 GVariant *parameters,
6239 const GVariantType *reply_type,
6240 GDBusCallFlags flags,
6242 GCancellable *cancellable,
6245 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);
6248 /* ---------------------------------------------------------------------------------------------------- */
6253 * g_dbus_connection_call_with_unix_fd_list:
6254 * @connection: a #GDBusConnection
6255 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6256 * @connection is not a message bus connection
6257 * @object_path: path of remote object
6258 * @interface_name: D-Bus interface to invoke method on
6259 * @method_name: the name of the method to invoke
6260 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6261 * or %NULL if not passing parameters
6262 * @reply_type: (nullable): the expected type of the reply, or %NULL
6263 * @flags: flags from the #GDBusCallFlags enumeration
6264 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6265 * timeout or %G_MAXINT for no timeout
6266 * @fd_list: (nullable): a #GUnixFDList or %NULL
6267 * @cancellable: (nullable): a #GCancellable or %NULL
6268 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
6269 * satisfied or %NULL if you don't * care about the result of the
6271 * @user_data: The data to pass to @callback.
6273 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6275 * The file descriptors normally correspond to %G_VARIANT_TYPE_HANDLE
6276 * values in the body of the message. For example, if a message contains
6277 * two file descriptors, @fd_list would have length 2, and
6278 * `g_variant_new_handle (0)` and `g_variant_new_handle (1)` would appear
6279 * somewhere in the body of the message (not necessarily in that order!)
6280 * to represent the file descriptors at indexes 0 and 1 respectively.
6282 * When designing D-Bus APIs that are intended to be interoperable,
6283 * please note that non-GDBus implementations of D-Bus can usually only
6284 * access file descriptors if they are referenced in this way by a
6285 * value of type %G_VARIANT_TYPE_HANDLE in the body of the message.
6287 * This method is only available on UNIX.
6292 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6293 const gchar *bus_name,
6294 const gchar *object_path,
6295 const gchar *interface_name,
6296 const gchar *method_name,
6297 GVariant *parameters,
6298 const GVariantType *reply_type,
6299 GDBusCallFlags flags,
6301 GUnixFDList *fd_list,
6302 GCancellable *cancellable,
6303 GAsyncReadyCallback callback,
6306 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);
6310 * g_dbus_connection_call_with_unix_fd_list_finish:
6311 * @connection: a #GDBusConnection
6312 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6313 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6314 * g_dbus_connection_call_with_unix_fd_list()
6315 * @error: return location for error or %NULL
6317 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6319 * The file descriptors normally correspond to %G_VARIANT_TYPE_HANDLE
6320 * values in the body of the message. For example,
6321 * if g_variant_get_handle() returns 5, that is intended to be a reference
6322 * to the file descriptor that can be accessed by
6323 * `g_unix_fd_list_get (*out_fd_list, 5, ...)`.
6325 * When designing D-Bus APIs that are intended to be interoperable,
6326 * please note that non-GDBus implementations of D-Bus can usually only
6327 * access file descriptors if they are referenced in this way by a
6328 * value of type %G_VARIANT_TYPE_HANDLE in the body of the message.
6330 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6331 * #GVariant tuple with return values. Free with g_variant_unref().
6336 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6337 GUnixFDList **out_fd_list,
6341 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6345 * g_dbus_connection_call_with_unix_fd_list_sync:
6346 * @connection: a #GDBusConnection
6347 * @bus_name: (nullable): a unique or well-known bus name or %NULL
6348 * if @connection is not a message bus connection
6349 * @object_path: path of remote object
6350 * @interface_name: D-Bus interface to invoke method on
6351 * @method_name: the name of the method to invoke
6352 * @parameters: (nullable): a #GVariant tuple with parameters for
6353 * the method or %NULL if not passing parameters
6354 * @reply_type: (nullable): the expected type of the reply, or %NULL
6355 * @flags: flags from the #GDBusCallFlags enumeration
6356 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6357 * timeout or %G_MAXINT for no timeout
6358 * @fd_list: (nullable): a #GUnixFDList or %NULL
6359 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6360 * @cancellable: (nullable): a #GCancellable or %NULL
6361 * @error: return location for error or %NULL
6363 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6364 * See g_dbus_connection_call_with_unix_fd_list() and
6365 * g_dbus_connection_call_with_unix_fd_list_finish() for more details.
6367 * This method is only available on UNIX.
6369 * Returns: (transfer full): %NULL if @error is set. Otherwise a non-floating
6370 * #GVariant tuple with return values. Free with g_variant_unref().
6375 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6376 const gchar *bus_name,
6377 const gchar *object_path,
6378 const gchar *interface_name,
6379 const gchar *method_name,
6380 GVariant *parameters,
6381 const GVariantType *reply_type,
6382 GDBusCallFlags flags,
6384 GUnixFDList *fd_list,
6385 GUnixFDList **out_fd_list,
6386 GCancellable *cancellable,
6389 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);
6392 #endif /* G_OS_UNIX */
6394 /* ---------------------------------------------------------------------------------------------------- */
6396 struct ExportedSubtree
6400 GDBusConnection *connection;
6401 GDBusSubtreeVTable *vtable;
6402 GDBusSubtreeFlags flags;
6404 GMainContext *context;
6406 GDestroyNotify user_data_free_func;
6410 exported_subtree_free (ExportedSubtree *es)
6412 call_destroy_notify (es->context,
6413 es->user_data_free_func,
6416 g_main_context_unref (es->context);
6418 _g_dbus_subtree_vtable_free (es->vtable);
6419 g_free (es->object_path);
6423 /* called without lock held in the thread where the caller registered
6427 handle_subtree_introspect (GDBusConnection *connection,
6428 ExportedSubtree *es,
6429 GDBusMessage *message)
6433 GDBusMessage *reply;
6436 const gchar *sender;
6437 const gchar *requested_object_path;
6438 const gchar *requested_node;
6439 GDBusInterfaceInfo **interfaces;
6441 gchar **subnode_paths;
6442 gboolean has_properties_interface;
6443 gboolean has_introspectable_interface;
6447 requested_object_path = g_dbus_message_get_path (message);
6448 sender = g_dbus_message_get_sender (message);
6449 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6451 s = g_string_new (NULL);
6452 introspect_append_header (s);
6454 /* Strictly we don't need the children in dynamic mode, but we avoid the
6455 * conditionals to preserve code clarity
6457 children = es->vtable->enumerate (es->connection,
6464 requested_node = strrchr (requested_object_path, '/') + 1;
6466 /* Assert existence of object if we are not dynamic */
6467 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6468 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6473 requested_node = NULL;
6476 interfaces = es->vtable->introspect (es->connection,
6481 if (interfaces != NULL)
6483 has_properties_interface = FALSE;
6484 has_introspectable_interface = FALSE;
6486 for (n = 0; interfaces[n] != NULL; n++)
6488 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6489 has_properties_interface = TRUE;
6490 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6491 has_introspectable_interface = TRUE;
6493 if (!has_properties_interface)
6494 g_string_append (s, introspect_properties_interface);
6495 if (!has_introspectable_interface)
6496 g_string_append (s, introspect_introspectable_interface);
6498 for (n = 0; interfaces[n] != NULL; n++)
6500 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6501 g_dbus_interface_info_unref (interfaces[n]);
6503 g_free (interfaces);
6506 /* then include <node> entries from the Subtree for the root */
6509 for (n = 0; children != NULL && children[n] != NULL; n++)
6510 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6513 /* finally include nodes registered below us */
6514 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6515 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6516 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6517 g_strfreev (subnode_paths);
6519 g_string_append (s, "</node>\n");
6521 reply = g_dbus_message_new_method_reply (message);
6522 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6523 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6524 g_object_unref (reply);
6529 g_string_free (s, TRUE);
6530 g_strfreev (children);
6534 /* called without lock held in the thread where the caller registered
6538 handle_subtree_method_invocation (GDBusConnection *connection,
6539 ExportedSubtree *es,
6540 GDBusMessage *message)
6543 const gchar *sender;
6544 const gchar *interface_name;
6545 const gchar *member;
6546 const gchar *signature;
6547 const gchar *requested_object_path;
6548 const gchar *requested_node;
6550 GDBusInterfaceInfo *interface_info;
6551 const GDBusInterfaceVTable *interface_vtable;
6552 gpointer interface_user_data;
6554 GDBusInterfaceInfo **interfaces;
6555 gboolean is_property_get;
6556 gboolean is_property_set;
6557 gboolean is_property_get_all;
6562 requested_object_path = g_dbus_message_get_path (message);
6563 sender = g_dbus_message_get_sender (message);
6564 interface_name = g_dbus_message_get_interface (message);
6565 member = g_dbus_message_get_member (message);
6566 signature = g_dbus_message_get_signature (message);
6567 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6569 is_property_get = FALSE;
6570 is_property_set = FALSE;
6571 is_property_get_all = FALSE;
6572 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6574 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6575 is_property_get = TRUE;
6576 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6577 is_property_set = TRUE;
6578 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6579 is_property_get_all = TRUE;
6584 requested_node = strrchr (requested_object_path, '/') + 1;
6586 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6588 /* We don't want to dispatch to unenumerated
6589 * nodes, so ensure that the child exists.
6594 children = es->vtable->enumerate (es->connection,
6599 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6600 g_strfreev (children);
6608 requested_node = NULL;
6611 /* get introspection data for the node */
6612 interfaces = es->vtable->introspect (es->connection,
6614 requested_object_path,
6618 if (interfaces == NULL)
6621 interface_info = NULL;
6622 for (n = 0; interfaces[n] != NULL; n++)
6624 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6625 interface_info = interfaces[n];
6628 /* dispatch the call if the user wants to handle it */
6629 if (interface_info != NULL)
6631 /* figure out where to dispatch the method call */
6632 interface_user_data = NULL;
6633 interface_vtable = es->vtable->dispatch (es->connection,
6638 &interface_user_data,
6640 if (interface_vtable == NULL)
6643 CONNECTION_LOCK (connection);
6644 handled = validate_and_maybe_schedule_method_call (es->connection,
6651 interface_user_data);
6652 CONNECTION_UNLOCK (connection);
6654 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6655 else if (is_property_get || is_property_set || is_property_get_all)
6657 if (is_property_get)
6658 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6659 else if (is_property_set)
6660 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6661 else if (is_property_get_all)
6662 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6664 g_assert_not_reached ();
6666 /* see if the object supports this interface at all */
6667 for (n = 0; interfaces[n] != NULL; n++)
6669 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6670 interface_info = interfaces[n];
6673 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6674 * claims it won't support the interface
6676 if (interface_info == NULL)
6678 GDBusMessage *reply;
6679 reply = g_dbus_message_new_method_error (message,
6680 "org.freedesktop.DBus.Error.InvalidArgs",
6681 _("No such interface “%s”"),
6683 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6684 g_object_unref (reply);
6689 /* figure out where to dispatch the property get/set/getall calls */
6690 interface_user_data = NULL;
6691 interface_vtable = es->vtable->dispatch (es->connection,
6696 &interface_user_data,
6698 if (interface_vtable == NULL)
6700 g_warning ("The subtree introspection function indicates that '%s' "
6701 "is a valid interface name, but calling the dispatch "
6702 "function on that interface gave us NULL", interface_name);
6706 if (is_property_get || is_property_set)
6708 CONNECTION_LOCK (connection);
6709 handled = validate_and_maybe_schedule_property_getset (es->connection,
6717 interface_user_data);
6718 CONNECTION_UNLOCK (connection);
6720 else if (is_property_get_all)
6722 CONNECTION_LOCK (connection);
6723 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6730 interface_user_data);
6731 CONNECTION_UNLOCK (connection);
6736 if (interfaces != NULL)
6738 for (n = 0; interfaces[n] != NULL; n++)
6739 g_dbus_interface_info_unref (interfaces[n]);
6740 g_free (interfaces);
6748 GDBusMessage *message;
6749 ExportedSubtree *es;
6750 } SubtreeDeferredData;
6753 subtree_deferred_data_free (SubtreeDeferredData *data)
6755 g_object_unref (data->message);
6759 /* called without lock held in the thread where the caller registered the subtree */
6761 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6763 SubtreeDeferredData *data = _data;
6768 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6769 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6770 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6771 handled = handle_subtree_introspect (data->es->connection,
6775 handled = handle_subtree_method_invocation (data->es->connection,
6781 CONNECTION_LOCK (data->es->connection);
6782 handled = handle_generic_unlocked (data->es->connection, data->message);
6783 CONNECTION_UNLOCK (data->es->connection);
6786 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6789 GDBusMessage *reply;
6790 reply = g_dbus_message_new_method_error (data->message,
6791 "org.freedesktop.DBus.Error.UnknownMethod",
6792 _("Method “%s” on interface “%s” with signature “%s” does not exist"),
6793 g_dbus_message_get_member (data->message),
6794 g_dbus_message_get_interface (data->message),
6795 g_dbus_message_get_signature (data->message));
6796 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6797 g_object_unref (reply);
6803 /* called in GDBusWorker thread with connection's lock held */
6805 subtree_message_func (GDBusConnection *connection,
6806 ExportedSubtree *es,
6807 GDBusMessage *message)
6809 GSource *idle_source;
6810 SubtreeDeferredData *data;
6812 data = g_new0 (SubtreeDeferredData, 1);
6813 data->message = g_object_ref (message);
6816 /* defer this call to an idle handler in the right thread */
6817 idle_source = g_idle_source_new ();
6818 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6819 g_source_set_callback (idle_source,
6820 process_subtree_vtable_message_in_idle_cb,
6822 (GDestroyNotify) subtree_deferred_data_free);
6823 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6824 g_source_attach (idle_source, es->context);
6825 g_source_unref (idle_source);
6827 /* since we own the entire subtree, handlers for objects not in the subtree have been
6828 * tried already by libdbus-1 - so we just need to ensure that we're always going
6829 * to reply to the message
6835 * g_dbus_connection_register_subtree:
6836 * @connection: a #GDBusConnection
6837 * @object_path: the object path to register the subtree at
6838 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6839 * dispatch nodes in the subtree
6840 * @flags: flags used to fine tune the behavior of the subtree
6841 * @user_data: data to pass to functions in @vtable
6842 * @user_data_free_func: function to call when the subtree is unregistered
6843 * @error: return location for error or %NULL
6845 * Registers a whole subtree of dynamic objects.
6847 * The @enumerate and @introspection functions in @vtable are used to
6848 * convey, to remote callers, what nodes exist in the subtree rooted
6851 * When handling remote calls into any node in the subtree, first the
6852 * @enumerate function is used to check if the node exists. If the node exists
6853 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6854 * the @introspection function is used to check if the node supports the
6855 * requested method. If so, the @dispatch function is used to determine
6856 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6857 * #gpointer will be used to call into the interface vtable for processing
6860 * All calls into user-provided code will be invoked in the
6861 * [thread-default main context][g-main-context-push-thread-default]
6862 * of the thread you are calling this method from.
6864 * If an existing subtree is already registered at @object_path or
6865 * then @error is set to #G_IO_ERROR_EXISTS.
6867 * Note that it is valid to register regular objects (using
6868 * g_dbus_connection_register_object()) in a subtree registered with
6869 * g_dbus_connection_register_subtree() - if so, the subtree handler
6870 * is tried as the last resort. One way to think about a subtree
6871 * handler is to consider it a fallback handler for object paths not
6872 * registered via g_dbus_connection_register_object() or other bindings.
6874 * Note that @vtable will be copied so you cannot change it after
6877 * See this [server][gdbus-subtree-server] for an example of how to use
6880 * Returns: 0 if @error is set, otherwise a subtree registration ID (never 0)
6881 * that can be used with g_dbus_connection_unregister_subtree()
6886 g_dbus_connection_register_subtree (GDBusConnection *connection,
6887 const gchar *object_path,
6888 const GDBusSubtreeVTable *vtable,
6889 GDBusSubtreeFlags flags,
6891 GDestroyNotify user_data_free_func,
6895 ExportedSubtree *es;
6897 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6898 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6899 g_return_val_if_fail (vtable != NULL, 0);
6900 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6901 g_return_val_if_fail (check_initialized (connection), 0);
6905 CONNECTION_LOCK (connection);
6907 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6913 _("A subtree is already exported for %s"),
6918 es = g_new0 (ExportedSubtree, 1);
6919 es->object_path = g_strdup (object_path);
6920 es->connection = connection;
6922 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6924 es->id = (guint) g_atomic_int_add (&_global_subtree_registration_id, 1); /* TODO: overflow etc. */
6925 es->user_data = user_data;
6926 es->user_data_free_func = user_data_free_func;
6927 es->context = g_main_context_ref_thread_default ();
6929 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6930 g_hash_table_insert (connection->map_id_to_es,
6931 GUINT_TO_POINTER (es->id),
6937 CONNECTION_UNLOCK (connection);
6942 /* ---------------------------------------------------------------------------------------------------- */
6945 * g_dbus_connection_unregister_subtree:
6946 * @connection: a #GDBusConnection
6947 * @registration_id: a subtree registration id obtained from
6948 * g_dbus_connection_register_subtree()
6950 * Unregisters a subtree.
6952 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6957 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6958 guint registration_id)
6960 ExportedSubtree *es;
6963 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6964 g_return_val_if_fail (check_initialized (connection), FALSE);
6968 CONNECTION_LOCK (connection);
6970 es = g_hash_table_lookup (connection->map_id_to_es,
6971 GUINT_TO_POINTER (registration_id));
6975 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6976 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6981 CONNECTION_UNLOCK (connection);
6986 /* ---------------------------------------------------------------------------------------------------- */
6988 /* may be called in any thread, with connection's lock held */
6990 handle_generic_ping_unlocked (GDBusConnection *connection,
6991 const gchar *object_path,
6992 GDBusMessage *message)
6994 GDBusMessage *reply;
6995 reply = g_dbus_message_new_method_reply (message);
6996 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6997 g_object_unref (reply);
7000 /* may be called in any thread, with connection's lock held */
7002 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
7003 const gchar *object_path,
7004 GDBusMessage *message)
7006 GDBusMessage *reply;
7009 if (connection->machine_id == NULL)
7014 connection->machine_id = _g_dbus_get_machine_id (&error);
7015 if (connection->machine_id == NULL)
7017 reply = g_dbus_message_new_method_error_literal (message,
7018 "org.freedesktop.DBus.Error.Failed",
7020 g_error_free (error);
7026 reply = g_dbus_message_new_method_reply (message);
7027 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
7029 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7030 g_object_unref (reply);
7033 /* may be called in any thread, with connection's lock held */
7035 handle_generic_introspect_unlocked (GDBusConnection *connection,
7036 const gchar *object_path,
7037 GDBusMessage *message)
7042 GDBusMessage *reply;
7044 /* first the header */
7045 s = g_string_new (NULL);
7046 introspect_append_header (s);
7048 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7049 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7050 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7051 g_strfreev (registered);
7052 g_string_append (s, "</node>\n");
7054 reply = g_dbus_message_new_method_reply (message);
7055 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7056 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7057 g_object_unref (reply);
7058 g_string_free (s, TRUE);
7061 /* may be called in any thread, with connection's lock held */
7063 handle_generic_unlocked (GDBusConnection *connection,
7064 GDBusMessage *message)
7067 const gchar *interface_name;
7068 const gchar *member;
7069 const gchar *signature;
7072 CONNECTION_ENSURE_LOCK (connection);
7076 interface_name = g_dbus_message_get_interface (message);
7077 member = g_dbus_message_get_member (message);
7078 signature = g_dbus_message_get_signature (message);
7079 path = g_dbus_message_get_path (message);
7081 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7082 g_strcmp0 (member, "Introspect") == 0 &&
7083 g_strcmp0 (signature, "") == 0)
7085 handle_generic_introspect_unlocked (connection, path, message);
7088 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7089 g_strcmp0 (member, "Ping") == 0 &&
7090 g_strcmp0 (signature, "") == 0)
7092 handle_generic_ping_unlocked (connection, path, message);
7095 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7096 g_strcmp0 (member, "GetMachineId") == 0 &&
7097 g_strcmp0 (signature, "") == 0)
7099 handle_generic_get_machine_id_unlocked (connection, path, message);
7106 /* ---------------------------------------------------------------------------------------------------- */
7108 /* called in GDBusWorker thread with connection's lock held */
7110 distribute_method_call (GDBusConnection *connection,
7111 GDBusMessage *message)
7113 GDBusMessage *reply;
7115 ExportedSubtree *es;
7116 const gchar *object_path;
7117 const gchar *interface_name;
7118 const gchar *member;
7120 gchar *subtree_path;
7123 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7125 interface_name = g_dbus_message_get_interface (message);
7126 member = g_dbus_message_get_member (message);
7127 path = g_dbus_message_get_path (message);
7128 subtree_path = g_strdup (path);
7129 needle = strrchr (subtree_path, '/');
7130 if (needle != NULL && needle != subtree_path)
7136 g_free (subtree_path);
7137 subtree_path = NULL;
7141 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7143 _g_dbus_debug_print_lock ();
7144 g_print ("========================================================================\n"
7145 "GDBus-debug:Incoming:\n"
7146 " <<<< METHOD INVOCATION %s.%s()\n"
7148 " invoked by name %s\n"
7150 interface_name, member,
7152 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7153 g_dbus_message_get_serial (message));
7154 _g_dbus_debug_print_unlock ();
7157 object_path = g_dbus_message_get_path (message);
7158 g_assert (object_path != NULL);
7160 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7163 if (obj_message_func (connection, eo, message))
7167 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7170 if (subtree_message_func (connection, es, message))
7174 if (subtree_path != NULL)
7176 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7179 if (subtree_message_func (connection, es, message))
7184 if (handle_generic_unlocked (connection, message))
7187 /* if we end up here, the message has not been not handled - so return an error saying this */
7188 reply = g_dbus_message_new_method_error (message,
7189 "org.freedesktop.DBus.Error.UnknownMethod",
7190 _("No such interface “%s” on object at path %s"),
7193 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7194 g_object_unref (reply);
7197 g_free (subtree_path);
7200 /* ---------------------------------------------------------------------------------------------------- */
7202 /* Called in any user thread, with the message_bus_lock held. */
7204 message_bus_get_singleton (GBusType bus_type,
7208 const gchar *starter_bus;
7214 case G_BUS_TYPE_SESSION:
7215 ret = &the_session_bus;
7218 case G_BUS_TYPE_SYSTEM:
7219 ret = &the_system_bus;
7222 case G_BUS_TYPE_STARTER:
7223 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7224 if (g_strcmp0 (starter_bus, "session") == 0)
7226 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7229 else if (g_strcmp0 (starter_bus, "system") == 0)
7231 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7236 if (starter_bus != NULL)
7240 G_IO_ERROR_INVALID_ARGUMENT,
7241 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7242 " — unknown value “%s”"),
7247 g_set_error_literal (error,
7249 G_IO_ERROR_INVALID_ARGUMENT,
7250 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7251 "variable is not set"));
7257 g_assert_not_reached ();
7265 /* Called in any user thread, without holding locks. */
7266 static GDBusConnection *
7267 get_uninitialized_connection (GBusType bus_type,
7268 GCancellable *cancellable,
7271 GWeakRef *singleton;
7272 GDBusConnection *ret;
7276 G_LOCK (message_bus_lock);
7277 singleton = message_bus_get_singleton (bus_type, error);
7278 if (singleton == NULL)
7281 ret = g_weak_ref_get (singleton);
7286 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7287 if (address == NULL)
7289 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7291 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7292 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7293 "exit-on-close", TRUE,
7296 g_weak_ref_set (singleton, ret);
7300 g_assert (ret != NULL);
7303 G_UNLOCK (message_bus_lock);
7307 /* May be called from any thread. Must not hold message_bus_lock. */
7309 _g_bus_get_singleton_if_exists (GBusType bus_type)
7311 GWeakRef *singleton;
7312 GDBusConnection *ret = NULL;
7314 G_LOCK (message_bus_lock);
7315 singleton = message_bus_get_singleton (bus_type, NULL);
7316 if (singleton == NULL)
7319 ret = g_weak_ref_get (singleton);
7322 G_UNLOCK (message_bus_lock);
7326 /* May be called from any thread. Must not hold message_bus_lock. */
7328 _g_bus_forget_singleton (GBusType bus_type)
7330 GWeakRef *singleton;
7332 G_LOCK (message_bus_lock);
7334 singleton = message_bus_get_singleton (bus_type, NULL);
7336 if (singleton != NULL)
7337 g_weak_ref_set (singleton, NULL);
7339 G_UNLOCK (message_bus_lock);
7344 * @bus_type: a #GBusType
7345 * @cancellable: (nullable): a #GCancellable or %NULL
7346 * @error: return location for error or %NULL
7348 * Synchronously connects to the message bus specified by @bus_type.
7349 * Note that the returned object may shared with other callers,
7350 * e.g. if two separate parts of a process calls this function with
7351 * the same @bus_type, they will share the same object.
7353 * This is a synchronous failable function. See g_bus_get() and
7354 * g_bus_get_finish() for the asynchronous version.
7356 * The returned object is a singleton, that is, shared with other
7357 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7358 * event that you need a private message bus connection, use
7359 * g_dbus_address_get_for_bus_sync() and
7360 * g_dbus_connection_new_for_address().
7362 * Note that the returned #GDBusConnection object will (usually) have
7363 * the #GDBusConnection:exit-on-close property set to %TRUE.
7365 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7366 * Free with g_object_unref().
7371 g_bus_get_sync (GBusType bus_type,
7372 GCancellable *cancellable,
7375 GDBusConnection *connection;
7377 _g_dbus_initialize ();
7379 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7381 connection = get_uninitialized_connection (bus_type, cancellable, error);
7382 if (connection == NULL)
7385 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7387 g_object_unref (connection);
7396 bus_get_async_initable_cb (GObject *source_object,
7400 GTask *task = user_data;
7401 GError *error = NULL;
7403 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7407 g_assert (error != NULL);
7408 g_task_return_error (task, error);
7409 g_object_unref (source_object);
7413 g_task_return_pointer (task, source_object, g_object_unref);
7415 g_object_unref (task);
7420 * @bus_type: a #GBusType
7421 * @cancellable: (nullable): a #GCancellable or %NULL
7422 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7423 * @user_data: the data to pass to @callback
7425 * Asynchronously connects to the message bus specified by @bus_type.
7427 * When the operation is finished, @callback will be invoked. You can
7428 * then call g_bus_get_finish() to get the result of the operation.
7430 * This is an asynchronous failable function. See g_bus_get_sync() for
7431 * the synchronous version.
7436 g_bus_get (GBusType bus_type,
7437 GCancellable *cancellable,
7438 GAsyncReadyCallback callback,
7441 GDBusConnection *connection;
7443 GError *error = NULL;
7445 _g_dbus_initialize ();
7447 task = g_task_new (NULL, cancellable, callback, user_data);
7448 g_task_set_source_tag (task, g_bus_get);
7450 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7451 if (connection == NULL)
7453 g_assert (error != NULL);
7454 g_task_return_error (task, error);
7455 g_object_unref (task);
7459 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7462 bus_get_async_initable_cb,
7469 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7471 * @error: return location for error or %NULL
7473 * Finishes an operation started with g_bus_get().
7475 * The returned object is a singleton, that is, shared with other
7476 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7477 * event that you need a private message bus connection, use
7478 * g_dbus_address_get_for_bus_sync() and
7479 * g_dbus_connection_new_for_address().
7481 * Note that the returned #GDBusConnection object will (usually) have
7482 * the #GDBusConnection:exit-on-close property set to %TRUE.
7484 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7485 * Free with g_object_unref().
7490 g_bus_get_finish (GAsyncResult *res,
7493 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7494 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7496 return g_task_propagate_pointer (G_TASK (res), error);
7499 /* ---------------------------------------------------------------------------------------------------- */