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"
113 #include "gstrfuncsprivate.h"
115 #include "gmarshal-internal.h"
118 #include "gunixconnection.h"
119 #include "gunixfdmessage.h"
122 #include "glibintl.h"
125 * SECTION:gdbusconnection
126 * @short_description: D-Bus Connections
127 * @include: gio/gio.h
129 * The #GDBusConnection type is used for D-Bus connections to remote
130 * peers such as a message buses. It is a low-level API that offers a
131 * lot of flexibility. For instance, it lets you establish a connection
132 * over any transport that can by represented as a #GIOStream.
134 * This class is rarely used directly in D-Bus clients. If you are writing
135 * a D-Bus client, it is often easier to use the g_bus_own_name(),
136 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
138 * As an exception to the usual GLib rule that a particular object must not
139 * be used by two threads at the same time, #GDBusConnection's methods may be
140 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
141 * can safely return the same #GDBusConnection when called from any thread.
143 * Most of the ways to obtain a #GDBusConnection automatically initialize it
144 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
145 * g_bus_get(), and the synchronous versions of those methods, give you an
146 * initialized connection. Language bindings for GIO should use
147 * g_initable_new() or g_async_initable_new_async(), which also initialize the
150 * If you construct an uninitialized #GDBusConnection, such as via
151 * g_object_new(), you must initialize it via g_initable_init() or
152 * g_async_initable_init_async() before using its methods or properties.
153 * Calling methods or accessing properties on a #GDBusConnection that has not
154 * completed initialization successfully is considered to be invalid, and leads
155 * to undefined behaviour. In particular, if initialization fails with a
156 * #GError, the only valid thing you can do with that #GDBusConnection is to
157 * free it with g_object_unref().
159 * ## An example D-Bus server # {#gdbus-server}
161 * Here is an example for a D-Bus server:
162 * [gdbus-example-server.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-server.c)
164 * ## An example for exporting a subtree # {#gdbus-subtree-server}
166 * Here is an example for exporting a subtree:
167 * [gdbus-example-subtree.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-subtree.c)
169 * ## An example for file descriptor passing # {#gdbus-unix-fd-client}
171 * Here is an example for passing UNIX file descriptors:
172 * [gdbus-unix-fd-client.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-unix-fd-client.c)
174 * ## An example for exporting a GObject # {#gdbus-export}
176 * Here is an example for exporting a #GObject:
177 * [gdbus-example-export.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-export.c)
180 /* ---------------------------------------------------------------------------------------------------- */
182 typedef struct _GDBusConnectionClass GDBusConnectionClass;
185 * GDBusConnectionClass:
186 * @closed: Signal class handler for the #GDBusConnection::closed signal.
188 * Class structure for #GDBusConnection.
192 struct _GDBusConnectionClass
195 GObjectClass parent_class;
199 void (*closed) (GDBusConnection *connection,
200 gboolean remote_peer_vanished,
204 G_LOCK_DEFINE_STATIC (message_bus_lock);
206 static GWeakRef the_session_bus;
207 static GWeakRef the_system_bus;
209 /* Extra pseudo-member of GDBusSendMessageFlags.
210 * Set by initable_init() to indicate that despite not being initialized yet,
211 * enough of the only-valid-after-init members are set that we can send a
212 * message, and we're being called from its thread, so no memory barrier is
213 * required before accessing them.
215 #define SEND_MESSAGE_FLAGS_INITIALIZING (1u << 31)
217 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
218 #define CALL_FLAGS_INITIALIZING (1u << 31)
220 /* ---------------------------------------------------------------------------------------------------- */
224 GDestroyNotify callback;
226 } CallDestroyNotifyData;
229 call_destroy_notify_data_in_idle (gpointer user_data)
231 CallDestroyNotifyData *data = user_data;
232 data->callback (data->user_data);
237 call_destroy_notify_data_free (CallDestroyNotifyData *data)
243 * call_destroy_notify: <internal>
244 * @context: (nullable): A #GMainContext or %NULL.
245 * @callback: (nullable): A #GDestroyNotify or %NULL.
246 * @user_data: Data to pass to @callback.
248 * Schedules @callback to run in @context.
251 call_destroy_notify (GMainContext *context,
252 GDestroyNotify callback,
255 GSource *idle_source;
256 CallDestroyNotifyData *data;
258 if (callback == NULL)
261 data = g_new0 (CallDestroyNotifyData, 1);
262 data->callback = callback;
263 data->user_data = user_data;
265 idle_source = g_idle_source_new ();
266 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
267 g_source_set_callback (idle_source,
268 call_destroy_notify_data_in_idle,
270 (GDestroyNotify) call_destroy_notify_data_free);
271 g_source_set_name (idle_source, "[gio] call_destroy_notify_data_in_idle");
272 g_source_attach (idle_source, context);
273 g_source_unref (idle_source);
276 /* ---------------------------------------------------------------------------------------------------- */
279 _g_strv_has_string (const gchar* const *haystack,
284 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
286 if (g_strcmp0 (haystack[n], needle) == 0)
292 /* ---------------------------------------------------------------------------------------------------- */
295 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
297 // TODO: for some reason this doesn't work on Windows
298 #define CONNECTION_ENSURE_LOCK(obj) do { \
299 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
301 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
302 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
307 #define CONNECTION_LOCK(obj) do { \
308 g_mutex_lock (&(obj)->lock); \
311 #define CONNECTION_UNLOCK(obj) do { \
312 g_mutex_unlock (&(obj)->lock); \
315 /* Flags in connection->atomic_flags */
317 FLAG_INITIALIZED = 1 << 0,
318 FLAG_EXIT_ON_CLOSE = 1 << 1,
325 * The #GDBusConnection structure contains only private data and
326 * should only be accessed using the provided API.
330 struct _GDBusConnection
333 GObject parent_instance;
335 /* ------------------------------------------------------------------------ */
336 /* -- General object state ------------------------------------------------ */
337 /* ------------------------------------------------------------------------ */
339 /* General-purpose lock for most fields */
342 /* A lock used in the init() method of the GInitable interface - see comments
343 * in initable_init() for why a separate lock is needed.
345 * If you need both @lock and @init_lock, you must take @init_lock first.
349 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
350 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
354 /* The underlying stream used for communication
355 * Read-only after initable_init(), so it may be read if you either
356 * hold @init_lock or check for initialization first.
360 /* The object used for authentication (if any).
361 * Read-only after initable_init(), so it may be read if you either
362 * hold @init_lock or check for initialization first.
366 /* Last serial used. Protected by @lock. */
369 /* The object used to send/receive messages.
370 * Read-only after initable_init(), so it may be read if you either
371 * hold @init_lock or check for initialization first.
375 /* If connected to a message bus, this contains the unique name assigned to
376 * us by the bus (e.g. ":1.42").
377 * Read-only after initable_init(), so it may be read if you either
378 * hold @init_lock or check for initialization first.
380 gchar *bus_unique_name;
382 /* The GUID returned by the other side if we authenticed as a client or
383 * the GUID to use if authenticating as a server.
384 * Read-only after initable_init(), so it may be read if you either
385 * hold @init_lock or check for initialization first.
389 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
390 * Inspect @initialization_error to see whether it succeeded or failed.
392 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
394 * FLAG_CLOSED is the closed property. It may be read at any time, but
395 * may only be written while holding @lock.
397 volatile gint atomic_flags;
399 /* If the connection could not be established during initable_init(),
400 * this GError will be set.
401 * Read-only after initable_init(), so it may be read if you either
402 * hold @init_lock or check for initialization first.
404 GError *initialization_error;
406 /* The result of g_main_context_ref_thread_default() when the object
407 * was created (the GObject _init() function) - this is used for delivery
408 * of the :closed GObject signal.
410 * Only set in the GObject init function, so no locks are needed.
412 GMainContext *main_context_at_construction;
414 /* Read-only construct properties, no locks needed */
416 GDBusConnectionFlags flags;
418 /* Map used for managing method replies, protected by @lock */
419 GHashTable *map_method_serial_to_task; /* guint32 -> GTask* */
421 /* Maps used for managing signal subscription, protected by @lock */
422 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
423 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
424 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
426 /* Maps used for managing exported objects and subtrees,
429 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
430 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
431 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
432 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
434 /* Map used for storing last used serials for each thread, protected by @lock */
435 GHashTable *map_thread_to_last_serial;
437 /* Structure used for message filters, protected by @lock */
440 /* Capabilities negotiated during authentication
441 * Read-only after initable_init(), so it may be read without holding a
442 * lock, if you check for initialization first.
444 GDBusCapabilityFlags capabilities;
446 /* Protected by @init_lock */
447 GDBusAuthObserver *authentication_observer;
449 /* Read-only after initable_init(), so it may be read if you either
450 * hold @init_lock or check for initialization first.
452 GCredentials *credentials;
454 /* set to TRUE when finalizing */
458 typedef struct ExportedObject ExportedObject;
459 static void exported_object_free (ExportedObject *eo);
461 typedef struct ExportedSubtree ExportedSubtree;
462 static void exported_subtree_free (ExportedSubtree *es);
480 PROP_CAPABILITY_FLAGS,
481 PROP_AUTHENTICATION_OBSERVER,
484 static void distribute_signals (GDBusConnection *connection,
485 GDBusMessage *message);
487 static void distribute_method_call (GDBusConnection *connection,
488 GDBusMessage *message);
490 static gboolean handle_generic_unlocked (GDBusConnection *connection,
491 GDBusMessage *message);
494 static void purge_all_signal_subscriptions (GDBusConnection *connection);
495 static void purge_all_filters (GDBusConnection *connection);
497 static void schedule_method_call (GDBusConnection *connection,
498 GDBusMessage *message,
499 guint registration_id,
500 guint subtree_registration_id,
501 const GDBusInterfaceInfo *interface_info,
502 const GDBusMethodInfo *method_info,
503 const GDBusPropertyInfo *property_info,
504 GVariant *parameters,
505 const GDBusInterfaceVTable *vtable,
506 GMainContext *main_context,
509 #define _G_ENSURE_LOCK(name) do { \
510 if (G_UNLIKELY (G_TRYLOCK(name))) \
512 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
513 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
517 static guint signals[LAST_SIGNAL] = { 0 };
519 static void initable_iface_init (GInitableIface *initable_iface);
520 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
522 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
523 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
524 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
528 * Check that all members of @connection that can only be accessed after
529 * the connection is initialized can safely be accessed. If not,
530 * log a critical warning. This function is a memory barrier.
532 * Returns: %TRUE if initialized
535 check_initialized (GDBusConnection *connection)
537 /* The access to @atomic_flags isn't conditional, so that this function
538 * provides a memory barrier for thread-safety even if checks are disabled.
539 * (If you don't want this stricter guarantee, you can call
540 * g_return_if_fail (check_initialized (c)).)
542 * This isn't strictly necessary now that we've decided use of an
543 * uninitialized GDBusConnection is undefined behaviour, but it seems
544 * better to be as deterministic as is feasible.
546 * (Anything that could suffer a crash from seeing undefined values
547 * must have a race condition - thread A initializes the connection while
548 * thread B calls a method without initialization, hoping that thread A will
549 * win the race - so its behaviour is undefined anyway.)
551 gint flags = g_atomic_int_get (&connection->atomic_flags);
553 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
555 /* We can safely access this, due to the memory barrier above */
556 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
562 MAY_BE_UNINITIALIZED = (1<<1)
563 } CheckUnclosedFlags;
566 * Check the same thing as check_initialized(), and also that the
567 * connection is not closed. If the connection is uninitialized,
568 * raise a critical warning (it's programmer error); if it's closed,
569 * raise a recoverable GError (it's a runtime error).
571 * This function is a memory barrier.
573 * Returns: %TRUE if initialized and not closed
576 check_unclosed (GDBusConnection *connection,
577 CheckUnclosedFlags check,
580 /* check_initialized() is effectively inlined, so we don't waste time
581 * doing two memory barriers
583 gint flags = g_atomic_int_get (&connection->atomic_flags);
585 if (!(check & MAY_BE_UNINITIALIZED))
587 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
588 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
591 if (flags & FLAG_CLOSED)
593 g_set_error_literal (error,
596 _("The connection is closed"));
603 static GHashTable *alive_connections = NULL;
606 g_dbus_connection_dispose (GObject *object)
608 GDBusConnection *connection = G_DBUS_CONNECTION (object);
610 G_LOCK (message_bus_lock);
611 CONNECTION_LOCK (connection);
612 if (connection->worker != NULL)
614 _g_dbus_worker_stop (connection->worker);
615 connection->worker = NULL;
616 if (alive_connections != NULL)
617 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
621 if (alive_connections != NULL)
622 g_warn_if_fail (!g_hash_table_contains (alive_connections, connection));
624 CONNECTION_UNLOCK (connection);
625 G_UNLOCK (message_bus_lock);
627 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
628 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
632 g_dbus_connection_finalize (GObject *object)
634 GDBusConnection *connection = G_DBUS_CONNECTION (object);
636 connection->finalizing = TRUE;
638 purge_all_signal_subscriptions (connection);
640 purge_all_filters (connection);
641 g_ptr_array_unref (connection->filters);
643 if (connection->authentication_observer != NULL)
644 g_object_unref (connection->authentication_observer);
646 if (connection->auth != NULL)
647 g_object_unref (connection->auth);
649 if (connection->credentials)
650 g_object_unref (connection->credentials);
652 if (connection->stream != NULL)
654 g_object_unref (connection->stream);
655 connection->stream = NULL;
658 g_free (connection->address);
660 g_free (connection->guid);
661 g_free (connection->bus_unique_name);
663 if (connection->initialization_error != NULL)
664 g_error_free (connection->initialization_error);
666 g_hash_table_unref (connection->map_method_serial_to_task);
668 g_hash_table_unref (connection->map_rule_to_signal_data);
669 g_hash_table_unref (connection->map_id_to_signal_data);
670 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
672 g_hash_table_unref (connection->map_id_to_ei);
673 g_hash_table_unref (connection->map_object_path_to_eo);
674 g_hash_table_unref (connection->map_id_to_es);
675 g_hash_table_unref (connection->map_object_path_to_es);
677 g_hash_table_unref (connection->map_thread_to_last_serial);
679 g_main_context_unref (connection->main_context_at_construction);
681 g_free (connection->machine_id);
683 g_mutex_clear (&connection->init_lock);
684 g_mutex_clear (&connection->lock);
686 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
689 /* called in any user thread, with the connection's lock not held */
691 g_dbus_connection_get_property (GObject *object,
696 GDBusConnection *connection = G_DBUS_CONNECTION (object);
701 g_value_set_object (value, g_dbus_connection_get_stream (connection));
705 g_value_set_string (value, g_dbus_connection_get_guid (connection));
708 case PROP_UNIQUE_NAME:
709 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
713 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
716 case PROP_EXIT_ON_CLOSE:
717 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
720 case PROP_CAPABILITY_FLAGS:
721 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
725 g_value_set_flags (value, g_dbus_connection_get_flags (connection));
729 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
734 /* called in any user thread, with the connection's lock not held */
736 g_dbus_connection_set_property (GObject *object,
741 GDBusConnection *connection = G_DBUS_CONNECTION (object);
746 connection->stream = g_value_dup_object (value);
750 connection->guid = g_value_dup_string (value);
754 connection->address = g_value_dup_string (value);
758 connection->flags = g_value_get_flags (value);
761 case PROP_EXIT_ON_CLOSE:
762 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
765 case PROP_AUTHENTICATION_OBSERVER:
766 connection->authentication_observer = g_value_dup_object (value);
770 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
775 /* Base-class implementation of GDBusConnection::closed.
777 * Called in a user thread, by the main context that was thread-default when
778 * the object was constructed.
781 g_dbus_connection_real_closed (GDBusConnection *connection,
782 gboolean remote_peer_vanished,
785 gint flags = g_atomic_int_get (&connection->atomic_flags);
787 /* Because atomic int access is a memory barrier, we can safely read
788 * initialization_error without a lock, as long as we do it afterwards.
790 if (remote_peer_vanished &&
791 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
792 (flags & FLAG_INITIALIZED) != 0 &&
793 connection->initialization_error == NULL)
800 g_dbus_connection_class_init (GDBusConnectionClass *klass)
802 GObjectClass *gobject_class;
804 gobject_class = G_OBJECT_CLASS (klass);
806 gobject_class->finalize = g_dbus_connection_finalize;
807 gobject_class->dispose = g_dbus_connection_dispose;
808 gobject_class->set_property = g_dbus_connection_set_property;
809 gobject_class->get_property = g_dbus_connection_get_property;
811 klass->closed = g_dbus_connection_real_closed;
814 * GDBusConnection:stream:
816 * The underlying #GIOStream used for I/O.
818 * If this is passed on construction and is a #GSocketConnection,
819 * then the corresponding #GSocket will be put into non-blocking mode.
821 * While the #GDBusConnection is active, it will interact with this
822 * stream from a worker thread, so it is not safe to interact with
823 * the stream directly.
827 g_object_class_install_property (gobject_class,
829 g_param_spec_object ("stream",
831 P_("The underlying streams used for I/O"),
835 G_PARAM_CONSTRUCT_ONLY |
836 G_PARAM_STATIC_NAME |
837 G_PARAM_STATIC_BLURB |
838 G_PARAM_STATIC_NICK));
841 * GDBusConnection:address:
843 * A D-Bus address specifying potential endpoints that can be used
844 * when establishing the connection.
848 g_object_class_install_property (gobject_class,
850 g_param_spec_string ("address",
852 P_("D-Bus address specifying potential socket endpoints"),
855 G_PARAM_CONSTRUCT_ONLY |
856 G_PARAM_STATIC_NAME |
857 G_PARAM_STATIC_BLURB |
858 G_PARAM_STATIC_NICK));
861 * GDBusConnection:flags:
863 * Flags from the #GDBusConnectionFlags enumeration.
867 g_object_class_install_property (gobject_class,
869 g_param_spec_flags ("flags",
872 G_TYPE_DBUS_CONNECTION_FLAGS,
873 G_DBUS_CONNECTION_FLAGS_NONE,
876 G_PARAM_CONSTRUCT_ONLY |
877 G_PARAM_STATIC_NAME |
878 G_PARAM_STATIC_BLURB |
879 G_PARAM_STATIC_NICK));
882 * GDBusConnection:guid:
884 * The GUID of the peer performing the role of server when
887 * If you are constructing a #GDBusConnection and pass
888 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
889 * #GDBusConnection:flags property then you MUST also set this
890 * property to a valid guid.
892 * If you are constructing a #GDBusConnection and pass
893 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
894 * #GDBusConnection:flags property you will be able to read the GUID
895 * of the other peer here after the connection has been successfully
900 g_object_class_install_property (gobject_class,
902 g_param_spec_string ("guid",
904 P_("GUID of the server peer"),
908 G_PARAM_CONSTRUCT_ONLY |
909 G_PARAM_STATIC_NAME |
910 G_PARAM_STATIC_BLURB |
911 G_PARAM_STATIC_NICK));
914 * GDBusConnection:unique-name:
916 * The unique name as assigned by the message bus or %NULL if the
917 * connection is not open or not a message bus connection.
921 g_object_class_install_property (gobject_class,
923 g_param_spec_string ("unique-name",
925 P_("Unique name of bus connection"),
928 G_PARAM_STATIC_NAME |
929 G_PARAM_STATIC_BLURB |
930 G_PARAM_STATIC_NICK));
933 * GDBusConnection:closed:
935 * A boolean specifying whether the connection has been closed.
939 g_object_class_install_property (gobject_class,
941 g_param_spec_boolean ("closed",
943 P_("Whether the connection is closed"),
946 G_PARAM_STATIC_NAME |
947 G_PARAM_STATIC_BLURB |
948 G_PARAM_STATIC_NICK));
951 * GDBusConnection:exit-on-close:
953 * A boolean specifying whether the process will be terminated (by
954 * calling `raise(SIGTERM)`) if the connection is closed by the
957 * Note that #GDBusConnection objects returned by g_bus_get_finish()
958 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
962 g_object_class_install_property (gobject_class,
964 g_param_spec_boolean ("exit-on-close",
966 P_("Whether the process is terminated when the connection is closed"),
970 G_PARAM_STATIC_NAME |
971 G_PARAM_STATIC_BLURB |
972 G_PARAM_STATIC_NICK));
975 * GDBusConnection:capabilities:
977 * Flags from the #GDBusCapabilityFlags enumeration
978 * representing connection features negotiated with the other peer.
982 g_object_class_install_property (gobject_class,
983 PROP_CAPABILITY_FLAGS,
984 g_param_spec_flags ("capabilities",
987 G_TYPE_DBUS_CAPABILITY_FLAGS,
988 G_DBUS_CAPABILITY_FLAGS_NONE,
990 G_PARAM_STATIC_NAME |
991 G_PARAM_STATIC_BLURB |
992 G_PARAM_STATIC_NICK));
995 * GDBusConnection:authentication-observer:
997 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1001 g_object_class_install_property (gobject_class,
1002 PROP_AUTHENTICATION_OBSERVER,
1003 g_param_spec_object ("authentication-observer",
1004 P_("Authentication Observer"),
1005 P_("Object used to assist in the authentication process"),
1006 G_TYPE_DBUS_AUTH_OBSERVER,
1008 G_PARAM_CONSTRUCT_ONLY |
1009 G_PARAM_STATIC_NAME |
1010 G_PARAM_STATIC_BLURB |
1011 G_PARAM_STATIC_NICK));
1014 * GDBusConnection::closed:
1015 * @connection: the #GDBusConnection emitting the signal
1016 * @remote_peer_vanished: %TRUE if @connection is closed because the
1017 * remote peer closed its end of the connection
1018 * @error: (nullable): a #GError with more details about the event or %NULL
1020 * Emitted when the connection is closed.
1022 * The cause of this event can be
1024 * - If g_dbus_connection_close() is called. In this case
1025 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1027 * - If the remote peer closes the connection. In this case
1028 * @remote_peer_vanished is set to %TRUE and @error is set.
1030 * - If the remote peer sends invalid or malformed data. In this
1031 * case @remote_peer_vanished is set to %FALSE and @error is set.
1033 * Upon receiving this signal, you should give up your reference to
1034 * @connection. You are guaranteed that this signal is emitted only
1039 signals[CLOSED_SIGNAL] = g_signal_new (I_("closed"),
1040 G_TYPE_DBUS_CONNECTION,
1042 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1045 _g_cclosure_marshal_VOID__BOOLEAN_BOXED,
1050 g_signal_set_va_marshaller (signals[CLOSED_SIGNAL],
1051 G_TYPE_FROM_CLASS (klass),
1052 _g_cclosure_marshal_VOID__BOOLEAN_BOXEDv);
1056 g_dbus_connection_init (GDBusConnection *connection)
1058 g_mutex_init (&connection->lock);
1059 g_mutex_init (&connection->init_lock);
1061 connection->map_method_serial_to_task = g_hash_table_new (g_direct_hash, g_direct_equal);
1063 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1065 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1067 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1070 (GDestroyNotify) g_ptr_array_unref);
1072 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1075 (GDestroyNotify) exported_object_free);
1077 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1080 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1083 (GDestroyNotify) exported_subtree_free);
1085 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1088 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1091 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1093 connection->filters = g_ptr_array_new ();
1097 * g_dbus_connection_get_stream:
1098 * @connection: a #GDBusConnection
1100 * Gets the underlying stream used for IO.
1102 * While the #GDBusConnection is active, it will interact with this
1103 * stream from a worker thread, so it is not safe to interact with
1104 * the stream directly.
1106 * Returns: (transfer none): the stream used for IO
1111 g_dbus_connection_get_stream (GDBusConnection *connection)
1113 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1115 /* do not use g_return_val_if_fail(), we want the memory barrier */
1116 if (!check_initialized (connection))
1119 return connection->stream;
1123 * g_dbus_connection_start_message_processing:
1124 * @connection: a #GDBusConnection
1126 * If @connection was created with
1127 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1128 * starts processing messages. Does nothing on if @connection wasn't
1129 * created with this flag or if the method has already been called.
1134 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1136 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1138 /* do not use g_return_val_if_fail(), we want the memory barrier */
1139 if (!check_initialized (connection))
1142 g_assert (connection->worker != NULL);
1143 _g_dbus_worker_unfreeze (connection->worker);
1147 * g_dbus_connection_is_closed:
1148 * @connection: a #GDBusConnection
1150 * Gets whether @connection is closed.
1152 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1157 g_dbus_connection_is_closed (GDBusConnection *connection)
1161 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1163 flags = g_atomic_int_get (&connection->atomic_flags);
1165 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1169 * g_dbus_connection_get_capabilities:
1170 * @connection: a #GDBusConnection
1172 * Gets the capabilities negotiated with the remote peer
1174 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1178 GDBusCapabilityFlags
1179 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1181 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1183 /* do not use g_return_val_if_fail(), we want the memory barrier */
1184 if (!check_initialized (connection))
1185 return G_DBUS_CAPABILITY_FLAGS_NONE;
1187 return connection->capabilities;
1191 * g_dbus_connection_get_flags:
1192 * @connection: a #GDBusConnection
1194 * Gets the flags used to construct this connection
1196 * Returns: zero or more flags from the #GDBusConnectionFlags enumeration
1200 GDBusConnectionFlags
1201 g_dbus_connection_get_flags (GDBusConnection *connection)
1203 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CONNECTION_FLAGS_NONE);
1205 /* do not use g_return_val_if_fail(), we want the memory barrier */
1206 if (!check_initialized (connection))
1207 return G_DBUS_CONNECTION_FLAGS_NONE;
1209 return connection->flags;
1212 /* ---------------------------------------------------------------------------------------------------- */
1214 /* Called in a temporary thread without holding locks. */
1216 flush_in_thread_func (GTask *task,
1217 gpointer source_object,
1219 GCancellable *cancellable)
1221 GError *error = NULL;
1223 if (g_dbus_connection_flush_sync (source_object,
1226 g_task_return_boolean (task, TRUE);
1228 g_task_return_error (task, error);
1232 * g_dbus_connection_flush:
1233 * @connection: a #GDBusConnection
1234 * @cancellable: (nullable): a #GCancellable or %NULL
1235 * @callback: (nullable): a #GAsyncReadyCallback to call when the
1236 * request is satisfied or %NULL if you don't care about the result
1237 * @user_data: The data to pass to @callback
1239 * Asynchronously flushes @connection, that is, writes all queued
1240 * outgoing message to the transport and then flushes the transport
1241 * (using g_output_stream_flush_async()). This is useful in programs
1242 * that wants to emit a D-Bus signal and then exit immediately. Without
1243 * flushing the connection, there is no guaranteed that the message has
1244 * been sent to the networking buffers in the OS kernel.
1246 * This is an asynchronous method. When the operation is finished,
1247 * @callback will be invoked in the
1248 * [thread-default main context][g-main-context-push-thread-default]
1249 * of the thread you are calling this method from. You can
1250 * then call g_dbus_connection_flush_finish() to get the result of the
1251 * operation. See g_dbus_connection_flush_sync() for the synchronous
1257 g_dbus_connection_flush (GDBusConnection *connection,
1258 GCancellable *cancellable,
1259 GAsyncReadyCallback callback,
1264 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1266 task = g_task_new (connection, cancellable, callback, user_data);
1267 g_task_set_source_tag (task, g_dbus_connection_flush);
1268 g_task_run_in_thread (task, flush_in_thread_func);
1269 g_object_unref (task);
1273 * g_dbus_connection_flush_finish:
1274 * @connection: a #GDBusConnection
1275 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1276 * to g_dbus_connection_flush()
1277 * @error: return location for error or %NULL
1279 * Finishes an operation started with g_dbus_connection_flush().
1281 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1286 g_dbus_connection_flush_finish (GDBusConnection *connection,
1290 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1291 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1292 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1294 return g_task_propagate_boolean (G_TASK (res), error);
1298 * g_dbus_connection_flush_sync:
1299 * @connection: a #GDBusConnection
1300 * @cancellable: (nullable): a #GCancellable or %NULL
1301 * @error: return location for error or %NULL
1303 * Synchronously flushes @connection. The calling thread is blocked
1304 * until this is done. See g_dbus_connection_flush() for the
1305 * asynchronous version of this method and more details about what it
1308 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1313 g_dbus_connection_flush_sync (GDBusConnection *connection,
1314 GCancellable *cancellable,
1319 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1320 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1324 /* This is only a best-effort attempt to see whether the connection is
1325 * closed, so it doesn't need the lock. If the connection closes just
1326 * after this check, but before scheduling the flush operation, the
1327 * result will be more or less the same as if the connection closed while
1328 * the flush operation was pending - it'll fail with either CLOSED or
1331 if (!check_unclosed (connection, 0, error))
1334 g_assert (connection->worker != NULL);
1336 ret = _g_dbus_worker_flush_sync (connection->worker,
1344 /* ---------------------------------------------------------------------------------------------------- */
1348 GDBusConnection *connection;
1350 gboolean remote_peer_vanished;
1354 emit_closed_data_free (EmitClosedData *data)
1356 g_object_unref (data->connection);
1357 if (data->error != NULL)
1358 g_error_free (data->error);
1362 /* Called in a user thread that has acquired the main context that was
1363 * thread-default when the object was constructed
1366 emit_closed_in_idle (gpointer user_data)
1368 EmitClosedData *data = user_data;
1371 g_object_notify (G_OBJECT (data->connection), "closed");
1372 g_signal_emit (data->connection,
1373 signals[CLOSED_SIGNAL],
1375 data->remote_peer_vanished,
1381 /* Can be called from any thread, must hold lock.
1382 * FLAG_CLOSED must already have been set.
1385 schedule_closed_unlocked (GDBusConnection *connection,
1386 gboolean remote_peer_vanished,
1389 GSource *idle_source;
1390 EmitClosedData *data;
1392 CONNECTION_ENSURE_LOCK (connection);
1394 data = g_new0 (EmitClosedData, 1);
1395 data->connection = g_object_ref (connection);
1396 data->remote_peer_vanished = remote_peer_vanished;
1397 data->error = error != NULL ? g_error_copy (error) : NULL;
1399 idle_source = g_idle_source_new ();
1400 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1401 g_source_set_callback (idle_source,
1402 emit_closed_in_idle,
1404 (GDestroyNotify) emit_closed_data_free);
1405 g_source_set_name (idle_source, "[gio] emit_closed_in_idle");
1406 g_source_attach (idle_source, connection->main_context_at_construction);
1407 g_source_unref (idle_source);
1410 /* ---------------------------------------------------------------------------------------------------- */
1413 * g_dbus_connection_close:
1414 * @connection: a #GDBusConnection
1415 * @cancellable: (nullable): a #GCancellable or %NULL
1416 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
1417 * satisfied or %NULL if you don't care about the result
1418 * @user_data: The data to pass to @callback
1420 * Closes @connection. Note that this never causes the process to
1421 * exit (this might only happen if the other end of a shared message
1422 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1424 * Once the connection is closed, operations such as sending a message
1425 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1426 * will not automatically flush the connection so queued messages may
1427 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1429 * If @connection is already closed, this method fails with
1430 * %G_IO_ERROR_CLOSED.
1432 * When @connection has been closed, the #GDBusConnection::closed
1433 * signal is emitted in the
1434 * [thread-default main context][g-main-context-push-thread-default]
1435 * of the thread that @connection was constructed in.
1437 * This is an asynchronous method. When the operation is finished,
1438 * @callback will be invoked in the
1439 * [thread-default main context][g-main-context-push-thread-default]
1440 * of the thread you are calling this method from. You can
1441 * then call g_dbus_connection_close_finish() to get the result of the
1442 * operation. See g_dbus_connection_close_sync() for the synchronous
1448 g_dbus_connection_close (GDBusConnection *connection,
1449 GCancellable *cancellable,
1450 GAsyncReadyCallback callback,
1455 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1457 /* do not use g_return_val_if_fail(), we want the memory barrier */
1458 if (!check_initialized (connection))
1461 g_assert (connection->worker != NULL);
1463 task = g_task_new (connection, cancellable, callback, user_data);
1464 g_task_set_source_tag (task, g_dbus_connection_close);
1465 _g_dbus_worker_close (connection->worker, task);
1466 g_object_unref (task);
1470 * g_dbus_connection_close_finish:
1471 * @connection: a #GDBusConnection
1472 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1473 * to g_dbus_connection_close()
1474 * @error: return location for error or %NULL
1476 * Finishes an operation started with g_dbus_connection_close().
1478 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1483 g_dbus_connection_close_finish (GDBusConnection *connection,
1487 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1488 g_return_val_if_fail (g_task_is_valid (res, connection), FALSE);
1489 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1491 return g_task_propagate_boolean (G_TASK (res), error);
1496 GAsyncResult *result;
1499 /* Can be called by any thread, without the connection lock */
1501 sync_close_cb (GObject *source_object,
1505 SyncCloseData *data = user_data;
1507 data->result = g_object_ref (res);
1508 g_main_loop_quit (data->loop);
1512 * g_dbus_connection_close_sync:
1513 * @connection: a #GDBusConnection
1514 * @cancellable: (nullable): a #GCancellable or %NULL
1515 * @error: return location for error or %NULL
1517 * Synchronously closes @connection. The calling thread is blocked
1518 * until this is done. See g_dbus_connection_close() for the
1519 * asynchronous version of this method and more details about what it
1522 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1527 g_dbus_connection_close_sync (GDBusConnection *connection,
1528 GCancellable *cancellable,
1533 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1534 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1538 if (check_unclosed (connection, 0, error))
1540 GMainContext *context;
1543 context = g_main_context_new ();
1544 g_main_context_push_thread_default (context);
1545 data.loop = g_main_loop_new (context, TRUE);
1548 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1549 g_main_loop_run (data.loop);
1550 ret = g_dbus_connection_close_finish (connection, data.result, error);
1552 g_object_unref (data.result);
1553 g_main_loop_unref (data.loop);
1554 g_main_context_pop_thread_default (context);
1555 g_main_context_unref (context);
1561 /* ---------------------------------------------------------------------------------------------------- */
1564 * g_dbus_connection_get_last_serial:
1565 * @connection: a #GDBusConnection
1567 * Retrieves the last serial number assigned to a #GDBusMessage on
1568 * the current thread. This includes messages sent via both low-level
1569 * API such as g_dbus_connection_send_message() as well as
1570 * high-level API such as g_dbus_connection_emit_signal(),
1571 * g_dbus_connection_call() or g_dbus_proxy_call().
1573 * Returns: the last used serial or zero when no message has been sent
1574 * within the current thread
1579 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1583 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1585 CONNECTION_LOCK (connection);
1586 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1588 CONNECTION_UNLOCK (connection);
1593 /* ---------------------------------------------------------------------------------------------------- */
1595 /* Can be called by any thread, with the connection lock held */
1597 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1598 GDBusMessage *message,
1599 GDBusSendMessageFlags flags,
1600 volatile guint32 *out_serial,
1605 guint32 serial_to_use;
1608 CONNECTION_ENSURE_LOCK (connection);
1610 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1611 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1613 /* TODO: check all necessary headers are present */
1618 if (out_serial != NULL)
1621 /* If we're in initable_init(), don't check for being initialized, to avoid
1622 * chicken-and-egg problems. initable_init() is responsible for setting up
1623 * our prerequisites (mainly connection->worker), and only calling us
1624 * from its own thread (so no memory barrier is needed).
1626 if (!check_unclosed (connection,
1627 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1631 blob = g_dbus_message_to_blob (message,
1633 connection->capabilities,
1638 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1639 serial_to_use = g_dbus_message_get_serial (message);
1641 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1646 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1649 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1652 g_assert_not_reached ();
1657 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1658 blob_size, serial_to_use, connection);
1659 g_printerr ("----\n");
1660 hexdump (blob, blob_size);
1661 g_printerr ("----\n");
1664 /* TODO: use connection->auth to encode the blob */
1666 if (out_serial != NULL)
1667 *out_serial = serial_to_use;
1669 /* store used serial for the current thread */
1670 /* TODO: watch the thread disposal and remove associated record
1672 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1674 g_hash_table_replace (connection->map_thread_to_last_serial,
1676 GUINT_TO_POINTER (serial_to_use));
1678 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1679 g_dbus_message_set_serial (message, serial_to_use);
1681 g_dbus_message_lock (message);
1682 _g_dbus_worker_send_message (connection->worker,
1686 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1697 * g_dbus_connection_send_message:
1698 * @connection: a #GDBusConnection
1699 * @message: a #GDBusMessage
1700 * @flags: flags affecting how the message is sent
1701 * @out_serial: (out) (optional): return location for serial number assigned
1702 * to @message when sending it or %NULL
1703 * @error: Return location for error or %NULL
1705 * Asynchronously sends @message to the peer represented by @connection.
1707 * Unless @flags contain the
1708 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1709 * will be assigned by @connection and set on @message via
1710 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1711 * serial number used will be written to this location prior to
1712 * submitting the message to the underlying transport.
1714 * If @connection is closed then the operation will fail with
1715 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1716 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1718 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1719 * for an example of how to use this low-level API to send and receive
1720 * UNIX file descriptors.
1722 * Note that @message must be unlocked, unless @flags contain the
1723 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1725 * Returns: %TRUE if the message was well-formed and queued for
1726 * transmission, %FALSE if @error is set
1731 g_dbus_connection_send_message (GDBusConnection *connection,
1732 GDBusMessage *message,
1733 GDBusSendMessageFlags flags,
1734 volatile guint32 *out_serial,
1739 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1740 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1741 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1742 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1744 CONNECTION_LOCK (connection);
1745 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1746 CONNECTION_UNLOCK (connection);
1750 /* ---------------------------------------------------------------------------------------------------- */
1756 gulong cancellable_handler_id;
1758 GSource *timeout_source;
1763 /* Can be called from any thread with or without lock held */
1765 send_message_data_free (SendMessageData *data)
1767 g_assert (data->timeout_source == NULL);
1768 g_assert (data->cancellable_handler_id == 0);
1770 g_slice_free (SendMessageData, data);
1773 /* ---------------------------------------------------------------------------------------------------- */
1775 /* can be called from any thread with lock held; @task is (transfer full) */
1777 send_message_with_reply_cleanup (GTask *task, gboolean remove)
1779 GDBusConnection *connection = g_task_get_source_object (task);
1780 SendMessageData *data = g_task_get_task_data (task);
1782 CONNECTION_ENSURE_LOCK (connection);
1784 g_assert (!data->delivered);
1786 data->delivered = TRUE;
1788 if (data->timeout_source != NULL)
1790 g_source_destroy (data->timeout_source);
1791 data->timeout_source = NULL;
1793 if (data->cancellable_handler_id > 0)
1795 g_cancellable_disconnect (g_task_get_cancellable (task), data->cancellable_handler_id);
1796 data->cancellable_handler_id = 0;
1801 gboolean removed = g_hash_table_remove (connection->map_method_serial_to_task,
1802 GUINT_TO_POINTER (data->serial));
1803 g_warn_if_fail (removed);
1806 g_object_unref (task);
1809 /* ---------------------------------------------------------------------------------------------------- */
1811 /* Called from GDBus worker thread with lock held; @task is (transfer full). */
1813 send_message_data_deliver_reply_unlocked (GTask *task,
1814 GDBusMessage *reply)
1816 SendMessageData *data = g_task_get_task_data (task);
1818 if (data->delivered)
1821 g_task_return_pointer (task, g_object_ref (reply), g_object_unref);
1823 send_message_with_reply_cleanup (task, TRUE);
1829 /* Called from a user thread, lock is not held */
1831 send_message_data_deliver_error (GTask *task,
1834 const char *message)
1836 GDBusConnection *connection = g_task_get_source_object (task);
1837 SendMessageData *data = g_task_get_task_data (task);
1839 CONNECTION_LOCK (connection);
1840 if (data->delivered)
1842 CONNECTION_UNLOCK (connection);
1846 g_object_ref (task);
1847 send_message_with_reply_cleanup (task, TRUE);
1848 CONNECTION_UNLOCK (connection);
1850 g_task_return_new_error (task, domain, code, "%s", message);
1851 g_object_unref (task);
1854 /* ---------------------------------------------------------------------------------------------------- */
1856 /* Called from a user thread, lock is not held; @task is (transfer full) */
1858 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1860 GTask *task = user_data;
1862 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_CANCELLED,
1863 _("Operation was cancelled"));
1867 /* Can be called from any thread with or without lock held */
1869 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1872 GTask *task = user_data;
1873 GSource *idle_source;
1875 /* postpone cancellation to idle handler since we may be called directly
1876 * via g_cancellable_connect() (e.g. holding lock)
1878 idle_source = g_idle_source_new ();
1879 g_source_set_name (idle_source, "[gio] send_message_with_reply_cancelled_idle_cb");
1880 g_task_attach_source (task, idle_source, send_message_with_reply_cancelled_idle_cb);
1881 g_source_unref (idle_source);
1884 /* ---------------------------------------------------------------------------------------------------- */
1886 /* Called from a user thread, lock is not held; @task is (transfer full) */
1888 send_message_with_reply_timeout_cb (gpointer user_data)
1890 GTask *task = user_data;
1892 send_message_data_deliver_error (task, G_IO_ERROR, G_IO_ERROR_TIMED_OUT,
1893 _("Timeout was reached"));
1897 /* ---------------------------------------------------------------------------------------------------- */
1899 /* Called from a user thread, connection's lock is held */
1901 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1902 GDBusMessage *message,
1903 GDBusSendMessageFlags flags,
1905 volatile guint32 *out_serial,
1906 GCancellable *cancellable,
1907 GAsyncReadyCallback callback,
1911 SendMessageData *data;
1912 GError *error = NULL;
1913 volatile guint32 serial;
1915 if (out_serial == NULL)
1916 out_serial = &serial;
1918 if (timeout_msec == -1)
1919 timeout_msec = 25 * 1000;
1921 data = g_slice_new0 (SendMessageData);
1922 task = g_task_new (connection, cancellable, callback, user_data);
1923 g_task_set_source_tag (task,
1924 g_dbus_connection_send_message_with_reply_unlocked);
1925 g_task_set_task_data (task, data, (GDestroyNotify) send_message_data_free);
1927 if (g_task_return_error_if_cancelled (task))
1929 g_object_unref (task);
1933 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1935 g_task_return_error (task, error);
1936 g_object_unref (task);
1939 data->serial = *out_serial;
1941 if (cancellable != NULL)
1943 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1944 G_CALLBACK (send_message_with_reply_cancelled_cb),
1945 g_object_ref (task),
1949 if (timeout_msec != G_MAXINT)
1951 data->timeout_source = g_timeout_source_new (timeout_msec);
1952 g_task_attach_source (task, data->timeout_source,
1953 (GSourceFunc) send_message_with_reply_timeout_cb);
1954 g_source_unref (data->timeout_source);
1957 g_hash_table_insert (connection->map_method_serial_to_task,
1958 GUINT_TO_POINTER (*out_serial),
1959 g_steal_pointer (&task));
1963 * g_dbus_connection_send_message_with_reply:
1964 * @connection: a #GDBusConnection
1965 * @message: a #GDBusMessage
1966 * @flags: flags affecting how the message is sent
1967 * @timeout_msec: the timeout in milliseconds, -1 to use the default
1968 * timeout or %G_MAXINT for no timeout
1969 * @out_serial: (out) (optional): return location for serial number assigned
1970 * to @message when sending it or %NULL
1971 * @cancellable: (nullable): a #GCancellable or %NULL
1972 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
1973 * is satisfied or %NULL if you don't care about the result
1974 * @user_data: The data to pass to @callback
1976 * Asynchronously sends @message to the peer represented by @connection.
1978 * Unless @flags contain the
1979 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1980 * will be assigned by @connection and set on @message via
1981 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1982 * serial number used will be written to this location prior to
1983 * submitting the message to the underlying transport.
1985 * If @connection is closed then the operation will fail with
1986 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1987 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1988 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1990 * This is an asynchronous method. When the operation is finished, @callback
1991 * will be invoked in the
1992 * [thread-default main context][g-main-context-push-thread-default]
1993 * of the thread you are calling this method from. You can then call
1994 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1995 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1997 * Note that @message must be unlocked, unless @flags contain the
1998 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2000 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2001 * for an example of how to use this low-level API to send and receive
2002 * UNIX file descriptors.
2007 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2008 GDBusMessage *message,
2009 GDBusSendMessageFlags flags,
2011 volatile guint32 *out_serial,
2012 GCancellable *cancellable,
2013 GAsyncReadyCallback callback,
2016 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2017 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2018 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2019 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2021 CONNECTION_LOCK (connection);
2022 g_dbus_connection_send_message_with_reply_unlocked (connection,
2030 CONNECTION_UNLOCK (connection);
2034 * g_dbus_connection_send_message_with_reply_finish:
2035 * @connection: a #GDBusConnection
2036 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2037 * g_dbus_connection_send_message_with_reply()
2038 * @error: teturn location for error or %NULL
2040 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2042 * Note that @error is only set if a local in-process error
2043 * occurred. That is to say that the returned #GDBusMessage object may
2044 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2045 * g_dbus_message_to_gerror() to transcode this to a #GError.
2047 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2048 * for an example of how to use this low-level API to send and receive
2049 * UNIX file descriptors.
2051 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2056 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2060 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2061 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
2062 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2064 return g_task_propagate_pointer (G_TASK (res), error);
2067 /* ---------------------------------------------------------------------------------------------------- */
2072 GMainContext *context;
2074 } SendMessageSyncData;
2076 /* Called from a user thread, lock is not held */
2078 send_message_with_reply_sync_cb (GDBusConnection *connection,
2082 SendMessageSyncData *data = user_data;
2083 data->res = g_object_ref (res);
2084 g_main_loop_quit (data->loop);
2088 * g_dbus_connection_send_message_with_reply_sync:
2089 * @connection: a #GDBusConnection
2090 * @message: a #GDBusMessage
2091 * @flags: flags affecting how the message is sent.
2092 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2093 * timeout or %G_MAXINT for no timeout
2094 * @out_serial: (out) (optional): return location for serial number
2095 * assigned to @message when sending it or %NULL
2096 * @cancellable: (nullable): a #GCancellable or %NULL
2097 * @error: return location for error or %NULL
2099 * Synchronously sends @message to the peer represented by @connection
2100 * and blocks the calling thread until a reply is received or the
2101 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2102 * for the asynchronous version of this method.
2104 * Unless @flags contain the
2105 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2106 * will be assigned by @connection and set on @message via
2107 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2108 * serial number used will be written to this location prior to
2109 * submitting the message to the underlying transport.
2111 * If @connection is closed then the operation will fail with
2112 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2113 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2114 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2116 * Note that @error is only set if a local in-process error
2117 * occurred. That is to say that the returned #GDBusMessage object may
2118 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2119 * g_dbus_message_to_gerror() to transcode this to a #GError.
2121 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2122 * for an example of how to use this low-level API to send and receive
2123 * UNIX file descriptors.
2125 * Note that @message must be unlocked, unless @flags contain the
2126 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2128 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2129 * to @message or %NULL if @error is set
2134 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2135 GDBusMessage *message,
2136 GDBusSendMessageFlags flags,
2138 volatile guint32 *out_serial,
2139 GCancellable *cancellable,
2142 SendMessageSyncData data;
2143 GDBusMessage *reply;
2145 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2146 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2147 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2148 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2149 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2152 data.context = g_main_context_new ();
2153 data.loop = g_main_loop_new (data.context, FALSE);
2155 g_main_context_push_thread_default (data.context);
2157 g_dbus_connection_send_message_with_reply (connection,
2163 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2165 g_main_loop_run (data.loop);
2166 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2170 g_main_context_pop_thread_default (data.context);
2172 g_main_context_unref (data.context);
2173 g_main_loop_unref (data.loop);
2175 g_object_unref (data.res);
2180 /* ---------------------------------------------------------------------------------------------------- */
2186 GDBusMessageFilterFunction filter_function;
2188 GDestroyNotify user_data_free_func;
2189 GMainContext *context;
2192 /* requires CONNECTION_LOCK */
2193 static FilterData **
2194 copy_filter_list (GPtrArray *filters)
2199 copy = g_new (FilterData *, filters->len + 1);
2200 for (n = 0; n < filters->len; n++)
2202 copy[n] = filters->pdata[n];
2203 copy[n]->ref_count++;
2210 /* requires CONNECTION_LOCK */
2212 free_filter_list (FilterData **filters)
2216 for (n = 0; filters[n]; n++)
2218 filters[n]->ref_count--;
2219 if (filters[n]->ref_count == 0)
2221 call_destroy_notify (filters[n]->context,
2222 filters[n]->user_data_free_func,
2223 filters[n]->user_data);
2224 g_main_context_unref (filters[n]->context);
2225 g_free (filters[n]);
2231 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2233 on_worker_message_received (GDBusWorker *worker,
2234 GDBusMessage *message,
2237 GDBusConnection *connection;
2238 FilterData **filters;
2242 G_LOCK (message_bus_lock);
2243 alive = g_hash_table_contains (alive_connections, user_data);
2246 G_UNLOCK (message_bus_lock);
2249 connection = G_DBUS_CONNECTION (user_data);
2250 g_object_ref (connection);
2251 G_UNLOCK (message_bus_lock);
2253 //g_debug ("in on_worker_message_received");
2255 g_object_ref (message);
2256 g_dbus_message_lock (message);
2258 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2260 /* First collect the set of callback functions */
2261 CONNECTION_LOCK (connection);
2262 filters = copy_filter_list (connection->filters);
2263 CONNECTION_UNLOCK (connection);
2265 /* then call the filters in order (without holding the lock) */
2266 for (n = 0; filters[n]; n++)
2268 message = filters[n]->filter_function (connection,
2271 filters[n]->user_data);
2272 if (message == NULL)
2274 g_dbus_message_lock (message);
2277 CONNECTION_LOCK (connection);
2278 free_filter_list (filters);
2279 CONNECTION_UNLOCK (connection);
2281 /* Standard dispatch unless the filter ate the message - no need to
2282 * do anything if the message was altered
2284 if (message != NULL)
2286 GDBusMessageType message_type;
2288 message_type = g_dbus_message_get_message_type (message);
2289 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2291 guint32 reply_serial;
2294 reply_serial = g_dbus_message_get_reply_serial (message);
2295 CONNECTION_LOCK (connection);
2296 task = g_hash_table_lookup (connection->map_method_serial_to_task,
2297 GUINT_TO_POINTER (reply_serial));
2300 /* This removes @task from @map_method_serial_to_task. */
2301 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2302 send_message_data_deliver_reply_unlocked (task, message);
2306 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2308 CONNECTION_UNLOCK (connection);
2310 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2312 CONNECTION_LOCK (connection);
2313 distribute_signals (connection, message);
2314 CONNECTION_UNLOCK (connection);
2316 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2318 CONNECTION_LOCK (connection);
2319 distribute_method_call (connection, message);
2320 CONNECTION_UNLOCK (connection);
2324 if (message != NULL)
2325 g_object_unref (message);
2326 g_object_unref (connection);
2329 /* Called in GDBusWorker's thread, lock is not held */
2330 static GDBusMessage *
2331 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2332 GDBusMessage *message,
2335 GDBusConnection *connection;
2336 FilterData **filters;
2340 G_LOCK (message_bus_lock);
2341 alive = g_hash_table_contains (alive_connections, user_data);
2344 G_UNLOCK (message_bus_lock);
2347 connection = G_DBUS_CONNECTION (user_data);
2348 g_object_ref (connection);
2349 G_UNLOCK (message_bus_lock);
2351 //g_debug ("in on_worker_message_about_to_be_sent");
2353 /* First collect the set of callback functions */
2354 CONNECTION_LOCK (connection);
2355 filters = copy_filter_list (connection->filters);
2356 CONNECTION_UNLOCK (connection);
2358 /* then call the filters in order (without holding the lock) */
2359 for (n = 0; filters[n]; n++)
2361 g_dbus_message_lock (message);
2362 message = filters[n]->filter_function (connection,
2365 filters[n]->user_data);
2366 if (message == NULL)
2370 CONNECTION_LOCK (connection);
2371 free_filter_list (filters);
2372 CONNECTION_UNLOCK (connection);
2374 g_object_unref (connection);
2379 /* called with connection lock held, in GDBusWorker thread */
2381 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2383 GTask *task = value;
2384 SendMessageData *data = g_task_get_task_data (task);
2386 if (data->delivered)
2389 g_task_return_new_error (task,
2392 _("The connection is closed"));
2394 /* Ask send_message_with_reply_cleanup not to remove the element from the
2395 * hash table - we're in the middle of a foreach; that would be unsafe.
2396 * Instead, return TRUE from this function so that it gets removed safely.
2398 send_message_with_reply_cleanup (task, FALSE);
2402 /* Called in GDBusWorker's thread - we must not block - without lock held */
2404 on_worker_closed (GDBusWorker *worker,
2405 gboolean remote_peer_vanished,
2409 GDBusConnection *connection;
2411 guint old_atomic_flags;
2413 G_LOCK (message_bus_lock);
2414 alive = g_hash_table_contains (alive_connections, user_data);
2417 G_UNLOCK (message_bus_lock);
2420 connection = G_DBUS_CONNECTION (user_data);
2421 g_object_ref (connection);
2422 G_UNLOCK (message_bus_lock);
2424 //g_debug ("in on_worker_closed: %s", error->message);
2426 CONNECTION_LOCK (connection);
2427 /* Even though this is atomic, we do it inside the lock to avoid breaking
2428 * assumptions in remove_match_rule(). We'd need the lock in a moment
2429 * anyway, so, no loss.
2431 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2433 if (!(old_atomic_flags & FLAG_CLOSED))
2435 g_hash_table_foreach_remove (connection->map_method_serial_to_task, cancel_method_on_close, NULL);
2436 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2438 CONNECTION_UNLOCK (connection);
2440 g_object_unref (connection);
2443 /* ---------------------------------------------------------------------------------------------------- */
2445 /* Determines the biggest set of capabilities we can support on this
2448 * Called with the init_lock held.
2450 static GDBusCapabilityFlags
2451 get_offered_capabilities_max (GDBusConnection *connection)
2453 GDBusCapabilityFlags ret;
2454 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2456 if (G_IS_UNIX_CONNECTION (connection->stream))
2457 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2462 /* Called in a user thread, lock is not held */
2464 initable_init (GInitable *initable,
2465 GCancellable *cancellable,
2468 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2471 /* This method needs to be idempotent to work with the singleton
2472 * pattern. See the docs for g_initable_init(). We implement this by
2475 * Unfortunately we can't use the main lock since the on_worker_*()
2476 * callbacks above needs the lock during initialization (for message
2477 * bus connections we do a synchronous Hello() call on the bus).
2479 g_mutex_lock (&connection->init_lock);
2483 /* Make this a no-op if we're already initialized (successfully or
2486 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2488 ret = (connection->initialization_error == NULL);
2492 /* Because of init_lock, we can't get here twice in different threads */
2493 g_assert (connection->initialization_error == NULL);
2495 /* The user can pass multiple (but mutally exclusive) construct
2498 * - stream (of type GIOStream)
2499 * - address (of type gchar*)
2501 * At the end of the day we end up with a non-NULL GIOStream
2502 * object in connection->stream.
2504 if (connection->address != NULL)
2506 g_assert (connection->stream == NULL);
2508 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2509 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2511 g_set_error_literal (&connection->initialization_error,
2513 G_IO_ERROR_INVALID_ARGUMENT,
2514 _("Unsupported flags encountered when constructing a client-side connection"));
2518 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2519 NULL, /* TODO: out_guid */
2521 &connection->initialization_error);
2522 if (connection->stream == NULL)
2525 else if (connection->stream != NULL)
2531 g_assert_not_reached ();
2534 /* Authenticate the connection */
2535 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2537 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2538 g_assert (connection->guid != NULL);
2539 connection->auth = _g_dbus_auth_new (connection->stream);
2540 if (!_g_dbus_auth_run_server (connection->auth,
2541 connection->authentication_observer,
2543 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2544 get_offered_capabilities_max (connection),
2545 &connection->capabilities,
2546 &connection->credentials,
2548 &connection->initialization_error))
2551 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2553 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2554 g_assert (connection->guid == NULL);
2555 connection->auth = _g_dbus_auth_new (connection->stream);
2556 connection->guid = _g_dbus_auth_run_client (connection->auth,
2557 connection->authentication_observer,
2558 get_offered_capabilities_max (connection),
2559 &connection->capabilities,
2561 &connection->initialization_error);
2562 if (connection->guid == NULL)
2566 if (connection->authentication_observer != NULL)
2568 g_object_unref (connection->authentication_observer);
2569 connection->authentication_observer = NULL;
2572 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2574 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2577 /* We want all IO operations to be non-blocking since they happen in
2578 * the worker thread which is shared by _all_ connections.
2580 if (G_IS_SOCKET_CONNECTION (connection->stream))
2582 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2586 G_LOCK (message_bus_lock);
2587 if (alive_connections == NULL)
2588 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2589 g_hash_table_add (alive_connections, connection);
2590 G_UNLOCK (message_bus_lock);
2592 connection->worker = _g_dbus_worker_new (connection->stream,
2593 connection->capabilities,
2594 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2595 on_worker_message_received,
2596 on_worker_message_about_to_be_sent,
2600 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2601 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2603 GVariant *hello_result;
2605 /* we could lift this restriction by adding code in gdbusprivate.c */
2606 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2608 g_set_error_literal (&connection->initialization_error,
2611 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2615 hello_result = g_dbus_connection_call_sync (connection,
2616 "org.freedesktop.DBus", /* name */
2617 "/org/freedesktop/DBus", /* path */
2618 "org.freedesktop.DBus", /* interface */
2620 NULL, /* parameters */
2621 G_VARIANT_TYPE ("(s)"),
2622 CALL_FLAGS_INITIALIZING,
2624 NULL, /* TODO: cancellable */
2625 &connection->initialization_error);
2626 if (hello_result == NULL)
2629 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2630 g_variant_unref (hello_result);
2631 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2638 g_assert (connection->initialization_error != NULL);
2639 g_propagate_error (error, g_error_copy (connection->initialization_error));
2642 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2643 g_mutex_unlock (&connection->init_lock);
2649 initable_iface_init (GInitableIface *initable_iface)
2651 initable_iface->init = initable_init;
2654 /* ---------------------------------------------------------------------------------------------------- */
2657 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2662 /* ---------------------------------------------------------------------------------------------------- */
2665 * g_dbus_connection_new:
2666 * @stream: a #GIOStream
2667 * @guid: (nullable): the GUID to use if authenticating as a server or %NULL
2668 * @flags: flags describing how to make the connection
2669 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2670 * @cancellable: (nullable): a #GCancellable or %NULL
2671 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2672 * @user_data: the data to pass to @callback
2674 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2675 * with the end represented by @stream.
2677 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2678 * will be put into non-blocking mode.
2680 * The D-Bus connection will interact with @stream from a worker thread.
2681 * As a result, the caller should not interact with @stream after this
2682 * method has been called, except by calling g_object_unref() on it.
2684 * If @observer is not %NULL it may be used to control the
2685 * authentication process.
2687 * When the operation is finished, @callback will be invoked. You can
2688 * then call g_dbus_connection_new_finish() to get the result of the
2691 * This is an asynchronous failable constructor. See
2692 * g_dbus_connection_new_sync() for the synchronous
2698 g_dbus_connection_new (GIOStream *stream,
2700 GDBusConnectionFlags flags,
2701 GDBusAuthObserver *observer,
2702 GCancellable *cancellable,
2703 GAsyncReadyCallback callback,
2706 _g_dbus_initialize ();
2708 g_return_if_fail (G_IS_IO_STREAM (stream));
2710 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2718 "authentication-observer", observer,
2723 * g_dbus_connection_new_finish:
2724 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2725 * passed to g_dbus_connection_new().
2726 * @error: return location for error or %NULL
2728 * Finishes an operation started with g_dbus_connection_new().
2730 * Returns: a #GDBusConnection or %NULL if @error is set. Free
2731 * with g_object_unref().
2736 g_dbus_connection_new_finish (GAsyncResult *res,
2740 GObject *source_object;
2742 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2743 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2745 source_object = g_async_result_get_source_object (res);
2746 g_assert (source_object != NULL);
2747 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2750 g_object_unref (source_object);
2752 return G_DBUS_CONNECTION (object);
2758 * g_dbus_connection_new_sync:
2759 * @stream: a #GIOStream
2760 * @guid: (nullable): the GUID to use if authenticating as a server or %NULL
2761 * @flags: flags describing how to make the connection
2762 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2763 * @cancellable: (nullable): a #GCancellable or %NULL
2764 * @error: return location for error or %NULL
2766 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2767 * with the end represented by @stream.
2769 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2770 * will be put into non-blocking mode.
2772 * The D-Bus connection will interact with @stream from a worker thread.
2773 * As a result, the caller should not interact with @stream after this
2774 * method has been called, except by calling g_object_unref() on it.
2776 * If @observer is not %NULL it may be used to control the
2777 * authentication process.
2779 * This is a synchronous failable constructor. See
2780 * g_dbus_connection_new() for the asynchronous version.
2782 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2787 g_dbus_connection_new_sync (GIOStream *stream,
2789 GDBusConnectionFlags flags,
2790 GDBusAuthObserver *observer,
2791 GCancellable *cancellable,
2794 _g_dbus_initialize ();
2795 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2796 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2797 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2803 "authentication-observer", observer,
2807 /* ---------------------------------------------------------------------------------------------------- */
2810 * g_dbus_connection_new_for_address:
2811 * @address: a D-Bus address
2812 * @flags: flags describing how to make the connection
2813 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2814 * @cancellable: (nullable): a #GCancellable or %NULL
2815 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2816 * @user_data: the data to pass to @callback
2818 * Asynchronously connects and sets up a D-Bus client connection for
2819 * exchanging D-Bus messages with an endpoint specified by @address
2820 * which must be in the
2821 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2823 * This constructor can only be used to initiate client-side
2824 * connections - use g_dbus_connection_new() if you need to act as the
2825 * server. In particular, @flags cannot contain the
2826 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2827 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2829 * When the operation is finished, @callback will be invoked. You can
2830 * then call g_dbus_connection_new_for_address_finish() to get the result of
2833 * If @observer is not %NULL it may be used to control the
2834 * authentication process.
2836 * This is an asynchronous failable constructor. See
2837 * g_dbus_connection_new_for_address_sync() for the synchronous
2843 g_dbus_connection_new_for_address (const gchar *address,
2844 GDBusConnectionFlags flags,
2845 GDBusAuthObserver *observer,
2846 GCancellable *cancellable,
2847 GAsyncReadyCallback callback,
2850 _g_dbus_initialize ();
2852 g_return_if_fail (address != NULL);
2854 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2861 "authentication-observer", observer,
2866 * g_dbus_connection_new_for_address_finish:
2867 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2868 * to g_dbus_connection_new()
2869 * @error: return location for error or %NULL
2871 * Finishes an operation started with g_dbus_connection_new_for_address().
2873 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2879 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2883 GObject *source_object;
2885 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2886 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2888 source_object = g_async_result_get_source_object (res);
2889 g_assert (source_object != NULL);
2890 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2893 g_object_unref (source_object);
2895 return G_DBUS_CONNECTION (object);
2901 * g_dbus_connection_new_for_address_sync:
2902 * @address: a D-Bus address
2903 * @flags: flags describing how to make the connection
2904 * @observer: (nullable): a #GDBusAuthObserver or %NULL
2905 * @cancellable: (nullable): a #GCancellable or %NULL
2906 * @error: return location for error or %NULL
2908 * Synchronously connects and sets up a D-Bus client connection for
2909 * exchanging D-Bus messages with an endpoint specified by @address
2910 * which must be in the
2911 * [D-Bus address format](https://dbus.freedesktop.org/doc/dbus-specification.html#addresses).
2913 * This constructor can only be used to initiate client-side
2914 * connections - use g_dbus_connection_new_sync() if you need to act
2915 * as the server. In particular, @flags cannot contain the
2916 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2917 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2919 * This is a synchronous failable constructor. See
2920 * g_dbus_connection_new_for_address() for the asynchronous version.
2922 * If @observer is not %NULL it may be used to control the
2923 * authentication process.
2925 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2931 g_dbus_connection_new_for_address_sync (const gchar *address,
2932 GDBusConnectionFlags flags,
2933 GDBusAuthObserver *observer,
2934 GCancellable *cancellable,
2937 _g_dbus_initialize ();
2939 g_return_val_if_fail (address != NULL, NULL);
2940 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2941 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2946 "authentication-observer", observer,
2950 /* ---------------------------------------------------------------------------------------------------- */
2953 * g_dbus_connection_set_exit_on_close:
2954 * @connection: a #GDBusConnection
2955 * @exit_on_close: whether the process should be terminated
2956 * when @connection is closed by the remote peer
2958 * Sets whether the process should be terminated when @connection is
2959 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2962 * Note that this function should be used with care. Most modern UNIX
2963 * desktops tie the notion of a user session with the session bus, and expect
2964 * all of a user's applications to quit when their bus connection goes away.
2965 * If you are setting @exit_on_close to %FALSE for the shared session
2966 * bus connection, you should make sure that your application exits
2967 * when the user session ends.
2972 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2973 gboolean exit_on_close)
2975 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2978 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2980 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2985 * g_dbus_connection_get_exit_on_close:
2986 * @connection: a #GDBusConnection
2988 * Gets whether the process is terminated when @connection is
2989 * closed by the remote peer. See
2990 * #GDBusConnection:exit-on-close for more details.
2992 * Returns: whether the process is terminated when @connection is
2993 * closed by the remote peer
2998 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3000 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3002 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3009 * g_dbus_connection_get_guid:
3010 * @connection: a #GDBusConnection
3012 * The GUID of the peer performing the role of server when
3013 * authenticating. See #GDBusConnection:guid for more details.
3015 * Returns: The GUID. Do not free this string, it is owned by
3021 g_dbus_connection_get_guid (GDBusConnection *connection)
3023 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3024 return connection->guid;
3028 * g_dbus_connection_get_unique_name:
3029 * @connection: a #GDBusConnection
3031 * Gets the unique name of @connection as assigned by the message
3032 * bus. This can also be used to figure out if @connection is a
3033 * message bus connection.
3035 * Returns: (nullable): the unique name or %NULL if @connection is not a message
3036 * bus connection. Do not free this string, it is owned by
3042 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3044 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3046 /* do not use g_return_val_if_fail(), we want the memory barrier */
3047 if (!check_initialized (connection))
3050 return connection->bus_unique_name;
3054 * g_dbus_connection_get_peer_credentials:
3055 * @connection: a #GDBusConnection
3057 * Gets the credentials of the authenticated peer. This will always
3058 * return %NULL unless @connection acted as a server
3059 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3060 * when set up and the client passed credentials as part of the
3061 * authentication process.
3063 * In a message bus setup, the message bus is always the server and
3064 * each application is a client. So this method will always return
3065 * %NULL for message bus clients.
3067 * Returns: (transfer none) (nullable): a #GCredentials or %NULL if not
3068 * available. Do not free this object, it is owned by @connection.
3073 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3075 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3077 /* do not use g_return_val_if_fail(), we want the memory barrier */
3078 if (!check_initialized (connection))
3081 return connection->credentials;
3084 /* ---------------------------------------------------------------------------------------------------- */
3086 static volatile guint _global_filter_id = 1;
3089 * g_dbus_connection_add_filter:
3090 * @connection: a #GDBusConnection
3091 * @filter_function: a filter function
3092 * @user_data: user data to pass to @filter_function
3093 * @user_data_free_func: function to free @user_data with when filter
3094 * is removed or %NULL
3096 * Adds a message filter. Filters are handlers that are run on all
3097 * incoming and outgoing messages, prior to standard dispatch. Filters
3098 * are run in the order that they were added. The same handler can be
3099 * added as a filter more than once, in which case it will be run more
3100 * than once. Filters added during a filter callback won't be run on
3101 * the message being processed. Filter functions are allowed to modify
3102 * and even drop messages.
3104 * Note that filters are run in a dedicated message handling thread so
3105 * they can't block and, generally, can't do anything but signal a
3106 * worker thread. Also note that filters are rarely needed - use API
3107 * such as g_dbus_connection_send_message_with_reply(),
3108 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3110 * If a filter consumes an incoming message the message is not
3111 * dispatched anywhere else - not even the standard dispatch machinery
3112 * (that API such as g_dbus_connection_signal_subscribe() and
3113 * g_dbus_connection_send_message_with_reply() relies on) will see the
3114 * message. Similarly, if a filter consumes an outgoing message, the
3115 * message will not be sent to the other peer.
3117 * If @user_data_free_func is non-%NULL, it will be called (in the
3118 * thread-default main context of the thread you are calling this
3119 * method from) at some point after @user_data is no longer
3120 * needed. (It is not guaranteed to be called synchronously when the
3121 * filter is removed, and may be called after @connection has been
3124 * Returns: a filter identifier that can be used with
3125 * g_dbus_connection_remove_filter()
3130 g_dbus_connection_add_filter (GDBusConnection *connection,
3131 GDBusMessageFilterFunction filter_function,
3133 GDestroyNotify user_data_free_func)
3137 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3138 g_return_val_if_fail (filter_function != NULL, 0);
3139 g_return_val_if_fail (check_initialized (connection), 0);
3141 CONNECTION_LOCK (connection);
3142 data = g_new0 (FilterData, 1);
3143 data->id = (guint) g_atomic_int_add (&_global_filter_id, 1); /* TODO: overflow etc. */
3144 data->ref_count = 1;
3145 data->filter_function = filter_function;
3146 data->user_data = user_data;
3147 data->user_data_free_func = user_data_free_func;
3148 data->context = g_main_context_ref_thread_default ();
3149 g_ptr_array_add (connection->filters, data);
3150 CONNECTION_UNLOCK (connection);
3155 /* only called from finalize(), removes all filters */
3157 purge_all_filters (GDBusConnection *connection)
3160 for (n = 0; n < connection->filters->len; n++)
3162 FilterData *data = connection->filters->pdata[n];
3164 call_destroy_notify (data->context,
3165 data->user_data_free_func,
3167 g_main_context_unref (data->context);
3173 * g_dbus_connection_remove_filter:
3174 * @connection: a #GDBusConnection
3175 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3179 * Note that since filters run in a different thread, there is a race
3180 * condition where it is possible that the filter will be running even
3181 * after calling g_dbus_connection_remove_filter(), so you cannot just
3182 * free data that the filter might be using. Instead, you should pass
3183 * a #GDestroyNotify to g_dbus_connection_add_filter(), which will be
3184 * called when it is guaranteed that the data is no longer needed.
3189 g_dbus_connection_remove_filter (GDBusConnection *connection,
3194 FilterData *to_destroy;
3196 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3197 g_return_if_fail (check_initialized (connection));
3199 CONNECTION_LOCK (connection);
3202 for (n = 0; n < connection->filters->len; n++)
3204 FilterData *data = connection->filters->pdata[n];
3205 if (data->id == filter_id)
3208 g_ptr_array_remove_index (connection->filters, n);
3210 if (data->ref_count == 0)
3215 CONNECTION_UNLOCK (connection);
3217 /* do free without holding lock */
3218 if (to_destroy != NULL)
3220 if (to_destroy->user_data_free_func != NULL)
3221 to_destroy->user_data_free_func (to_destroy->user_data);
3222 g_main_context_unref (to_destroy->context);
3223 g_free (to_destroy);
3227 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3231 /* ---------------------------------------------------------------------------------------------------- */
3237 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3238 gchar *interface_name;
3242 GDBusSignalFlags flags;
3243 GPtrArray *subscribers; /* (owned) (element-type SignalSubscriber) */
3247 signal_data_free (SignalData *signal_data)
3249 g_free (signal_data->rule);
3250 g_free (signal_data->sender);
3251 g_free (signal_data->sender_unique_name);
3252 g_free (signal_data->interface_name);
3253 g_free (signal_data->member);
3254 g_free (signal_data->object_path);
3255 g_free (signal_data->arg0);
3256 g_ptr_array_unref (signal_data->subscribers);
3257 g_free (signal_data);
3262 /* All fields are immutable after construction. */
3263 gatomicrefcount ref_count;
3264 GDBusSignalCallback callback;
3266 GDestroyNotify user_data_free_func;
3268 GMainContext *context;
3271 static SignalSubscriber *
3272 signal_subscriber_ref (SignalSubscriber *subscriber)
3274 g_atomic_ref_count_inc (&subscriber->ref_count);
3279 signal_subscriber_unref (SignalSubscriber *subscriber)
3281 if (g_atomic_ref_count_dec (&subscriber->ref_count))
3283 /* Destroy the user data. It doesn’t matter which thread
3284 * signal_subscriber_unref() is called in (or whether it’s called with a
3285 * lock held), as call_destroy_notify() always defers to the next
3286 * #GMainContext iteration. */
3287 call_destroy_notify (subscriber->context,
3288 subscriber->user_data_free_func,
3289 subscriber->user_data);
3291 g_main_context_unref (subscriber->context);
3292 g_free (subscriber);
3297 args_to_rule (const gchar *sender,
3298 const gchar *interface_name,
3299 const gchar *member,
3300 const gchar *object_path,
3302 GDBusSignalFlags flags)
3306 rule = g_string_new ("type='signal'");
3307 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3308 g_string_prepend_c (rule, '-');
3310 g_string_append_printf (rule, ",sender='%s'", sender);
3311 if (interface_name != NULL)
3312 g_string_append_printf (rule, ",interface='%s'", interface_name);
3314 g_string_append_printf (rule, ",member='%s'", member);
3315 if (object_path != NULL)
3316 g_string_append_printf (rule, ",path='%s'", object_path);
3320 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3321 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3322 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3323 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3325 g_string_append_printf (rule, ",arg0='%s'", arg0);
3328 return g_string_free (rule, FALSE);
3331 static volatile guint _global_subscriber_id = 1;
3332 static volatile guint _global_registration_id = 1;
3333 static volatile guint _global_subtree_registration_id = 1;
3335 /* ---------------------------------------------------------------------------------------------------- */
3337 /* Called in a user thread, lock is held */
3339 add_match_rule (GDBusConnection *connection,
3340 const gchar *match_rule)
3343 GDBusMessage *message;
3345 if (match_rule[0] == '-')
3348 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3349 "/org/freedesktop/DBus", /* path */
3350 "org.freedesktop.DBus", /* interface */
3352 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3354 if (!g_dbus_connection_send_message_unlocked (connection,
3356 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3360 g_critical ("Error while sending AddMatch() message: %s", error->message);
3361 g_error_free (error);
3363 g_object_unref (message);
3366 /* ---------------------------------------------------------------------------------------------------- */
3368 /* Called in a user thread, lock is held */
3370 remove_match_rule (GDBusConnection *connection,
3371 const gchar *match_rule)
3374 GDBusMessage *message;
3376 if (match_rule[0] == '-')
3379 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3380 "/org/freedesktop/DBus", /* path */
3381 "org.freedesktop.DBus", /* interface */
3383 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3386 if (!g_dbus_connection_send_message_unlocked (connection,
3388 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3392 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3393 * critical; but we're holding the lock, and our caller checked whether
3394 * we were already closed, so we can't get that error.
3396 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3397 g_error_free (error);
3399 g_object_unref (message);
3402 /* ---------------------------------------------------------------------------------------------------- */
3405 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3407 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3408 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3409 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3410 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3411 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3414 /* ---------------------------------------------------------------------------------------------------- */
3417 * g_dbus_connection_signal_subscribe:
3418 * @connection: a #GDBusConnection
3419 * @sender: (nullable): sender name to match on (unique or well-known name)
3420 * or %NULL to listen from all senders
3421 * @interface_name: (nullable): D-Bus interface name to match on or %NULL to
3422 * match on all interfaces
3423 * @member: (nullable): D-Bus signal name to match on or %NULL to match on
3425 * @object_path: (nullable): object path to match on or %NULL to match on
3427 * @arg0: (nullable): contents of first string argument to match on or %NULL
3428 * to match on all kinds of arguments
3429 * @flags: #GDBusSignalFlags describing how arg0 is used in subscribing to the
3431 * @callback: callback to invoke when there is a signal matching the requested data
3432 * @user_data: user data to pass to @callback
3433 * @user_data_free_func: (nullable): function to free @user_data with when
3434 * subscription is removed or %NULL
3436 * Subscribes to signals on @connection and invokes @callback with a whenever
3437 * the signal is received. Note that @callback will be invoked in the
3438 * [thread-default main context][g-main-context-push-thread-default]
3439 * of the thread you are calling this method from.
3441 * If @connection is not a message bus connection, @sender must be
3444 * If @sender is a well-known name note that @callback is invoked with
3445 * the unique name for the owner of @sender, not the well-known name
3446 * as one would expect. This is because the message bus rewrites the
3447 * name. As such, to avoid certain race conditions, users should be
3448 * tracking the name owner of the well-known name and use that when
3449 * processing the received signal.
3451 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3452 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3453 * interpreted as part of a namespace or path. The first argument
3454 * of a signal is matched against that part as specified by D-Bus.
3456 * If @user_data_free_func is non-%NULL, it will be called (in the
3457 * thread-default main context of the thread you are calling this
3458 * method from) at some point after @user_data is no longer
3459 * needed. (It is not guaranteed to be called synchronously when the
3460 * signal is unsubscribed from, and may be called after @connection
3461 * has been destroyed.)
3463 * As @callback is potentially invoked in a different thread from where it’s
3464 * emitted, it’s possible for this to happen after
3465 * g_dbus_connection_signal_unsubscribe() has been called in another thread.
3466 * Due to this, @user_data should have a strong reference which is freed with
3467 * @user_data_free_func, rather than pointing to data whose lifecycle is tied
3468 * to the signal subscription. For example, if a #GObject is used to store the
3469 * subscription ID from g_dbus_connection_signal_subscribe(), a strong reference
3470 * to that #GObject must be passed to @user_data, and g_object_unref() passed to
3471 * @user_data_free_func. You are responsible for breaking the resulting
3472 * reference count cycle by explicitly unsubscribing from the signal when
3473 * dropping the last external reference to the #GObject. Alternatively, a weak
3474 * reference may be used.
3476 * It is guaranteed that if you unsubscribe from a signal using
3477 * g_dbus_connection_signal_unsubscribe() from the same thread which made the
3478 * corresponding g_dbus_connection_signal_subscribe() call, @callback will not
3479 * be invoked after g_dbus_connection_signal_unsubscribe() returns.
3481 * The returned subscription identifier is an opaque value which is guaranteed
3484 * This function can never fail.
3486 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3491 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3492 const gchar *sender,
3493 const gchar *interface_name,
3494 const gchar *member,
3495 const gchar *object_path,
3497 GDBusSignalFlags flags,
3498 GDBusSignalCallback callback,
3500 GDestroyNotify user_data_free_func)
3503 SignalData *signal_data;
3504 SignalSubscriber *subscriber;
3505 GPtrArray *signal_data_array;
3506 const gchar *sender_unique_name;
3508 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3509 * an OOM condition. We might want to change that but that would involve making
3510 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3511 * handle that. And there's really no sensible way of handling this short of retrying
3512 * to add the match rule... and then there's the little thing that, hey, maybe there's
3513 * a reason the bus in an OOM condition.
3515 * Doable, but not really sure it's worth it...
3518 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3519 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3520 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3521 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3522 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3523 g_return_val_if_fail (callback != NULL, 0);
3524 g_return_val_if_fail (check_initialized (connection), 0);
3525 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3526 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3528 CONNECTION_LOCK (connection);
3530 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3531 * with a '-' character to prefix the rule (which will otherwise be
3534 * This allows us to hash the rule and do our lifecycle tracking in
3535 * the usual way, but the '-' prevents the match rule from ever
3536 * actually being send to the bus (either for add or remove).
3538 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3540 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3541 sender_unique_name = sender;
3543 sender_unique_name = "";
3545 subscriber = g_new0 (SignalSubscriber, 1);
3546 subscriber->ref_count = 1;
3547 subscriber->callback = callback;
3548 subscriber->user_data = user_data;
3549 subscriber->user_data_free_func = user_data_free_func;
3550 subscriber->id = (guint) g_atomic_int_add (&_global_subscriber_id, 1); /* TODO: overflow etc. */
3551 subscriber->context = g_main_context_ref_thread_default ();
3553 /* see if we've already have this rule */
3554 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3555 if (signal_data != NULL)
3557 g_ptr_array_add (signal_data->subscribers, subscriber);
3562 signal_data = g_new0 (SignalData, 1);
3563 signal_data->rule = rule;
3564 signal_data->sender = g_strdup (sender);
3565 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3566 signal_data->interface_name = g_strdup (interface_name);
3567 signal_data->member = g_strdup (member);
3568 signal_data->object_path = g_strdup (object_path);
3569 signal_data->arg0 = g_strdup (arg0);
3570 signal_data->flags = flags;
3571 signal_data->subscribers = g_ptr_array_new_with_free_func ((GDestroyNotify) signal_subscriber_unref);
3572 g_ptr_array_add (signal_data->subscribers, subscriber);
3574 g_hash_table_insert (connection->map_rule_to_signal_data,
3578 /* Add the match rule to the bus...
3580 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3581 * always send such messages to us.
3583 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3585 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3586 add_match_rule (connection, signal_data->rule);
3589 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3590 signal_data->sender_unique_name);
3591 if (signal_data_array == NULL)
3593 signal_data_array = g_ptr_array_new ();
3594 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3595 g_strdup (signal_data->sender_unique_name),
3598 g_ptr_array_add (signal_data_array, signal_data);
3601 g_hash_table_insert (connection->map_id_to_signal_data,
3602 GUINT_TO_POINTER (subscriber->id),
3605 CONNECTION_UNLOCK (connection);
3607 return subscriber->id;
3610 /* ---------------------------------------------------------------------------------------------------- */
3612 /* called in any thread */
3613 /* must hold lock when calling this (except if connection->finalizing is TRUE)
3614 * returns the number of removed subscribers */
3616 unsubscribe_id_internal (GDBusConnection *connection,
3617 guint subscription_id)
3619 SignalData *signal_data;
3620 GPtrArray *signal_data_array;
3622 guint n_removed = 0;
3624 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3625 GUINT_TO_POINTER (subscription_id));
3626 if (signal_data == NULL)
3628 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3632 for (n = 0; n < signal_data->subscribers->len; n++)
3634 SignalSubscriber *subscriber = signal_data->subscribers->pdata[n];
3636 if (subscriber->id != subscription_id)
3639 /* It’s OK to rearrange the array order using the ‘fast’ #GPtrArray
3640 * removal functions, since we’re going to exit the loop below anyway — we
3641 * never move on to the next element. Secondly, subscription IDs are
3642 * guaranteed to be unique. */
3643 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3644 GUINT_TO_POINTER (subscription_id)));
3646 g_ptr_array_remove_index_fast (signal_data->subscribers, n);
3648 if (signal_data->subscribers->len == 0)
3650 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3652 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3653 signal_data->sender_unique_name);
3654 g_warn_if_fail (signal_data_array != NULL);
3655 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3657 if (signal_data_array->len == 0)
3659 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3660 signal_data->sender_unique_name));
3663 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3664 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3665 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3666 !g_dbus_connection_is_closed (connection) &&
3667 !connection->finalizing)
3669 /* The check for g_dbus_connection_is_closed() means that
3670 * sending the RemoveMatch message can't fail with
3671 * G_IO_ERROR_CLOSED, because we're holding the lock,
3672 * so on_worker_closed() can't happen between the check we just
3673 * did, and releasing the lock later.
3675 remove_match_rule (connection, signal_data->rule);
3678 signal_data_free (signal_data);
3684 g_assert_not_reached ();
3691 * g_dbus_connection_signal_unsubscribe:
3692 * @connection: a #GDBusConnection
3693 * @subscription_id: a subscription id obtained from
3694 * g_dbus_connection_signal_subscribe()
3696 * Unsubscribes from signals.
3698 * Note that there may still be D-Bus traffic to process (relating to this
3699 * signal subscription) in the current thread-default #GMainContext after this
3700 * function has returned. You should continue to iterate the #GMainContext
3701 * until the #GDestroyNotify function passed to
3702 * g_dbus_connection_signal_subscribe() is called, in order to avoid memory
3703 * leaks through callbacks queued on the #GMainContext after it’s stopped being
3709 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3710 guint subscription_id)
3712 guint n_subscribers_removed G_GNUC_UNUSED /* when compiling with G_DISABLE_ASSERT */;
3714 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3715 g_return_if_fail (check_initialized (connection));
3717 CONNECTION_LOCK (connection);
3718 n_subscribers_removed = unsubscribe_id_internal (connection, subscription_id);
3719 CONNECTION_UNLOCK (connection);
3722 g_assert (n_subscribers_removed == 0 || n_subscribers_removed == 1);
3725 /* ---------------------------------------------------------------------------------------------------- */
3729 SignalSubscriber *subscriber; /* (owned) */
3730 GDBusMessage *message;
3731 GDBusConnection *connection;
3732 const gchar *sender; /* (nullable) for peer-to-peer connections */
3734 const gchar *interface;
3735 const gchar *member;
3738 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3742 emit_signal_instance_in_idle_cb (gpointer data)
3744 SignalInstance *signal_instance = data;
3745 GVariant *parameters;
3746 gboolean has_subscription;
3748 parameters = g_dbus_message_get_body (signal_instance->message);
3749 if (parameters == NULL)
3751 parameters = g_variant_new ("()");
3752 g_variant_ref_sink (parameters);
3756 g_variant_ref_sink (parameters);
3760 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3761 signal_instance->subscriber->id,
3762 signal_instance->sender,
3763 signal_instance->path,
3764 signal_instance->interface,
3765 signal_instance->member,
3766 g_variant_print (parameters, TRUE));
3769 /* Careful here, don't do the callback if we no longer has the subscription */
3770 CONNECTION_LOCK (signal_instance->connection);
3771 has_subscription = FALSE;
3772 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3773 GUINT_TO_POINTER (signal_instance->subscriber->id)) != NULL)
3774 has_subscription = TRUE;
3775 CONNECTION_UNLOCK (signal_instance->connection);
3777 if (has_subscription)
3778 signal_instance->subscriber->callback (signal_instance->connection,
3779 signal_instance->sender,
3780 signal_instance->path,
3781 signal_instance->interface,
3782 signal_instance->member,
3784 signal_instance->subscriber->user_data);
3786 g_variant_unref (parameters);
3792 signal_instance_free (SignalInstance *signal_instance)
3794 g_object_unref (signal_instance->message);
3795 g_object_unref (signal_instance->connection);
3796 signal_subscriber_unref (signal_instance->subscriber);
3797 g_free (signal_instance);
3801 namespace_rule_matches (const gchar *namespace,
3807 len_namespace = strlen (namespace);
3808 len_name = strlen (name);
3810 if (len_name < len_namespace)
3813 if (memcmp (namespace, name, len_namespace) != 0)
3816 return len_namespace == len_name || name[len_namespace] == '.';
3820 path_rule_matches (const gchar *path_a,
3821 const gchar *path_b)
3825 len_a = strlen (path_a);
3826 len_b = strlen (path_b);
3828 if (len_a < len_b && (len_a == 0 || path_a[len_a - 1] != '/'))
3831 if (len_b < len_a && (len_b == 0 || path_b[len_b - 1] != '/'))
3834 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3837 /* called in GDBusWorker thread WITH lock held
3839 * @sender is (nullable) for peer-to-peer connections */
3841 schedule_callbacks (GDBusConnection *connection,
3842 GPtrArray *signal_data_array,
3843 GDBusMessage *message,
3844 const gchar *sender)
3847 const gchar *interface;
3848 const gchar *member;
3857 interface = g_dbus_message_get_interface (message);
3858 member = g_dbus_message_get_member (message);
3859 path = g_dbus_message_get_path (message);
3860 arg0 = g_dbus_message_get_arg0 (message);
3863 g_print ("In schedule_callbacks:\n"
3865 " interface = '%s'\n"
3876 /* TODO: if this is slow, then we can change signal_data_array into
3877 * map_object_path_to_signal_data_array or something.
3879 for (n = 0; n < signal_data_array->len; n++)
3881 SignalData *signal_data = signal_data_array->pdata[n];
3883 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3886 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3889 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3892 if (signal_data->arg0 != NULL)
3897 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3899 if (!namespace_rule_matches (signal_data->arg0, arg0))
3902 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3904 if (!path_rule_matches (signal_data->arg0, arg0))
3907 else if (!g_str_equal (signal_data->arg0, arg0))
3911 for (m = 0; m < signal_data->subscribers->len; m++)
3913 SignalSubscriber *subscriber = signal_data->subscribers->pdata[m];
3914 GSource *idle_source;
3915 SignalInstance *signal_instance;
3917 signal_instance = g_new0 (SignalInstance, 1);
3918 signal_instance->subscriber = signal_subscriber_ref (subscriber);
3919 signal_instance->message = g_object_ref (message);
3920 signal_instance->connection = g_object_ref (connection);
3921 signal_instance->sender = sender;
3922 signal_instance->path = path;
3923 signal_instance->interface = interface;
3924 signal_instance->member = member;
3926 idle_source = g_idle_source_new ();
3927 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3928 g_source_set_callback (idle_source,
3929 emit_signal_instance_in_idle_cb,
3931 (GDestroyNotify) signal_instance_free);
3932 g_source_set_name (idle_source, "[gio] emit_signal_instance_in_idle_cb");
3933 g_source_attach (idle_source, subscriber->context);
3934 g_source_unref (idle_source);
3939 /* called in GDBusWorker thread with lock held */
3941 distribute_signals (GDBusConnection *connection,
3942 GDBusMessage *message)
3944 GPtrArray *signal_data_array;
3945 const gchar *sender;
3947 sender = g_dbus_message_get_sender (message);
3949 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3951 _g_dbus_debug_print_lock ();
3952 g_print ("========================================================================\n"
3953 "GDBus-debug:Signal:\n"
3954 " <<<< RECEIVED SIGNAL %s.%s\n"
3956 " sent by name %s\n",
3957 g_dbus_message_get_interface (message),
3958 g_dbus_message_get_member (message),
3959 g_dbus_message_get_path (message),
3960 sender != NULL ? sender : "(none)");
3961 _g_dbus_debug_print_unlock ();
3964 /* collect subscribers that match on sender */
3967 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3968 if (signal_data_array != NULL)
3969 schedule_callbacks (connection, signal_data_array, message, sender);
3972 /* collect subscribers not matching on sender */
3973 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3974 if (signal_data_array != NULL)
3975 schedule_callbacks (connection, signal_data_array, message, sender);
3978 /* ---------------------------------------------------------------------------------------------------- */
3980 /* only called from finalize(), removes all subscriptions */
3982 purge_all_signal_subscriptions (GDBusConnection *connection)
3984 GHashTableIter iter;
3989 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3990 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3991 while (g_hash_table_iter_next (&iter, &key, NULL))
3993 guint subscription_id = GPOINTER_TO_UINT (key);
3994 g_array_append_val (ids, subscription_id);
3997 for (n = 0; n < ids->len; n++)
3999 guint subscription_id = g_array_index (ids, guint, n);
4000 unsubscribe_id_internal (connection, subscription_id);
4002 g_array_free (ids, TRUE);
4005 /* ---------------------------------------------------------------------------------------------------- */
4007 static GDBusInterfaceVTable *
4008 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
4010 /* Don't waste memory by copying padding - remember to update this
4011 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
4013 return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
4017 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4022 /* ---------------------------------------------------------------------------------------------------- */
4024 static GDBusSubtreeVTable *
4025 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4027 /* Don't waste memory by copying padding - remember to update this
4028 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4030 return g_memdup2 ((gconstpointer) vtable, 3 * sizeof (gpointer));
4034 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4039 /* ---------------------------------------------------------------------------------------------------- */
4041 struct ExportedObject
4044 GDBusConnection *connection;
4046 /* maps gchar* -> ExportedInterface* */
4047 GHashTable *map_if_name_to_ei;
4050 /* only called with lock held */
4052 exported_object_free (ExportedObject *eo)
4054 g_free (eo->object_path);
4055 g_hash_table_unref (eo->map_if_name_to_ei);
4064 gchar *interface_name;
4065 GDBusInterfaceVTable *vtable;
4066 GDBusInterfaceInfo *interface_info;
4068 GMainContext *context;
4070 GDestroyNotify user_data_free_func;
4071 } ExportedInterface;
4073 /* called with lock held */
4075 exported_interface_free (ExportedInterface *ei)
4077 g_dbus_interface_info_cache_release (ei->interface_info);
4078 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4080 call_destroy_notify (ei->context,
4081 ei->user_data_free_func,
4084 g_main_context_unref (ei->context);
4086 g_free (ei->interface_name);
4087 _g_dbus_interface_vtable_free (ei->vtable);
4091 /* ---------------------------------------------------------------------------------------------------- */
4093 /* Convenience function to check if @registration_id (if not zero) or
4094 * @subtree_registration_id (if not zero) has been unregistered. If
4095 * so, returns %TRUE.
4097 * May be called by any thread. Caller must *not* hold lock.
4100 has_object_been_unregistered (GDBusConnection *connection,
4101 guint registration_id,
4102 guint subtree_registration_id)
4106 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4110 CONNECTION_LOCK (connection);
4111 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4112 GUINT_TO_POINTER (registration_id)) == NULL)
4116 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4117 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4121 CONNECTION_UNLOCK (connection);
4126 /* ---------------------------------------------------------------------------------------------------- */
4130 GDBusConnection *connection;
4131 GDBusMessage *message;
4133 const gchar *property_name;
4134 const GDBusInterfaceVTable *vtable;
4135 GDBusInterfaceInfo *interface_info;
4136 const GDBusPropertyInfo *property_info;
4137 guint registration_id;
4138 guint subtree_registration_id;
4142 property_data_free (PropertyData *data)
4144 g_object_unref (data->connection);
4145 g_object_unref (data->message);
4149 /* called in thread where object was registered - no locks held */
4151 invoke_get_property_in_idle_cb (gpointer _data)
4153 PropertyData *data = _data;
4156 GDBusMessage *reply;
4158 if (has_object_been_unregistered (data->connection,
4159 data->registration_id,
4160 data->subtree_registration_id))
4162 reply = g_dbus_message_new_method_error (data->message,
4163 "org.freedesktop.DBus.Error.UnknownMethod",
4164 _("No such interface “org.freedesktop.DBus.Properties” on object at path %s"),
4165 g_dbus_message_get_path (data->message));
4166 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4167 g_object_unref (reply);
4172 value = data->vtable->get_property (data->connection,
4173 g_dbus_message_get_sender (data->message),
4174 g_dbus_message_get_path (data->message),
4175 data->interface_info->name,
4176 data->property_name,
4183 g_assert_no_error (error);
4185 g_variant_take_ref (value);
4186 reply = g_dbus_message_new_method_reply (data->message);
4187 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4188 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4189 g_variant_unref (value);
4190 g_object_unref (reply);
4194 gchar *dbus_error_name;
4195 g_assert (error != NULL);
4196 dbus_error_name = g_dbus_error_encode_gerror (error);
4197 reply = g_dbus_message_new_method_error_literal (data->message,
4200 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4201 g_free (dbus_error_name);
4202 g_error_free (error);
4203 g_object_unref (reply);
4210 /* called in thread where object was registered - no locks held */
4212 invoke_set_property_in_idle_cb (gpointer _data)
4214 PropertyData *data = _data;
4216 GDBusMessage *reply;
4222 g_variant_get (g_dbus_message_get_body (data->message),
4228 if (!data->vtable->set_property (data->connection,
4229 g_dbus_message_get_sender (data->message),
4230 g_dbus_message_get_path (data->message),
4231 data->interface_info->name,
4232 data->property_name,
4237 gchar *dbus_error_name;
4238 g_assert (error != NULL);
4239 dbus_error_name = g_dbus_error_encode_gerror (error);
4240 reply = g_dbus_message_new_method_error_literal (data->message,
4243 g_free (dbus_error_name);
4244 g_error_free (error);
4248 reply = g_dbus_message_new_method_reply (data->message);
4251 g_assert (reply != NULL);
4252 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4253 g_object_unref (reply);
4254 g_variant_unref (value);
4259 /* called in any thread with connection's lock held */
4261 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4262 GDBusMessage *message,
4263 guint registration_id,
4264 guint subtree_registration_id,
4266 GDBusInterfaceInfo *interface_info,
4267 const GDBusInterfaceVTable *vtable,
4268 GMainContext *main_context,
4272 const char *interface_name;
4273 const char *property_name;
4274 const GDBusPropertyInfo *property_info;
4275 GSource *idle_source;
4276 PropertyData *property_data;
4277 GDBusMessage *reply;
4282 g_variant_get (g_dbus_message_get_body (message),
4287 g_variant_get (g_dbus_message_get_body (message),
4296 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4298 property_info = NULL;
4300 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4301 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4302 if (property_info == NULL)
4304 reply = g_dbus_message_new_method_error (message,
4305 "org.freedesktop.DBus.Error.InvalidArgs",
4306 _("No such property “%s”"),
4308 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4309 g_object_unref (reply);
4314 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4316 reply = g_dbus_message_new_method_error (message,
4317 "org.freedesktop.DBus.Error.InvalidArgs",
4318 _("Property “%s” is not readable"),
4320 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4321 g_object_unref (reply);
4325 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4327 reply = g_dbus_message_new_method_error (message,
4328 "org.freedesktop.DBus.Error.InvalidArgs",
4329 _("Property “%s” is not writable"),
4331 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4332 g_object_unref (reply);
4341 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4342 * of the given value is wrong
4344 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4345 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4347 reply = g_dbus_message_new_method_error (message,
4348 "org.freedesktop.DBus.Error.InvalidArgs",
4349 _("Error setting property “%s”: Expected type “%s” but got “%s”"),
4350 property_name, property_info->signature,
4351 g_variant_get_type_string (value));
4352 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4353 g_variant_unref (value);
4354 g_object_unref (reply);
4359 g_variant_unref (value);
4362 /* If the vtable pointer for get_property() resp. set_property() is
4363 * NULL then dispatch the call via the method_call() handler.
4367 if (vtable->get_property == NULL)
4369 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4370 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4371 vtable, main_context, user_data);
4378 if (vtable->set_property == NULL)
4380 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4381 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4382 vtable, main_context, user_data);
4388 /* ok, got the property info - call user code in an idle handler */
4389 property_data = g_new0 (PropertyData, 1);
4390 property_data->connection = g_object_ref (connection);
4391 property_data->message = g_object_ref (message);
4392 property_data->user_data = user_data;
4393 property_data->property_name = property_name;
4394 property_data->vtable = vtable;
4395 property_data->interface_info = interface_info;
4396 property_data->property_info = property_info;
4397 property_data->registration_id = registration_id;
4398 property_data->subtree_registration_id = subtree_registration_id;
4400 idle_source = g_idle_source_new ();
4401 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4402 g_source_set_callback (idle_source,
4403 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4405 (GDestroyNotify) property_data_free);
4407 g_source_set_name (idle_source, "[gio] invoke_get_property_in_idle_cb");
4409 g_source_set_name (idle_source, "[gio] invoke_set_property_in_idle_cb");
4410 g_source_attach (idle_source, main_context);
4411 g_source_unref (idle_source);
4419 /* called in GDBusWorker thread with connection's lock held */
4421 handle_getset_property (GDBusConnection *connection,
4423 GDBusMessage *message,
4426 ExportedInterface *ei;
4428 const char *interface_name;
4429 const char *property_name;
4434 g_variant_get (g_dbus_message_get_body (message),
4439 g_variant_get (g_dbus_message_get_body (message),
4445 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4446 * no such interface registered
4448 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4451 GDBusMessage *reply;
4452 reply = g_dbus_message_new_method_error (message,
4453 "org.freedesktop.DBus.Error.InvalidArgs",
4454 _("No such interface “%s”"),
4456 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4457 g_object_unref (reply);
4462 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4475 /* ---------------------------------------------------------------------------------------------------- */
4479 GDBusConnection *connection;
4480 GDBusMessage *message;
4482 const GDBusInterfaceVTable *vtable;
4483 GDBusInterfaceInfo *interface_info;
4484 guint registration_id;
4485 guint subtree_registration_id;
4486 } PropertyGetAllData;
4489 property_get_all_data_free (PropertyData *data)
4491 g_object_unref (data->connection);
4492 g_object_unref (data->message);
4496 /* called in thread where object was registered - no locks held */
4498 invoke_get_all_properties_in_idle_cb (gpointer _data)
4500 PropertyGetAllData *data = _data;
4501 GVariantBuilder builder;
4502 GDBusMessage *reply;
4505 if (has_object_been_unregistered (data->connection,
4506 data->registration_id,
4507 data->subtree_registration_id))
4509 reply = g_dbus_message_new_method_error (data->message,
4510 "org.freedesktop.DBus.Error.UnknownMethod",
4511 _("No such interface “org.freedesktop.DBus.Properties” on object at path %s"),
4512 g_dbus_message_get_path (data->message));
4513 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4514 g_object_unref (reply);
4518 /* TODO: Right now we never fail this call - we just omit values if
4519 * a get_property() call is failing.
4521 * We could fail the whole call if just a single get_property() call
4522 * returns an error. We need clarification in the D-Bus spec about this.
4524 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4525 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4526 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4528 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4531 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4534 value = data->vtable->get_property (data->connection,
4535 g_dbus_message_get_sender (data->message),
4536 g_dbus_message_get_path (data->message),
4537 data->interface_info->name,
4538 property_info->name,
4545 g_variant_take_ref (value);
4546 g_variant_builder_add (&builder,
4548 property_info->name,
4550 g_variant_unref (value);
4552 g_variant_builder_close (&builder);
4554 reply = g_dbus_message_new_method_reply (data->message);
4555 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4556 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4557 g_object_unref (reply);
4564 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4568 if (!interface_info->properties)
4571 for (i = 0; interface_info->properties[i]; i++)
4572 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4578 /* called in any thread with connection's lock held */
4580 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4581 GDBusMessage *message,
4582 guint registration_id,
4583 guint subtree_registration_id,
4584 GDBusInterfaceInfo *interface_info,
4585 const GDBusInterfaceVTable *vtable,
4586 GMainContext *main_context,
4590 GSource *idle_source;
4591 PropertyGetAllData *property_get_all_data;
4598 /* If the vtable pointer for get_property() is NULL but we have a
4599 * non-zero number of readable properties, then dispatch the call via
4600 * the method_call() handler.
4602 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4604 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4605 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4606 vtable, main_context, user_data);
4611 /* ok, got the property info - call user in an idle handler */
4612 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4613 property_get_all_data->connection = g_object_ref (connection);
4614 property_get_all_data->message = g_object_ref (message);
4615 property_get_all_data->user_data = user_data;
4616 property_get_all_data->vtable = vtable;
4617 property_get_all_data->interface_info = interface_info;
4618 property_get_all_data->registration_id = registration_id;
4619 property_get_all_data->subtree_registration_id = subtree_registration_id;
4621 idle_source = g_idle_source_new ();
4622 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4623 g_source_set_callback (idle_source,
4624 invoke_get_all_properties_in_idle_cb,
4625 property_get_all_data,
4626 (GDestroyNotify) property_get_all_data_free);
4627 g_source_set_name (idle_source, "[gio] invoke_get_all_properties_in_idle_cb");
4628 g_source_attach (idle_source, main_context);
4629 g_source_unref (idle_source);
4637 /* called in GDBusWorker thread with connection's lock held */
4639 handle_get_all_properties (GDBusConnection *connection,
4641 GDBusMessage *message)
4643 ExportedInterface *ei;
4645 const char *interface_name;
4649 g_variant_get (g_dbus_message_get_body (message),
4653 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4654 * no such interface registered
4656 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4659 GDBusMessage *reply;
4660 reply = g_dbus_message_new_method_error (message,
4661 "org.freedesktop.DBus.Error.InvalidArgs",
4662 _("No such interface “%s”"),
4664 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4665 g_object_unref (reply);
4670 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4682 /* ---------------------------------------------------------------------------------------------------- */
4684 static const gchar introspect_header[] =
4685 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4686 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4687 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4690 static const gchar introspect_tail[] =
4693 static const gchar introspect_properties_interface[] =
4694 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4695 " <method name=\"Get\">\n"
4696 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4697 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4698 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4700 " <method name=\"GetAll\">\n"
4701 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4702 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4704 " <method name=\"Set\">\n"
4705 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4706 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4707 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4709 " <signal name=\"PropertiesChanged\">\n"
4710 " <arg type=\"s\" name=\"interface_name\"/>\n"
4711 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4712 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4716 static const gchar introspect_introspectable_interface[] =
4717 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4718 " <method name=\"Introspect\">\n"
4719 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4722 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4723 " <method name=\"Ping\"/>\n"
4724 " <method name=\"GetMachineId\">\n"
4725 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4730 introspect_append_header (GString *s)
4732 g_string_append (s, introspect_header);
4736 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4738 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4744 begin = object_path + path_len;
4745 end = strchr (begin, '/');
4747 s = g_strndup (begin, end - begin);
4749 s = g_strdup (begin);
4751 if (!g_hash_table_contains (set, s))
4752 g_hash_table_add (set, s);
4758 /* TODO: we want a nicer public interface for this */
4759 /* called in any thread with connection's lock held */
4761 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4766 GHashTableIter hash_iter;
4767 const gchar *object_path;
4773 CONNECTION_ENSURE_LOCK (connection);
4775 path_len = strlen (path);
4779 set = g_hash_table_new (g_str_hash, g_str_equal);
4781 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4782 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4783 maybe_add_path (path, path_len, object_path, set);
4785 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4786 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4787 maybe_add_path (path, path_len, object_path, set);
4789 p = g_ptr_array_new ();
4790 keys = g_hash_table_get_keys (set);
4791 for (l = keys; l != NULL; l = l->next)
4792 g_ptr_array_add (p, l->data);
4793 g_hash_table_unref (set);
4796 g_ptr_array_add (p, NULL);
4797 ret = (gchar **) g_ptr_array_free (p, FALSE);
4801 /* called in any thread with connection's lock not held */
4803 g_dbus_connection_list_registered (GDBusConnection *connection,
4807 CONNECTION_LOCK (connection);
4808 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4809 CONNECTION_UNLOCK (connection);
4813 /* called in GDBusWorker thread with connection's lock held */
4815 handle_introspect (GDBusConnection *connection,
4817 GDBusMessage *message)
4821 GDBusMessage *reply;
4822 GHashTableIter hash_iter;
4823 ExportedInterface *ei;
4826 /* first the header with the standard interfaces */
4827 s = g_string_sized_new (sizeof (introspect_header) +
4828 sizeof (introspect_properties_interface) +
4829 sizeof (introspect_introspectable_interface) +
4830 sizeof (introspect_tail));
4831 introspect_append_header (s);
4832 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4833 "org.freedesktop.DBus.Properties"))
4834 g_string_append (s, introspect_properties_interface);
4836 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4837 "org.freedesktop.DBus.Introspectable"))
4838 g_string_append (s, introspect_introspectable_interface);
4840 /* then include the registered interfaces */
4841 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4842 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4843 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4845 /* finally include nodes registered below us */
4846 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4847 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4848 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4849 g_strfreev (registered);
4850 g_string_append (s, introspect_tail);
4852 reply = g_dbus_message_new_method_reply (message);
4853 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4854 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4855 g_object_unref (reply);
4856 g_string_free (s, TRUE);
4861 /* called in thread where object was registered - no locks held */
4863 call_in_idle_cb (gpointer user_data)
4865 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4866 GDBusInterfaceVTable *vtable;
4867 guint registration_id;
4868 guint subtree_registration_id;
4870 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4871 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4873 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4875 subtree_registration_id))
4877 GDBusMessage *reply;
4878 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4879 "org.freedesktop.DBus.Error.UnknownMethod",
4880 _("No such interface “%s” on object at path %s"),
4881 g_dbus_method_invocation_get_interface_name (invocation),
4882 g_dbus_method_invocation_get_object_path (invocation));
4883 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4884 g_object_unref (reply);
4888 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4889 g_assert (vtable != NULL && vtable->method_call != NULL);
4891 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4892 g_dbus_method_invocation_get_sender (invocation),
4893 g_dbus_method_invocation_get_object_path (invocation),
4894 g_dbus_method_invocation_get_interface_name (invocation),
4895 g_dbus_method_invocation_get_method_name (invocation),
4896 g_dbus_method_invocation_get_parameters (invocation),
4897 g_object_ref (invocation),
4898 g_dbus_method_invocation_get_user_data (invocation));
4904 /* called in GDBusWorker thread with connection's lock held */
4906 schedule_method_call (GDBusConnection *connection,
4907 GDBusMessage *message,
4908 guint registration_id,
4909 guint subtree_registration_id,
4910 const GDBusInterfaceInfo *interface_info,
4911 const GDBusMethodInfo *method_info,
4912 const GDBusPropertyInfo *property_info,
4913 GVariant *parameters,
4914 const GDBusInterfaceVTable *vtable,
4915 GMainContext *main_context,
4918 GDBusMethodInvocation *invocation;
4919 GSource *idle_source;
4921 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4922 g_dbus_message_get_path (message),
4923 g_dbus_message_get_interface (message),
4924 g_dbus_message_get_member (message),
4932 /* TODO: would be nicer with a real MethodData like we already
4933 * have PropertyData and PropertyGetAllData... */
4934 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4935 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4936 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4938 idle_source = g_idle_source_new ();
4939 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4940 g_source_set_callback (idle_source,
4944 g_source_set_name (idle_source, "[gio, " __FILE__ "] call_in_idle_cb");
4945 g_source_attach (idle_source, main_context);
4946 g_source_unref (idle_source);
4949 /* called in GDBusWorker thread with connection's lock held */
4951 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4952 GDBusMessage *message,
4953 guint registration_id,
4954 guint subtree_registration_id,
4955 GDBusInterfaceInfo *interface_info,
4956 const GDBusInterfaceVTable *vtable,
4957 GMainContext *main_context,
4960 GDBusMethodInfo *method_info;
4961 GDBusMessage *reply;
4962 GVariant *parameters;
4964 GVariantType *in_type;
4968 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4969 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4971 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4972 * error to the caller
4974 if (method_info == NULL)
4976 reply = g_dbus_message_new_method_error (message,
4977 "org.freedesktop.DBus.Error.UnknownMethod",
4978 _("No such method “%s”"),
4979 g_dbus_message_get_member (message));
4980 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4981 g_object_unref (reply);
4986 parameters = g_dbus_message_get_body (message);
4987 if (parameters == NULL)
4989 parameters = g_variant_new ("()");
4990 g_variant_ref_sink (parameters);
4994 g_variant_ref (parameters);
4997 /* Check that the incoming args are of the right type - if they are not, return
4998 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
5000 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
5001 if (!g_variant_is_of_type (parameters, in_type))
5005 type_string = g_variant_type_dup_string (in_type);
5007 reply = g_dbus_message_new_method_error (message,
5008 "org.freedesktop.DBus.Error.InvalidArgs",
5009 _("Type of message, “%s”, does not match expected type “%s”"),
5010 g_variant_get_type_string (parameters),
5012 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5013 g_variant_type_free (in_type);
5014 g_variant_unref (parameters);
5015 g_object_unref (reply);
5016 g_free (type_string);
5020 g_variant_type_free (in_type);
5022 /* schedule the call in idle */
5023 schedule_method_call (connection, message, registration_id, subtree_registration_id,
5024 interface_info, method_info, NULL, parameters,
5025 vtable, main_context, user_data);
5026 g_variant_unref (parameters);
5033 /* ---------------------------------------------------------------------------------------------------- */
5035 /* called in GDBusWorker thread with connection's lock held */
5037 obj_message_func (GDBusConnection *connection,
5039 GDBusMessage *message)
5041 const gchar *interface_name;
5042 const gchar *member;
5043 const gchar *signature;
5048 interface_name = g_dbus_message_get_interface (message);
5049 member = g_dbus_message_get_member (message);
5050 signature = g_dbus_message_get_signature (message);
5052 /* see if we have an interface for handling this call */
5053 if (interface_name != NULL)
5055 ExportedInterface *ei;
5056 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5059 /* we do - invoke the handler in idle in the right thread */
5061 /* handle no vtable or handler being present */
5062 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5065 handled = validate_and_maybe_schedule_method_call (connection,
5077 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5078 g_strcmp0 (member, "Introspect") == 0 &&
5079 g_strcmp0 (signature, "") == 0)
5081 handled = handle_introspect (connection, eo, message);
5084 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5085 g_strcmp0 (member, "Get") == 0 &&
5086 g_strcmp0 (signature, "ss") == 0)
5088 handled = handle_getset_property (connection, eo, message, TRUE);
5091 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5092 g_strcmp0 (member, "Set") == 0 &&
5093 g_strcmp0 (signature, "ssv") == 0)
5095 handled = handle_getset_property (connection, eo, message, FALSE);
5098 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5099 g_strcmp0 (member, "GetAll") == 0 &&
5100 g_strcmp0 (signature, "s") == 0)
5102 handled = handle_get_all_properties (connection, eo, message);
5111 * g_dbus_connection_register_object:
5112 * @connection: a #GDBusConnection
5113 * @object_path: the object path to register at
5114 * @interface_info: introspection data for the interface
5115 * @vtable: (nullable): a #GDBusInterfaceVTable to call into or %NULL
5116 * @user_data: (nullable): data to pass to functions in @vtable
5117 * @user_data_free_func: function to call when the object path is unregistered
5118 * @error: return location for error or %NULL
5120 * Registers callbacks for exported objects at @object_path with the
5121 * D-Bus interface that is described in @interface_info.
5123 * Calls to functions in @vtable (and @user_data_free_func) will happen
5125 * [thread-default main context][g-main-context-push-thread-default]
5126 * of the thread you are calling this method from.
5128 * Note that all #GVariant values passed to functions in @vtable will match
5129 * the signature given in @interface_info - if a remote caller passes
5130 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5131 * is returned to the remote caller.
5133 * Additionally, if the remote caller attempts to invoke methods or
5134 * access properties not mentioned in @interface_info the
5135 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5136 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5137 * are returned to the caller.
5139 * It is considered a programming error if the
5140 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5141 * #GVariant of incorrect type.
5143 * If an existing callback is already registered at @object_path and
5144 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5146 * GDBus automatically implements the standard D-Bus interfaces
5147 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5148 * and org.freedesktop.Peer, so you don't have to implement those for the
5149 * objects you export. You can implement org.freedesktop.DBus.Properties
5150 * yourself, e.g. to handle getting and setting of properties asynchronously.
5152 * Note that the reference count on @interface_info will be
5153 * incremented by 1 (unless allocated statically, e.g. if the
5154 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5155 * as the object is exported. Also note that @vtable will be copied.
5157 * See this [server][gdbus-server] for an example of how to use this method.
5159 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5160 * that can be used with g_dbus_connection_unregister_object()
5165 g_dbus_connection_register_object (GDBusConnection *connection,
5166 const gchar *object_path,
5167 GDBusInterfaceInfo *interface_info,
5168 const GDBusInterfaceVTable *vtable,
5170 GDestroyNotify user_data_free_func,
5174 ExportedInterface *ei;
5177 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5178 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5179 g_return_val_if_fail (interface_info != NULL, 0);
5180 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5181 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5182 g_return_val_if_fail (check_initialized (connection), 0);
5186 CONNECTION_LOCK (connection);
5188 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5191 eo = g_new0 (ExportedObject, 1);
5192 eo->object_path = g_strdup (object_path);
5193 eo->connection = connection;
5194 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5197 (GDestroyNotify) exported_interface_free);
5198 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5201 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5207 _("An object is already exported for the interface %s at %s"),
5208 interface_info->name,
5213 ei = g_new0 (ExportedInterface, 1);
5214 ei->id = (guint) g_atomic_int_add (&_global_registration_id, 1); /* TODO: overflow etc. */
5216 ei->user_data = user_data;
5217 ei->user_data_free_func = user_data_free_func;
5218 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5219 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5220 g_dbus_interface_info_cache_build (ei->interface_info);
5221 ei->interface_name = g_strdup (interface_info->name);
5222 ei->context = g_main_context_ref_thread_default ();
5224 g_hash_table_insert (eo->map_if_name_to_ei,
5225 (gpointer) ei->interface_name,
5227 g_hash_table_insert (connection->map_id_to_ei,
5228 GUINT_TO_POINTER (ei->id),
5234 CONNECTION_UNLOCK (connection);
5240 * g_dbus_connection_unregister_object:
5241 * @connection: a #GDBusConnection
5242 * @registration_id: a registration id obtained from
5243 * g_dbus_connection_register_object()
5245 * Unregisters an object.
5247 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5252 g_dbus_connection_unregister_object (GDBusConnection *connection,
5253 guint registration_id)
5255 ExportedInterface *ei;
5259 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5260 g_return_val_if_fail (check_initialized (connection), FALSE);
5264 CONNECTION_LOCK (connection);
5266 ei = g_hash_table_lookup (connection->map_id_to_ei,
5267 GUINT_TO_POINTER (registration_id));
5273 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5274 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5275 /* unregister object path if we have no more exported interfaces */
5276 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5277 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5283 CONNECTION_UNLOCK (connection);
5289 GClosure *method_call_closure;
5290 GClosure *get_property_closure;
5291 GClosure *set_property_closure;
5292 } RegisterObjectData;
5294 static RegisterObjectData *
5295 register_object_data_new (GClosure *method_call_closure,
5296 GClosure *get_property_closure,
5297 GClosure *set_property_closure)
5299 RegisterObjectData *data;
5301 data = g_new0 (RegisterObjectData, 1);
5303 if (method_call_closure != NULL)
5305 data->method_call_closure = g_closure_ref (method_call_closure);
5306 g_closure_sink (method_call_closure);
5307 if (G_CLOSURE_NEEDS_MARSHAL (method_call_closure))
5308 g_closure_set_marshal (method_call_closure, g_cclosure_marshal_generic);
5311 if (get_property_closure != NULL)
5313 data->get_property_closure = g_closure_ref (get_property_closure);
5314 g_closure_sink (get_property_closure);
5315 if (G_CLOSURE_NEEDS_MARSHAL (get_property_closure))
5316 g_closure_set_marshal (get_property_closure, g_cclosure_marshal_generic);
5319 if (set_property_closure != NULL)
5321 data->set_property_closure = g_closure_ref (set_property_closure);
5322 g_closure_sink (set_property_closure);
5323 if (G_CLOSURE_NEEDS_MARSHAL (set_property_closure))
5324 g_closure_set_marshal (set_property_closure, g_cclosure_marshal_generic);
5331 register_object_free_func (gpointer user_data)
5333 RegisterObjectData *data = user_data;
5335 g_clear_pointer (&data->method_call_closure, g_closure_unref);
5336 g_clear_pointer (&data->get_property_closure, g_closure_unref);
5337 g_clear_pointer (&data->set_property_closure, g_closure_unref);
5343 register_with_closures_on_method_call (GDBusConnection *connection,
5344 const gchar *sender,
5345 const gchar *object_path,
5346 const gchar *interface_name,
5347 const gchar *method_name,
5348 GVariant *parameters,
5349 GDBusMethodInvocation *invocation,
5352 RegisterObjectData *data = user_data;
5353 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5355 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5356 g_value_set_object (¶ms[0], connection);
5358 g_value_init (¶ms[1], G_TYPE_STRING);
5359 g_value_set_string (¶ms[1], sender);
5361 g_value_init (¶ms[2], G_TYPE_STRING);
5362 g_value_set_string (¶ms[2], object_path);
5364 g_value_init (¶ms[3], G_TYPE_STRING);
5365 g_value_set_string (¶ms[3], interface_name);
5367 g_value_init (¶ms[4], G_TYPE_STRING);
5368 g_value_set_string (¶ms[4], method_name);
5370 g_value_init (¶ms[5], G_TYPE_VARIANT);
5371 g_value_set_variant (¶ms[5], parameters);
5373 g_value_init (¶ms[6], G_TYPE_DBUS_METHOD_INVOCATION);
5374 g_value_set_object (¶ms[6], invocation);
5376 g_closure_invoke (data->method_call_closure, NULL, G_N_ELEMENTS (params), params, NULL);
5378 g_value_unset (params + 0);
5379 g_value_unset (params + 1);
5380 g_value_unset (params + 2);
5381 g_value_unset (params + 3);
5382 g_value_unset (params + 4);
5383 g_value_unset (params + 5);
5384 g_value_unset (params + 6);
5388 register_with_closures_on_get_property (GDBusConnection *connection,
5389 const gchar *sender,
5390 const gchar *object_path,
5391 const gchar *interface_name,
5392 const gchar *property_name,
5396 RegisterObjectData *data = user_data;
5397 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5398 GValue result_value = G_VALUE_INIT;
5401 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5402 g_value_set_object (¶ms[0], connection);
5404 g_value_init (¶ms[1], G_TYPE_STRING);
5405 g_value_set_string (¶ms[1], sender);
5407 g_value_init (¶ms[2], G_TYPE_STRING);
5408 g_value_set_string (¶ms[2], object_path);
5410 g_value_init (¶ms[3], G_TYPE_STRING);
5411 g_value_set_string (¶ms[3], interface_name);
5413 g_value_init (¶ms[4], G_TYPE_STRING);
5414 g_value_set_string (¶ms[4], property_name);
5416 g_value_init (&result_value, G_TYPE_VARIANT);
5418 g_closure_invoke (data->get_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5420 result = g_value_get_variant (&result_value);
5422 g_variant_ref (result);
5424 g_value_unset (params + 0);
5425 g_value_unset (params + 1);
5426 g_value_unset (params + 2);
5427 g_value_unset (params + 3);
5428 g_value_unset (params + 4);
5429 g_value_unset (&result_value);
5432 g_set_error (error, G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5433 _("Unable to retrieve property %s.%s"),
5434 interface_name, property_name);
5440 register_with_closures_on_set_property (GDBusConnection *connection,
5441 const gchar *sender,
5442 const gchar *object_path,
5443 const gchar *interface_name,
5444 const gchar *property_name,
5449 RegisterObjectData *data = user_data;
5450 GValue params[] = { G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT, G_VALUE_INIT };
5451 GValue result_value = G_VALUE_INIT;
5454 g_value_init (¶ms[0], G_TYPE_DBUS_CONNECTION);
5455 g_value_set_object (¶ms[0], connection);
5457 g_value_init (¶ms[1], G_TYPE_STRING);
5458 g_value_set_string (¶ms[1], sender);
5460 g_value_init (¶ms[2], G_TYPE_STRING);
5461 g_value_set_string (¶ms[2], object_path);
5463 g_value_init (¶ms[3], G_TYPE_STRING);
5464 g_value_set_string (¶ms[3], interface_name);
5466 g_value_init (¶ms[4], G_TYPE_STRING);
5467 g_value_set_string (¶ms[4], property_name);
5469 g_value_init (¶ms[5], G_TYPE_VARIANT);
5470 g_value_set_variant (¶ms[5], value);
5472 g_value_init (&result_value, G_TYPE_BOOLEAN);
5474 g_closure_invoke (data->set_property_closure, &result_value, G_N_ELEMENTS (params), params, NULL);
5476 result = g_value_get_boolean (&result_value);
5478 g_value_unset (params + 0);
5479 g_value_unset (params + 1);
5480 g_value_unset (params + 2);
5481 g_value_unset (params + 3);
5482 g_value_unset (params + 4);
5483 g_value_unset (params + 5);
5484 g_value_unset (&result_value);
5488 G_DBUS_ERROR, G_DBUS_ERROR_FAILED,
5489 _("Unable to set property %s.%s"),
5490 interface_name, property_name);
5496 * g_dbus_connection_register_object_with_closures: (rename-to g_dbus_connection_register_object)
5497 * @connection: A #GDBusConnection.
5498 * @object_path: The object path to register at.
5499 * @interface_info: Introspection data for the interface.
5500 * @method_call_closure: (nullable): #GClosure for handling incoming method calls.
5501 * @get_property_closure: (nullable): #GClosure for getting a property.
5502 * @set_property_closure: (nullable): #GClosure for setting a property.
5503 * @error: Return location for error or %NULL.
5505 * Version of g_dbus_connection_register_object() using closures instead of a
5506 * #GDBusInterfaceVTable for easier binding in other languages.
5508 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5509 * that can be used with g_dbus_connection_unregister_object() .
5514 g_dbus_connection_register_object_with_closures (GDBusConnection *connection,
5515 const gchar *object_path,
5516 GDBusInterfaceInfo *interface_info,
5517 GClosure *method_call_closure,
5518 GClosure *get_property_closure,
5519 GClosure *set_property_closure,
5522 RegisterObjectData *data;
5523 GDBusInterfaceVTable vtable =
5525 method_call_closure != NULL ? register_with_closures_on_method_call : NULL,
5526 get_property_closure != NULL ? register_with_closures_on_get_property : NULL,
5527 set_property_closure != NULL ? register_with_closures_on_set_property : NULL
5530 data = register_object_data_new (method_call_closure, get_property_closure, set_property_closure);
5532 return g_dbus_connection_register_object (connection,
5537 register_object_free_func,
5541 /* ---------------------------------------------------------------------------------------------------- */
5544 * g_dbus_connection_emit_signal:
5545 * @connection: a #GDBusConnection
5546 * @destination_bus_name: (nullable): the unique bus name for the destination
5547 * for the signal or %NULL to emit to all listeners
5548 * @object_path: path of remote object
5549 * @interface_name: D-Bus interface to emit a signal on
5550 * @signal_name: the name of the signal to emit
5551 * @parameters: (nullable): a #GVariant tuple with parameters for the signal
5552 * or %NULL if not passing parameters
5553 * @error: Return location for error or %NULL
5557 * If the parameters GVariant is floating, it is consumed.
5559 * This can only fail if @parameters is not compatible with the D-Bus protocol
5560 * (%G_IO_ERROR_INVALID_ARGUMENT), or if @connection has been closed
5561 * (%G_IO_ERROR_CLOSED).
5563 * Returns: %TRUE unless @error is set
5568 g_dbus_connection_emit_signal (GDBusConnection *connection,
5569 const gchar *destination_bus_name,
5570 const gchar *object_path,
5571 const gchar *interface_name,
5572 const gchar *signal_name,
5573 GVariant *parameters,
5576 GDBusMessage *message;
5582 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5583 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5584 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5585 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5586 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5587 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5588 g_return_val_if_fail (check_initialized (connection), FALSE);
5590 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5592 _g_dbus_debug_print_lock ();
5593 g_print ("========================================================================\n"
5594 "GDBus-debug:Emission:\n"
5595 " >>>> SIGNAL EMISSION %s.%s()\n"
5597 " destination %s\n",
5598 interface_name, signal_name,
5600 destination_bus_name != NULL ? destination_bus_name : "(none)");
5601 _g_dbus_debug_print_unlock ();
5604 message = g_dbus_message_new_signal (object_path,
5608 if (destination_bus_name != NULL)
5609 g_dbus_message_set_header (message,
5610 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5611 g_variant_new_string (destination_bus_name));
5613 if (parameters != NULL)
5614 g_dbus_message_set_body (message, parameters);
5616 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5617 g_object_unref (message);
5623 add_call_flags (GDBusMessage *message,
5624 GDBusCallFlags flags)
5626 GDBusMessageFlags msg_flags = 0;
5628 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5629 msg_flags |= G_DBUS_MESSAGE_FLAGS_NO_AUTO_START;
5630 if (flags & G_DBUS_CALL_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION)
5631 msg_flags |= G_DBUS_MESSAGE_FLAGS_ALLOW_INTERACTIVE_AUTHORIZATION;
5633 g_dbus_message_set_flags (message, msg_flags);
5637 decode_method_reply (GDBusMessage *reply,
5638 const gchar *method_name,
5639 const GVariantType *reply_type,
5640 GUnixFDList **out_fd_list,
5646 switch (g_dbus_message_get_message_type (reply))
5648 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5649 result = g_dbus_message_get_body (reply);
5652 result = g_variant_new ("()");
5653 g_variant_ref_sink (result);
5657 g_variant_ref (result);
5660 if (!g_variant_is_of_type (result, reply_type))
5662 gchar *type_string = g_variant_type_dup_string (reply_type);
5666 G_IO_ERROR_INVALID_ARGUMENT,
5667 _("Method “%s” returned type “%s”, but expected “%s”"),
5668 method_name, g_variant_get_type_string (result), type_string);
5670 g_variant_unref (result);
5671 g_free (type_string);
5678 if (out_fd_list != NULL)
5680 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5681 if (*out_fd_list != NULL)
5682 g_object_ref (*out_fd_list);
5688 case G_DBUS_MESSAGE_TYPE_ERROR:
5689 g_dbus_message_to_gerror (reply, error);
5693 g_assert_not_reached ();
5703 GVariantType *reply_type;
5704 gchar *method_name; /* for error message */
5706 GUnixFDList *fd_list;
5710 call_state_free (CallState *state)
5712 g_variant_type_free (state->reply_type);
5713 g_free (state->method_name);
5715 if (state->fd_list != NULL)
5716 g_object_unref (state->fd_list);
5717 g_slice_free (CallState, state);
5720 /* called in any thread, with the connection's lock not held */
5722 g_dbus_connection_call_done (GObject *source,
5723 GAsyncResult *result,
5726 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5727 GTask *task = user_data;
5728 CallState *state = g_task_get_task_data (task);
5729 GError *error = NULL;
5730 GDBusMessage *reply;
5731 GVariant *value = NULL;
5733 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5737 if (G_UNLIKELY (_g_dbus_debug_call ()))
5739 _g_dbus_debug_print_lock ();
5740 g_print ("========================================================================\n"
5741 "GDBus-debug:Call:\n"
5742 " <<<< ASYNC COMPLETE %s()",
5743 state->method_name);
5747 g_print (" (serial %d)\n"
5749 g_dbus_message_get_reply_serial (reply));
5757 _g_dbus_debug_print_unlock ();
5761 value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5764 g_task_return_error (task, error);
5766 g_task_return_pointer (task, value, (GDestroyNotify) g_variant_unref);
5768 g_clear_object (&reply);
5769 g_object_unref (task);
5772 /* called in any thread, with the connection's lock not held */
5774 g_dbus_connection_call_internal (GDBusConnection *connection,
5775 const gchar *bus_name,
5776 const gchar *object_path,
5777 const gchar *interface_name,
5778 const gchar *method_name,
5779 GVariant *parameters,
5780 const GVariantType *reply_type,
5781 GDBusCallFlags flags,
5783 GUnixFDList *fd_list,
5784 GCancellable *cancellable,
5785 GAsyncReadyCallback callback,
5788 GDBusMessage *message;
5791 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5792 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5793 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5794 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5795 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5796 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5797 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5798 g_return_if_fail (check_initialized (connection));
5800 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5802 g_return_if_fail (fd_list == NULL);
5805 message = g_dbus_message_new_method_call (bus_name,
5809 add_call_flags (message, flags);
5810 if (parameters != NULL)
5811 g_dbus_message_set_body (message, parameters);
5814 if (fd_list != NULL)
5815 g_dbus_message_set_unix_fd_list (message, fd_list);
5818 /* If the user has no callback then we can just send the message with
5819 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5820 * the logic for processing the reply. If the service sends the reply
5821 * anyway then it will just be ignored.
5823 if (callback != NULL)
5828 state = g_slice_new0 (CallState);
5829 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5831 if (reply_type == NULL)
5832 reply_type = G_VARIANT_TYPE_ANY;
5834 state->reply_type = g_variant_type_copy (reply_type);
5836 task = g_task_new (connection, cancellable, callback, user_data);
5837 g_task_set_source_tag (task, g_dbus_connection_call_internal);
5838 g_task_set_task_data (task, state, (GDestroyNotify) call_state_free);
5840 g_dbus_connection_send_message_with_reply (connection,
5842 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5846 g_dbus_connection_call_done,
5851 GDBusMessageFlags flags;
5853 flags = g_dbus_message_get_flags (message);
5854 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5855 g_dbus_message_set_flags (message, flags);
5857 g_dbus_connection_send_message (connection,
5859 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5863 if (G_UNLIKELY (_g_dbus_debug_call ()))
5865 _g_dbus_debug_print_lock ();
5866 g_print ("========================================================================\n"
5867 "GDBus-debug:Call:\n"
5868 " >>>> ASYNC %s.%s()\n"
5870 " owned by name %s (serial %d)\n",
5874 bus_name != NULL ? bus_name : "(none)",
5876 _g_dbus_debug_print_unlock ();
5879 if (message != NULL)
5880 g_object_unref (message);
5883 /* called in any thread, with the connection's lock not held */
5885 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5886 GUnixFDList **out_fd_list,
5894 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5895 g_return_val_if_fail (g_task_is_valid (res, connection), NULL);
5896 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5898 task = G_TASK (res);
5899 state = g_task_get_task_data (task);
5901 ret = g_task_propagate_pointer (task, error);
5905 if (out_fd_list != NULL)
5906 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5910 /* called in any user thread, with the connection's lock not held */
5912 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5913 const gchar *bus_name,
5914 const gchar *object_path,
5915 const gchar *interface_name,
5916 const gchar *method_name,
5917 GVariant *parameters,
5918 const GVariantType *reply_type,
5919 GDBusCallFlags flags,
5921 GUnixFDList *fd_list,
5922 GUnixFDList **out_fd_list,
5923 GCancellable *cancellable,
5926 GDBusMessage *message;
5927 GDBusMessage *reply;
5929 GError *local_error;
5930 GDBusSendMessageFlags send_flags;
5936 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5937 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5938 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5939 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5940 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5941 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5942 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5944 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5946 g_return_val_if_fail (fd_list == NULL, NULL);
5948 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5950 if (!(flags & CALL_FLAGS_INITIALIZING))
5951 g_return_val_if_fail (check_initialized (connection), FALSE);
5953 if (reply_type == NULL)
5954 reply_type = G_VARIANT_TYPE_ANY;
5956 message = g_dbus_message_new_method_call (bus_name,
5960 add_call_flags (message, flags);
5961 if (parameters != NULL)
5962 g_dbus_message_set_body (message, parameters);
5965 if (fd_list != NULL)
5966 g_dbus_message_set_unix_fd_list (message, fd_list);
5969 if (G_UNLIKELY (_g_dbus_debug_call ()))
5971 _g_dbus_debug_print_lock ();
5972 g_print ("========================================================================\n"
5973 "GDBus-debug:Call:\n"
5974 " >>>> SYNC %s.%s()\n"
5976 " owned by name %s\n",
5980 bus_name != NULL ? bus_name : "(none)");
5981 _g_dbus_debug_print_unlock ();
5986 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5988 /* translate from one flavour of flags to another... */
5989 if (flags & CALL_FLAGS_INITIALIZING)
5990 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5992 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5996 NULL, /* volatile guint32 *out_serial */
6000 if (G_UNLIKELY (_g_dbus_debug_call ()))
6002 _g_dbus_debug_print_lock ();
6003 g_print ("========================================================================\n"
6004 "GDBus-debug:Call:\n"
6005 " <<<< SYNC COMPLETE %s.%s()\n"
6011 g_print ("SUCCESS\n");
6015 g_print ("FAILED: %s\n",
6016 local_error->message);
6018 _g_dbus_debug_print_unlock ();
6024 *error = local_error;
6026 g_error_free (local_error);
6030 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
6033 if (message != NULL)
6034 g_object_unref (message);
6036 g_object_unref (reply);
6041 /* ---------------------------------------------------------------------------------------------------- */
6044 * g_dbus_connection_call:
6045 * @connection: a #GDBusConnection
6046 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6047 * @connection is not a message bus connection
6048 * @object_path: path of remote object
6049 * @interface_name: D-Bus interface to invoke method on
6050 * @method_name: the name of the method to invoke
6051 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6052 * or %NULL if not passing parameters
6053 * @reply_type: (nullable): the expected type of the reply (which will be a
6055 * @flags: flags from the #GDBusCallFlags enumeration
6056 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6057 * timeout or %G_MAXINT for no timeout
6058 * @cancellable: (nullable): a #GCancellable or %NULL
6059 * @callback: (nullable): a #GAsyncReadyCallback to call when the request
6060 * is satisfied or %NULL if you don't care about the result of the
6062 * @user_data: the data to pass to @callback
6064 * Asynchronously invokes the @method_name method on the
6065 * @interface_name D-Bus interface on the remote object at
6066 * @object_path owned by @bus_name.
6068 * If @connection is closed then the operation will fail with
6069 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
6070 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
6071 * not compatible with the D-Bus protocol, the operation fails with
6072 * %G_IO_ERROR_INVALID_ARGUMENT.
6074 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
6075 * error will be raised if it does not match. Said another way, if you give a @reply_type
6076 * then any non-%NULL return value will be of this type. Unless it’s
6077 * %G_VARIANT_TYPE_UNIT, the @reply_type will be a tuple containing one or more
6080 * If the @parameters #GVariant is floating, it is consumed. This allows
6081 * convenient 'inline' use of g_variant_new(), e.g.:
6082 * |[<!-- language="C" -->
6083 * g_dbus_connection_call (connection,
6084 * "org.freedesktop.StringThings",
6085 * "/org/freedesktop/StringThings",
6086 * "org.freedesktop.StringThings",
6088 * g_variant_new ("(ss)",
6092 * G_DBUS_CALL_FLAGS_NONE,
6095 * (GAsyncReadyCallback) two_strings_done,
6099 * This is an asynchronous method. When the operation is finished,
6100 * @callback will be invoked in the
6101 * [thread-default main context][g-main-context-push-thread-default]
6102 * of the thread you are calling this method from. You can then call
6103 * g_dbus_connection_call_finish() to get the result of the operation.
6104 * See g_dbus_connection_call_sync() for the synchronous version of this
6107 * If @callback is %NULL then the D-Bus method call message will be sent with
6108 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
6113 g_dbus_connection_call (GDBusConnection *connection,
6114 const gchar *bus_name,
6115 const gchar *object_path,
6116 const gchar *interface_name,
6117 const gchar *method_name,
6118 GVariant *parameters,
6119 const GVariantType *reply_type,
6120 GDBusCallFlags flags,
6122 GCancellable *cancellable,
6123 GAsyncReadyCallback callback,
6126 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);
6130 * g_dbus_connection_call_finish:
6131 * @connection: a #GDBusConnection
6132 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
6133 * @error: return location for error or %NULL
6135 * Finishes an operation started with g_dbus_connection_call().
6137 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6138 * return values. Free with g_variant_unref().
6143 g_dbus_connection_call_finish (GDBusConnection *connection,
6147 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
6151 * g_dbus_connection_call_sync:
6152 * @connection: a #GDBusConnection
6153 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6154 * @connection is not a message bus connection
6155 * @object_path: path of remote object
6156 * @interface_name: D-Bus interface to invoke method on
6157 * @method_name: the name of the method to invoke
6158 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6159 * or %NULL if not passing parameters
6160 * @reply_type: (nullable): the expected type of the reply, or %NULL
6161 * @flags: flags from the #GDBusCallFlags enumeration
6162 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6163 * timeout or %G_MAXINT for no timeout
6164 * @cancellable: (nullable): a #GCancellable or %NULL
6165 * @error: return location for error or %NULL
6167 * Synchronously invokes the @method_name method on the
6168 * @interface_name D-Bus interface on the remote object at
6169 * @object_path owned by @bus_name.
6171 * If @connection is closed then the operation will fail with
6172 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
6173 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
6174 * contains a value not compatible with the D-Bus protocol, the operation
6175 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
6177 * If @reply_type is non-%NULL then the reply will be checked for having
6178 * this type and an error will be raised if it does not match. Said
6179 * another way, if you give a @reply_type then any non-%NULL return
6180 * value will be of this type.
6182 * If the @parameters #GVariant is floating, it is consumed.
6183 * This allows convenient 'inline' use of g_variant_new(), e.g.:
6184 * |[<!-- language="C" -->
6185 * g_dbus_connection_call_sync (connection,
6186 * "org.freedesktop.StringThings",
6187 * "/org/freedesktop/StringThings",
6188 * "org.freedesktop.StringThings",
6190 * g_variant_new ("(ss)",
6194 * G_DBUS_CALL_FLAGS_NONE,
6200 * The calling thread is blocked until a reply is received. See
6201 * g_dbus_connection_call() for the asynchronous version of
6204 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6205 * return values. Free with g_variant_unref().
6210 g_dbus_connection_call_sync (GDBusConnection *connection,
6211 const gchar *bus_name,
6212 const gchar *object_path,
6213 const gchar *interface_name,
6214 const gchar *method_name,
6215 GVariant *parameters,
6216 const GVariantType *reply_type,
6217 GDBusCallFlags flags,
6219 GCancellable *cancellable,
6222 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);
6225 /* ---------------------------------------------------------------------------------------------------- */
6230 * g_dbus_connection_call_with_unix_fd_list:
6231 * @connection: a #GDBusConnection
6232 * @bus_name: (nullable): a unique or well-known bus name or %NULL if
6233 * @connection is not a message bus connection
6234 * @object_path: path of remote object
6235 * @interface_name: D-Bus interface to invoke method on
6236 * @method_name: the name of the method to invoke
6237 * @parameters: (nullable): a #GVariant tuple with parameters for the method
6238 * or %NULL if not passing parameters
6239 * @reply_type: (nullable): the expected type of the reply, or %NULL
6240 * @flags: flags from the #GDBusCallFlags enumeration
6241 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6242 * timeout or %G_MAXINT for no timeout
6243 * @fd_list: (nullable): a #GUnixFDList or %NULL
6244 * @cancellable: (nullable): a #GCancellable or %NULL
6245 * @callback: (nullable): a #GAsyncReadyCallback to call when the request is
6246 * satisfied or %NULL if you don't * care about the result of the
6248 * @user_data: The data to pass to @callback.
6250 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
6252 * This method is only available on UNIX.
6257 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
6258 const gchar *bus_name,
6259 const gchar *object_path,
6260 const gchar *interface_name,
6261 const gchar *method_name,
6262 GVariant *parameters,
6263 const GVariantType *reply_type,
6264 GDBusCallFlags flags,
6266 GUnixFDList *fd_list,
6267 GCancellable *cancellable,
6268 GAsyncReadyCallback callback,
6271 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);
6275 * g_dbus_connection_call_with_unix_fd_list_finish:
6276 * @connection: a #GDBusConnection
6277 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6278 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
6279 * g_dbus_connection_call_with_unix_fd_list()
6280 * @error: return location for error or %NULL
6282 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6284 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6285 * return values. Free with g_variant_unref().
6290 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6291 GUnixFDList **out_fd_list,
6295 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6299 * g_dbus_connection_call_with_unix_fd_list_sync:
6300 * @connection: a #GDBusConnection
6301 * @bus_name: (nullable): a unique or well-known bus name or %NULL
6302 * if @connection is not a message bus connection
6303 * @object_path: path of remote object
6304 * @interface_name: D-Bus interface to invoke method on
6305 * @method_name: the name of the method to invoke
6306 * @parameters: (nullable): a #GVariant tuple with parameters for
6307 * the method or %NULL if not passing parameters
6308 * @reply_type: (nullable): the expected type of the reply, or %NULL
6309 * @flags: flags from the #GDBusCallFlags enumeration
6310 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6311 * timeout or %G_MAXINT for no timeout
6312 * @fd_list: (nullable): a #GUnixFDList or %NULL
6313 * @out_fd_list: (out) (optional): return location for a #GUnixFDList or %NULL
6314 * @cancellable: (nullable): a #GCancellable or %NULL
6315 * @error: return location for error or %NULL
6317 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6319 * This method is only available on UNIX.
6321 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6322 * return values. Free with g_variant_unref().
6327 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6328 const gchar *bus_name,
6329 const gchar *object_path,
6330 const gchar *interface_name,
6331 const gchar *method_name,
6332 GVariant *parameters,
6333 const GVariantType *reply_type,
6334 GDBusCallFlags flags,
6336 GUnixFDList *fd_list,
6337 GUnixFDList **out_fd_list,
6338 GCancellable *cancellable,
6341 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);
6344 #endif /* G_OS_UNIX */
6346 /* ---------------------------------------------------------------------------------------------------- */
6348 struct ExportedSubtree
6352 GDBusConnection *connection;
6353 GDBusSubtreeVTable *vtable;
6354 GDBusSubtreeFlags flags;
6356 GMainContext *context;
6358 GDestroyNotify user_data_free_func;
6362 exported_subtree_free (ExportedSubtree *es)
6364 call_destroy_notify (es->context,
6365 es->user_data_free_func,
6368 g_main_context_unref (es->context);
6370 _g_dbus_subtree_vtable_free (es->vtable);
6371 g_free (es->object_path);
6375 /* called without lock held in the thread where the caller registered
6379 handle_subtree_introspect (GDBusConnection *connection,
6380 ExportedSubtree *es,
6381 GDBusMessage *message)
6385 GDBusMessage *reply;
6388 const gchar *sender;
6389 const gchar *requested_object_path;
6390 const gchar *requested_node;
6391 GDBusInterfaceInfo **interfaces;
6393 gchar **subnode_paths;
6394 gboolean has_properties_interface;
6395 gboolean has_introspectable_interface;
6399 requested_object_path = g_dbus_message_get_path (message);
6400 sender = g_dbus_message_get_sender (message);
6401 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6403 s = g_string_new (NULL);
6404 introspect_append_header (s);
6406 /* Strictly we don't need the children in dynamic mode, but we avoid the
6407 * conditionals to preserve code clarity
6409 children = es->vtable->enumerate (es->connection,
6416 requested_node = strrchr (requested_object_path, '/') + 1;
6418 /* Assert existence of object if we are not dynamic */
6419 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6420 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6425 requested_node = NULL;
6428 interfaces = es->vtable->introspect (es->connection,
6433 if (interfaces != NULL)
6435 has_properties_interface = FALSE;
6436 has_introspectable_interface = FALSE;
6438 for (n = 0; interfaces[n] != NULL; n++)
6440 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6441 has_properties_interface = TRUE;
6442 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6443 has_introspectable_interface = TRUE;
6445 if (!has_properties_interface)
6446 g_string_append (s, introspect_properties_interface);
6447 if (!has_introspectable_interface)
6448 g_string_append (s, introspect_introspectable_interface);
6450 for (n = 0; interfaces[n] != NULL; n++)
6452 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6453 g_dbus_interface_info_unref (interfaces[n]);
6455 g_free (interfaces);
6458 /* then include <node> entries from the Subtree for the root */
6461 for (n = 0; children != NULL && children[n] != NULL; n++)
6462 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6465 /* finally include nodes registered below us */
6466 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6467 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6468 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6469 g_strfreev (subnode_paths);
6471 g_string_append (s, "</node>\n");
6473 reply = g_dbus_message_new_method_reply (message);
6474 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6475 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6476 g_object_unref (reply);
6481 g_string_free (s, TRUE);
6482 g_strfreev (children);
6486 /* called without lock held in the thread where the caller registered
6490 handle_subtree_method_invocation (GDBusConnection *connection,
6491 ExportedSubtree *es,
6492 GDBusMessage *message)
6495 const gchar *sender;
6496 const gchar *interface_name;
6497 const gchar *member;
6498 const gchar *signature;
6499 const gchar *requested_object_path;
6500 const gchar *requested_node;
6502 GDBusInterfaceInfo *interface_info;
6503 const GDBusInterfaceVTable *interface_vtable;
6504 gpointer interface_user_data;
6506 GDBusInterfaceInfo **interfaces;
6507 gboolean is_property_get;
6508 gboolean is_property_set;
6509 gboolean is_property_get_all;
6514 requested_object_path = g_dbus_message_get_path (message);
6515 sender = g_dbus_message_get_sender (message);
6516 interface_name = g_dbus_message_get_interface (message);
6517 member = g_dbus_message_get_member (message);
6518 signature = g_dbus_message_get_signature (message);
6519 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6521 is_property_get = FALSE;
6522 is_property_set = FALSE;
6523 is_property_get_all = FALSE;
6524 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6526 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6527 is_property_get = TRUE;
6528 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6529 is_property_set = TRUE;
6530 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6531 is_property_get_all = TRUE;
6536 requested_node = strrchr (requested_object_path, '/') + 1;
6538 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6540 /* We don't want to dispatch to unenumerated
6541 * nodes, so ensure that the child exists.
6546 children = es->vtable->enumerate (es->connection,
6551 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6552 g_strfreev (children);
6560 requested_node = NULL;
6563 /* get introspection data for the node */
6564 interfaces = es->vtable->introspect (es->connection,
6566 requested_object_path,
6570 if (interfaces == NULL)
6573 interface_info = NULL;
6574 for (n = 0; interfaces[n] != NULL; n++)
6576 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6577 interface_info = interfaces[n];
6580 /* dispatch the call if the user wants to handle it */
6581 if (interface_info != NULL)
6583 /* figure out where to dispatch the method call */
6584 interface_user_data = NULL;
6585 interface_vtable = es->vtable->dispatch (es->connection,
6590 &interface_user_data,
6592 if (interface_vtable == NULL)
6595 CONNECTION_LOCK (connection);
6596 handled = validate_and_maybe_schedule_method_call (es->connection,
6603 interface_user_data);
6604 CONNECTION_UNLOCK (connection);
6606 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6607 else if (is_property_get || is_property_set || is_property_get_all)
6609 if (is_property_get)
6610 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6611 else if (is_property_set)
6612 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6613 else if (is_property_get_all)
6614 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6616 g_assert_not_reached ();
6618 /* see if the object supports this interface at all */
6619 for (n = 0; interfaces[n] != NULL; n++)
6621 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6622 interface_info = interfaces[n];
6625 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6626 * claims it won't support the interface
6628 if (interface_info == NULL)
6630 GDBusMessage *reply;
6631 reply = g_dbus_message_new_method_error (message,
6632 "org.freedesktop.DBus.Error.InvalidArgs",
6633 _("No such interface “%s”"),
6635 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6636 g_object_unref (reply);
6641 /* figure out where to dispatch the property get/set/getall calls */
6642 interface_user_data = NULL;
6643 interface_vtable = es->vtable->dispatch (es->connection,
6648 &interface_user_data,
6650 if (interface_vtable == NULL)
6652 g_warning ("The subtree introspection function indicates that '%s' "
6653 "is a valid interface name, but calling the dispatch "
6654 "function on that interface gave us NULL", interface_name);
6658 if (is_property_get || is_property_set)
6660 CONNECTION_LOCK (connection);
6661 handled = validate_and_maybe_schedule_property_getset (es->connection,
6669 interface_user_data);
6670 CONNECTION_UNLOCK (connection);
6672 else if (is_property_get_all)
6674 CONNECTION_LOCK (connection);
6675 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6682 interface_user_data);
6683 CONNECTION_UNLOCK (connection);
6688 if (interfaces != NULL)
6690 for (n = 0; interfaces[n] != NULL; n++)
6691 g_dbus_interface_info_unref (interfaces[n]);
6692 g_free (interfaces);
6700 GDBusMessage *message;
6701 ExportedSubtree *es;
6702 } SubtreeDeferredData;
6705 subtree_deferred_data_free (SubtreeDeferredData *data)
6707 g_object_unref (data->message);
6711 /* called without lock held in the thread where the caller registered the subtree */
6713 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6715 SubtreeDeferredData *data = _data;
6720 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6721 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6722 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6723 handled = handle_subtree_introspect (data->es->connection,
6727 handled = handle_subtree_method_invocation (data->es->connection,
6733 CONNECTION_LOCK (data->es->connection);
6734 handled = handle_generic_unlocked (data->es->connection, data->message);
6735 CONNECTION_UNLOCK (data->es->connection);
6738 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6741 GDBusMessage *reply;
6742 reply = g_dbus_message_new_method_error (data->message,
6743 "org.freedesktop.DBus.Error.UnknownMethod",
6744 _("Method “%s” on interface “%s” with signature “%s” does not exist"),
6745 g_dbus_message_get_member (data->message),
6746 g_dbus_message_get_interface (data->message),
6747 g_dbus_message_get_signature (data->message));
6748 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6749 g_object_unref (reply);
6755 /* called in GDBusWorker thread with connection's lock held */
6757 subtree_message_func (GDBusConnection *connection,
6758 ExportedSubtree *es,
6759 GDBusMessage *message)
6761 GSource *idle_source;
6762 SubtreeDeferredData *data;
6764 data = g_new0 (SubtreeDeferredData, 1);
6765 data->message = g_object_ref (message);
6768 /* defer this call to an idle handler in the right thread */
6769 idle_source = g_idle_source_new ();
6770 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6771 g_source_set_callback (idle_source,
6772 process_subtree_vtable_message_in_idle_cb,
6774 (GDestroyNotify) subtree_deferred_data_free);
6775 g_source_set_name (idle_source, "[gio] process_subtree_vtable_message_in_idle_cb");
6776 g_source_attach (idle_source, es->context);
6777 g_source_unref (idle_source);
6779 /* since we own the entire subtree, handlers for objects not in the subtree have been
6780 * tried already by libdbus-1 - so we just need to ensure that we're always going
6781 * to reply to the message
6787 * g_dbus_connection_register_subtree:
6788 * @connection: a #GDBusConnection
6789 * @object_path: the object path to register the subtree at
6790 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6791 * dispatch nodes in the subtree
6792 * @flags: flags used to fine tune the behavior of the subtree
6793 * @user_data: data to pass to functions in @vtable
6794 * @user_data_free_func: function to call when the subtree is unregistered
6795 * @error: return location for error or %NULL
6797 * Registers a whole subtree of dynamic objects.
6799 * The @enumerate and @introspection functions in @vtable are used to
6800 * convey, to remote callers, what nodes exist in the subtree rooted
6803 * When handling remote calls into any node in the subtree, first the
6804 * @enumerate function is used to check if the node exists. If the node exists
6805 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6806 * the @introspection function is used to check if the node supports the
6807 * requested method. If so, the @dispatch function is used to determine
6808 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6809 * #gpointer will be used to call into the interface vtable for processing
6812 * All calls into user-provided code will be invoked in the
6813 * [thread-default main context][g-main-context-push-thread-default]
6814 * of the thread you are calling this method from.
6816 * If an existing subtree is already registered at @object_path or
6817 * then @error is set to #G_IO_ERROR_EXISTS.
6819 * Note that it is valid to register regular objects (using
6820 * g_dbus_connection_register_object()) in a subtree registered with
6821 * g_dbus_connection_register_subtree() - if so, the subtree handler
6822 * is tried as the last resort. One way to think about a subtree
6823 * handler is to consider it a fallback handler for object paths not
6824 * registered via g_dbus_connection_register_object() or other bindings.
6826 * Note that @vtable will be copied so you cannot change it after
6829 * See this [server][gdbus-subtree-server] for an example of how to use
6832 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6833 * that can be used with g_dbus_connection_unregister_subtree() .
6838 g_dbus_connection_register_subtree (GDBusConnection *connection,
6839 const gchar *object_path,
6840 const GDBusSubtreeVTable *vtable,
6841 GDBusSubtreeFlags flags,
6843 GDestroyNotify user_data_free_func,
6847 ExportedSubtree *es;
6849 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6850 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6851 g_return_val_if_fail (vtable != NULL, 0);
6852 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6853 g_return_val_if_fail (check_initialized (connection), 0);
6857 CONNECTION_LOCK (connection);
6859 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6865 _("A subtree is already exported for %s"),
6870 es = g_new0 (ExportedSubtree, 1);
6871 es->object_path = g_strdup (object_path);
6872 es->connection = connection;
6874 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6876 es->id = (guint) g_atomic_int_add (&_global_subtree_registration_id, 1); /* TODO: overflow etc. */
6877 es->user_data = user_data;
6878 es->user_data_free_func = user_data_free_func;
6879 es->context = g_main_context_ref_thread_default ();
6881 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6882 g_hash_table_insert (connection->map_id_to_es,
6883 GUINT_TO_POINTER (es->id),
6889 CONNECTION_UNLOCK (connection);
6894 /* ---------------------------------------------------------------------------------------------------- */
6897 * g_dbus_connection_unregister_subtree:
6898 * @connection: a #GDBusConnection
6899 * @registration_id: a subtree registration id obtained from
6900 * g_dbus_connection_register_subtree()
6902 * Unregisters a subtree.
6904 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6909 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6910 guint registration_id)
6912 ExportedSubtree *es;
6915 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6916 g_return_val_if_fail (check_initialized (connection), FALSE);
6920 CONNECTION_LOCK (connection);
6922 es = g_hash_table_lookup (connection->map_id_to_es,
6923 GUINT_TO_POINTER (registration_id));
6927 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6928 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6933 CONNECTION_UNLOCK (connection);
6938 /* ---------------------------------------------------------------------------------------------------- */
6940 /* may be called in any thread, with connection's lock held */
6942 handle_generic_ping_unlocked (GDBusConnection *connection,
6943 const gchar *object_path,
6944 GDBusMessage *message)
6946 GDBusMessage *reply;
6947 reply = g_dbus_message_new_method_reply (message);
6948 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6949 g_object_unref (reply);
6952 /* may be called in any thread, with connection's lock held */
6954 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6955 const gchar *object_path,
6956 GDBusMessage *message)
6958 GDBusMessage *reply;
6961 if (connection->machine_id == NULL)
6966 connection->machine_id = _g_dbus_get_machine_id (&error);
6967 if (connection->machine_id == NULL)
6969 reply = g_dbus_message_new_method_error_literal (message,
6970 "org.freedesktop.DBus.Error.Failed",
6972 g_error_free (error);
6978 reply = g_dbus_message_new_method_reply (message);
6979 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6981 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6982 g_object_unref (reply);
6985 /* may be called in any thread, with connection's lock held */
6987 handle_generic_introspect_unlocked (GDBusConnection *connection,
6988 const gchar *object_path,
6989 GDBusMessage *message)
6994 GDBusMessage *reply;
6996 /* first the header */
6997 s = g_string_new (NULL);
6998 introspect_append_header (s);
7000 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
7001 for (n = 0; registered != NULL && registered[n] != NULL; n++)
7002 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
7003 g_strfreev (registered);
7004 g_string_append (s, "</node>\n");
7006 reply = g_dbus_message_new_method_reply (message);
7007 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
7008 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7009 g_object_unref (reply);
7010 g_string_free (s, TRUE);
7013 /* may be called in any thread, with connection's lock held */
7015 handle_generic_unlocked (GDBusConnection *connection,
7016 GDBusMessage *message)
7019 const gchar *interface_name;
7020 const gchar *member;
7021 const gchar *signature;
7024 CONNECTION_ENSURE_LOCK (connection);
7028 interface_name = g_dbus_message_get_interface (message);
7029 member = g_dbus_message_get_member (message);
7030 signature = g_dbus_message_get_signature (message);
7031 path = g_dbus_message_get_path (message);
7033 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
7034 g_strcmp0 (member, "Introspect") == 0 &&
7035 g_strcmp0 (signature, "") == 0)
7037 handle_generic_introspect_unlocked (connection, path, message);
7040 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7041 g_strcmp0 (member, "Ping") == 0 &&
7042 g_strcmp0 (signature, "") == 0)
7044 handle_generic_ping_unlocked (connection, path, message);
7047 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
7048 g_strcmp0 (member, "GetMachineId") == 0 &&
7049 g_strcmp0 (signature, "") == 0)
7051 handle_generic_get_machine_id_unlocked (connection, path, message);
7058 /* ---------------------------------------------------------------------------------------------------- */
7060 /* called in GDBusWorker thread with connection's lock held */
7062 distribute_method_call (GDBusConnection *connection,
7063 GDBusMessage *message)
7065 GDBusMessage *reply;
7067 ExportedSubtree *es;
7068 const gchar *object_path;
7069 const gchar *interface_name;
7070 const gchar *member;
7072 gchar *subtree_path;
7075 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
7077 interface_name = g_dbus_message_get_interface (message);
7078 member = g_dbus_message_get_member (message);
7079 path = g_dbus_message_get_path (message);
7080 subtree_path = g_strdup (path);
7081 needle = strrchr (subtree_path, '/');
7082 if (needle != NULL && needle != subtree_path)
7088 g_free (subtree_path);
7089 subtree_path = NULL;
7093 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
7095 _g_dbus_debug_print_lock ();
7096 g_print ("========================================================================\n"
7097 "GDBus-debug:Incoming:\n"
7098 " <<<< METHOD INVOCATION %s.%s()\n"
7100 " invoked by name %s\n"
7102 interface_name, member,
7104 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
7105 g_dbus_message_get_serial (message));
7106 _g_dbus_debug_print_unlock ();
7109 object_path = g_dbus_message_get_path (message);
7110 g_assert (object_path != NULL);
7112 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
7115 if (obj_message_func (connection, eo, message))
7119 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
7122 if (subtree_message_func (connection, es, message))
7126 if (subtree_path != NULL)
7128 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
7131 if (subtree_message_func (connection, es, message))
7136 if (handle_generic_unlocked (connection, message))
7139 /* if we end up here, the message has not been not handled - so return an error saying this */
7140 reply = g_dbus_message_new_method_error (message,
7141 "org.freedesktop.DBus.Error.UnknownMethod",
7142 _("No such interface “%s” on object at path %s"),
7145 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
7146 g_object_unref (reply);
7149 g_free (subtree_path);
7152 /* ---------------------------------------------------------------------------------------------------- */
7154 /* Called in any user thread, with the message_bus_lock held. */
7156 message_bus_get_singleton (GBusType bus_type,
7160 const gchar *starter_bus;
7166 case G_BUS_TYPE_SESSION:
7167 ret = &the_session_bus;
7170 case G_BUS_TYPE_SYSTEM:
7171 ret = &the_system_bus;
7174 case G_BUS_TYPE_STARTER:
7175 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
7176 if (g_strcmp0 (starter_bus, "session") == 0)
7178 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
7181 else if (g_strcmp0 (starter_bus, "system") == 0)
7183 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
7188 if (starter_bus != NULL)
7192 G_IO_ERROR_INVALID_ARGUMENT,
7193 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
7194 " — unknown value “%s”"),
7199 g_set_error_literal (error,
7201 G_IO_ERROR_INVALID_ARGUMENT,
7202 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
7203 "variable is not set"));
7209 g_assert_not_reached ();
7217 /* Called in any user thread, without holding locks. */
7218 static GDBusConnection *
7219 get_uninitialized_connection (GBusType bus_type,
7220 GCancellable *cancellable,
7223 GWeakRef *singleton;
7224 GDBusConnection *ret;
7228 G_LOCK (message_bus_lock);
7229 singleton = message_bus_get_singleton (bus_type, error);
7230 if (singleton == NULL)
7233 ret = g_weak_ref_get (singleton);
7238 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
7239 if (address == NULL)
7241 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
7243 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
7244 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
7245 "exit-on-close", TRUE,
7248 g_weak_ref_set (singleton, ret);
7252 g_assert (ret != NULL);
7255 G_UNLOCK (message_bus_lock);
7259 /* May be called from any thread. Must not hold message_bus_lock. */
7261 _g_bus_get_singleton_if_exists (GBusType bus_type)
7263 GWeakRef *singleton;
7264 GDBusConnection *ret = NULL;
7266 G_LOCK (message_bus_lock);
7267 singleton = message_bus_get_singleton (bus_type, NULL);
7268 if (singleton == NULL)
7271 ret = g_weak_ref_get (singleton);
7274 G_UNLOCK (message_bus_lock);
7278 /* May be called from any thread. Must not hold message_bus_lock. */
7280 _g_bus_forget_singleton (GBusType bus_type)
7282 GWeakRef *singleton;
7284 G_LOCK (message_bus_lock);
7286 singleton = message_bus_get_singleton (bus_type, NULL);
7288 if (singleton != NULL)
7289 g_weak_ref_set (singleton, NULL);
7291 G_UNLOCK (message_bus_lock);
7296 * @bus_type: a #GBusType
7297 * @cancellable: (nullable): a #GCancellable or %NULL
7298 * @error: return location for error or %NULL
7300 * Synchronously connects to the message bus specified by @bus_type.
7301 * Note that the returned object may shared with other callers,
7302 * e.g. if two separate parts of a process calls this function with
7303 * the same @bus_type, they will share the same object.
7305 * This is a synchronous failable function. See g_bus_get() and
7306 * g_bus_get_finish() for the asynchronous version.
7308 * The returned object is a singleton, that is, shared with other
7309 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7310 * event that you need a private message bus connection, use
7311 * g_dbus_address_get_for_bus_sync() and
7312 * g_dbus_connection_new_for_address().
7314 * Note that the returned #GDBusConnection object will (usually) have
7315 * the #GDBusConnection:exit-on-close property set to %TRUE.
7317 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7318 * Free with g_object_unref().
7323 g_bus_get_sync (GBusType bus_type,
7324 GCancellable *cancellable,
7327 GDBusConnection *connection;
7329 _g_dbus_initialize ();
7331 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7333 connection = get_uninitialized_connection (bus_type, cancellable, error);
7334 if (connection == NULL)
7337 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7339 g_object_unref (connection);
7348 bus_get_async_initable_cb (GObject *source_object,
7352 GTask *task = user_data;
7353 GError *error = NULL;
7355 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7359 g_assert (error != NULL);
7360 g_task_return_error (task, error);
7361 g_object_unref (source_object);
7365 g_task_return_pointer (task, source_object, g_object_unref);
7367 g_object_unref (task);
7372 * @bus_type: a #GBusType
7373 * @cancellable: (nullable): a #GCancellable or %NULL
7374 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7375 * @user_data: the data to pass to @callback
7377 * Asynchronously connects to the message bus specified by @bus_type.
7379 * When the operation is finished, @callback will be invoked. You can
7380 * then call g_bus_get_finish() to get the result of the operation.
7382 * This is an asynchronous failable function. See g_bus_get_sync() for
7383 * the synchronous version.
7388 g_bus_get (GBusType bus_type,
7389 GCancellable *cancellable,
7390 GAsyncReadyCallback callback,
7393 GDBusConnection *connection;
7395 GError *error = NULL;
7397 _g_dbus_initialize ();
7399 task = g_task_new (NULL, cancellable, callback, user_data);
7400 g_task_set_source_tag (task, g_bus_get);
7402 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7403 if (connection == NULL)
7405 g_assert (error != NULL);
7406 g_task_return_error (task, error);
7407 g_object_unref (task);
7411 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7414 bus_get_async_initable_cb,
7421 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7423 * @error: return location for error or %NULL
7425 * Finishes an operation started with g_bus_get().
7427 * The returned object is a singleton, that is, shared with other
7428 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7429 * event that you need a private message bus connection, use
7430 * g_dbus_address_get_for_bus_sync() and
7431 * g_dbus_connection_new_for_address().
7433 * Note that the returned #GDBusConnection object will (usually) have
7434 * the #GDBusConnection:exit-on-close property set to %TRUE.
7436 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7437 * Free with g_object_unref().
7442 g_bus_get_finish (GAsyncResult *res,
7445 g_return_val_if_fail (g_task_is_valid (res, NULL), NULL);
7446 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7448 return g_task_propagate_pointer (G_TASK (res), error);
7451 /* ---------------------------------------------------------------------------------------------------- */