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 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, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * Most of the ways to obtain a #GDBusConnection automatically initialize it
152 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
153 * g_bus_get(), and the synchronous versions of those methods, give you an
154 * initialized connection. Language bindings for GIO should use
155 * g_initable_new() or g_async_initable_new(), which also initialize the
158 * If you construct an uninitialized #GDBusConnection, such as via
159 * g_object_new(), you must initialize it via g_initable_init() or
160 * g_async_initable_init() before using its methods or properties. Calling
161 * methods or accessing properties on a #GDBusConnection that has not completed
162 * initialization successfully is considered to be invalid, and leads to
163 * undefined behaviour. In particular, if initialization fails with a #GError,
164 * the only valid thing you can do with that #GDBusConnection is to free it
165 * with g_object_unref().
167 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
169 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
171 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
173 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
176 /* ---------------------------------------------------------------------------------------------------- */
178 typedef struct _GDBusConnectionClass GDBusConnectionClass;
181 * GDBusConnectionClass:
182 * @closed: Signal class handler for the #GDBusConnection::closed signal.
184 * Class structure for #GDBusConnection.
188 struct _GDBusConnectionClass
191 GObjectClass parent_class;
195 void (*closed) (GDBusConnection *connection,
196 gboolean remote_peer_vanished,
200 G_LOCK_DEFINE_STATIC (message_bus_lock);
202 static GDBusConnection *the_session_bus = NULL;
203 static GDBusConnection *the_system_bus = NULL;
205 /* Extra pseudo-member of GDBusSendMessageFlags.
206 * Set by initable_init() to indicate that despite not being initialized yet,
207 * enough of the only-valid-after-init members are set that we can send a
208 * message, and we're being called from its thread, so no memory barrier is
209 * required before accessing them.
211 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
213 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
214 #define CALL_FLAGS_INITIALIZING (1<<31)
216 /* ---------------------------------------------------------------------------------------------------- */
220 GDestroyNotify callback;
222 GMainContext *context;
223 } CallDestroyNotifyData;
226 call_destroy_notify_data_in_idle (gpointer user_data)
228 CallDestroyNotifyData *data = user_data;
229 data->callback (data->user_data);
234 call_destroy_notify_data_free (CallDestroyNotifyData *data)
236 if (data->context != NULL)
237 g_main_context_unref (data->context);
242 * call_destroy_notify: <internal>
243 * @context: A #GMainContext or %NULL.
244 * @callback: A #GDestroyNotify or %NULL.
245 * @user_data: Data to pass to @callback.
247 * Schedules @callback to run in @context.
250 call_destroy_notify (GMainContext *context,
251 GDestroyNotify callback,
254 GMainContext *current_context;
256 if (callback == NULL)
259 current_context = g_main_context_get_thread_default ();
260 if ((context == current_context) ||
261 (current_context == NULL && context == g_main_context_default ()))
263 callback (user_data);
267 GSource *idle_source;
268 CallDestroyNotifyData *data;
270 data = g_new0 (CallDestroyNotifyData, 1);
271 data->callback = callback;
272 data->user_data = user_data;
273 data->context = context;
274 if (data->context != NULL)
275 g_main_context_ref (data->context);
277 idle_source = g_idle_source_new ();
278 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
279 g_source_set_callback (idle_source,
280 call_destroy_notify_data_in_idle,
282 (GDestroyNotify) call_destroy_notify_data_free);
283 g_source_attach (idle_source, data->context);
284 g_source_unref (idle_source);
291 /* ---------------------------------------------------------------------------------------------------- */
294 _g_strv_has_string (const gchar* const *haystack,
299 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
301 if (g_strcmp0 (haystack[n], needle) == 0)
307 /* ---------------------------------------------------------------------------------------------------- */
310 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
312 // TODO: for some reason this doesn't work on Windows
313 #define CONNECTION_ENSURE_LOCK(obj) do { \
314 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
316 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
317 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
322 #define CONNECTION_LOCK(obj) do { \
323 g_mutex_lock (&(obj)->lock); \
326 #define CONNECTION_UNLOCK(obj) do { \
327 g_mutex_unlock (&(obj)->lock); \
330 /* Flags in connection->atomic_flags */
332 FLAG_INITIALIZED = 1 << 0,
333 FLAG_EXIT_ON_CLOSE = 1 << 1
339 * The #GDBusConnection structure contains only private data and
340 * should only be accessed using the provided API.
344 struct _GDBusConnection
347 GObject parent_instance;
349 /* ------------------------------------------------------------------------ */
350 /* -- General object state ------------------------------------------------ */
351 /* ------------------------------------------------------------------------ */
353 /* General-purpose lock for most fields */
356 /* A lock used in the init() method of the GInitable interface - see comments
357 * in initable_init() for why a separate lock is needed.
359 * If you need both @lock and @init_lock, you must take @init_lock first.
363 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
364 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
368 /* The underlying stream used for communication
369 * Read-only after initable_init(), so it may be read if you either
370 * hold @init_lock or check for initialization first.
374 /* The object used for authentication (if any).
375 * Read-only after initable_init(), so it may be read if you either
376 * hold @init_lock or check for initialization first.
380 /* Set to TRUE if the connection has been closed */
383 /* Last serial used. Protected by @lock. */
386 /* The object used to send/receive messages.
387 * Read-only after initable_init(), so it may be read if you either
388 * hold @init_lock or check for initialization first.
392 /* If connected to a message bus, this contains the unique name assigned to
393 * us by the bus (e.g. ":1.42").
394 * Read-only after initable_init(), so it may be read if you either
395 * hold @init_lock or check for initialization first.
397 gchar *bus_unique_name;
399 /* The GUID returned by the other side if we authenticed as a client or
400 * the GUID to use if authenticating as a server.
401 * Read-only after initable_init(), so it may be read if you either
402 * hold @init_lock or check for initialization first.
406 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
407 * Inspect @initialization_error to see whether it succeeded or failed.
409 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
411 volatile gint atomic_flags;
413 /* If the connection could not be established during initable_init(),
414 * this GError will be set.
415 * Read-only after initable_init(), so it may be read if you either
416 * hold @init_lock or check for initialization first.
418 GError *initialization_error;
420 /* The result of g_main_context_ref_thread_default() when the object
421 * was created (the GObject _init() function) - this is used for delivery
422 * of the :closed GObject signal.
424 * Only set in the GObject init function, so no locks are needed.
426 GMainContext *main_context_at_construction;
428 /* Read-only construct properties, no locks needed */
430 GDBusConnectionFlags flags;
432 /* Map used for managing method replies, protected by @lock */
433 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
435 /* Maps used for managing signal subscription, protected by @lock */
436 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
437 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
438 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
440 /* Maps used for managing exported objects and subtrees,
443 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
444 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
445 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
446 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
448 /* Structure used for message filters, protected by @lock */
451 /* Capabilities negotiated during authentication
452 * Read-only after initable_init(), so it may be read without holding a
453 * lock, if you check for initialization first.
455 GDBusCapabilityFlags capabilities;
457 /* Protected by @init_lock */
458 GDBusAuthObserver *authentication_observer;
460 /* Read-only after initable_init(), so it may be read if you either
461 * hold @init_lock or check for initialization first.
463 GCredentials *credentials;
465 /* set to TRUE when finalizing */
469 typedef struct ExportedObject ExportedObject;
470 static void exported_object_free (ExportedObject *eo);
472 typedef struct ExportedSubtree ExportedSubtree;
473 static void exported_subtree_free (ExportedSubtree *es);
491 PROP_CAPABILITY_FLAGS,
492 PROP_AUTHENTICATION_OBSERVER,
495 static void distribute_signals (GDBusConnection *connection,
496 GDBusMessage *message);
498 static void distribute_method_call (GDBusConnection *connection,
499 GDBusMessage *message);
501 static gboolean handle_generic_unlocked (GDBusConnection *connection,
502 GDBusMessage *message);
505 static void purge_all_signal_subscriptions (GDBusConnection *connection);
506 static void purge_all_filters (GDBusConnection *connection);
508 #define _G_ENSURE_LOCK(name) do { \
509 if (G_UNLIKELY (G_TRYLOCK(name))) \
511 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
512 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
516 static guint signals[LAST_SIGNAL] = { 0 };
518 static void initable_iface_init (GInitableIface *initable_iface);
519 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
521 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
522 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
523 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
527 * Check that all members of @connection that can only be accessed after
528 * the connection is initialized can safely be accessed. If not,
529 * log a critical warning. This function is a memory barrier.
531 * Returns: %TRUE if initialized
534 check_initialized (GDBusConnection *connection)
536 /* The access to @atomic_flags isn't conditional, so that this function
537 * provides a memory barrier for thread-safety even if checks are disabled.
538 * (If you don't want this stricter guarantee, you can call
539 * g_return_if_fail (check_initialized (c)).)
541 * This isn't strictly necessary now that we've decided use of an
542 * uninitialized GDBusConnection is undefined behaviour, but it seems
543 * better to be as deterministic as is feasible.
545 * (Anything that could suffer a crash from seeing undefined values
546 * must have a race condition - thread A initializes the connection while
547 * thread B calls a method without initialization, hoping that thread A will
548 * win the race - so its behaviour is undefined anyway.)
550 gint flags = g_atomic_int_get (&connection->atomic_flags);
552 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
554 /* We can safely access this, due to the memory barrier above */
555 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
560 static GHashTable *alive_connections = NULL;
563 g_dbus_connection_dispose (GObject *object)
565 GDBusConnection *connection = G_DBUS_CONNECTION (object);
567 G_LOCK (message_bus_lock);
568 if (connection == the_session_bus)
570 the_session_bus = NULL;
572 else if (connection == the_system_bus)
574 the_system_bus = NULL;
576 CONNECTION_LOCK (connection);
577 if (connection->worker != NULL)
579 _g_dbus_worker_stop (connection->worker);
580 connection->worker = NULL;
581 if (alive_connections != NULL)
582 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
586 if (alive_connections != NULL)
587 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
589 CONNECTION_UNLOCK (connection);
590 G_UNLOCK (message_bus_lock);
592 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
593 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
597 g_dbus_connection_finalize (GObject *object)
599 GDBusConnection *connection = G_DBUS_CONNECTION (object);
601 connection->finalizing = TRUE;
603 purge_all_signal_subscriptions (connection);
605 purge_all_filters (connection);
606 g_ptr_array_unref (connection->filters);
608 if (connection->authentication_observer != NULL)
609 g_object_unref (connection->authentication_observer);
611 if (connection->auth != NULL)
612 g_object_unref (connection->auth);
614 if (connection->credentials)
615 g_object_unref (connection->credentials);
617 if (connection->stream != NULL)
619 g_object_unref (connection->stream);
620 connection->stream = NULL;
623 g_free (connection->address);
625 g_free (connection->guid);
626 g_free (connection->bus_unique_name);
628 if (connection->initialization_error != NULL)
629 g_error_free (connection->initialization_error);
631 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
633 g_hash_table_unref (connection->map_rule_to_signal_data);
634 g_hash_table_unref (connection->map_id_to_signal_data);
635 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
637 g_hash_table_unref (connection->map_id_to_ei);
638 g_hash_table_unref (connection->map_object_path_to_eo);
639 g_hash_table_unref (connection->map_id_to_es);
640 g_hash_table_unref (connection->map_object_path_to_es);
642 g_main_context_unref (connection->main_context_at_construction);
644 g_free (connection->machine_id);
646 g_mutex_clear (&connection->init_lock);
647 g_mutex_clear (&connection->lock);
649 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
652 /* called in any user thread, with the connection's lock not held */
654 g_dbus_connection_get_property (GObject *object,
659 GDBusConnection *connection = G_DBUS_CONNECTION (object);
664 g_value_set_object (value, g_dbus_connection_get_stream (connection));
668 g_value_set_string (value, g_dbus_connection_get_guid (connection));
671 case PROP_UNIQUE_NAME:
672 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
676 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
679 case PROP_EXIT_ON_CLOSE:
680 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
683 case PROP_CAPABILITY_FLAGS:
684 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
688 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
693 /* called in any user thread, with the connection's lock not held */
695 g_dbus_connection_set_property (GObject *object,
700 GDBusConnection *connection = G_DBUS_CONNECTION (object);
705 connection->stream = g_value_dup_object (value);
709 connection->guid = g_value_dup_string (value);
713 connection->address = g_value_dup_string (value);
717 connection->flags = g_value_get_flags (value);
720 case PROP_EXIT_ON_CLOSE:
721 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
724 case PROP_AUTHENTICATION_OBSERVER:
725 connection->authentication_observer = g_value_dup_object (value);
729 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
734 /* Base-class implementation of GDBusConnection::closed.
736 * Called in a user thread, by the main context that was thread-default when
737 * the object was constructed.
740 g_dbus_connection_real_closed (GDBusConnection *connection,
741 gboolean remote_peer_vanished,
744 gint flags = g_atomic_int_get (&connection->atomic_flags);
746 /* Because atomic int access is a memory barrier, we can safely read
747 * initialization_error without a lock, as long as we do it afterwards.
749 if (remote_peer_vanished &&
750 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
751 (flags & FLAG_INITIALIZED) != 0 &&
752 connection->initialization_error == NULL)
756 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
759 g_quark_to_string (error->domain), error->code);
763 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
770 g_dbus_connection_class_init (GDBusConnectionClass *klass)
772 GObjectClass *gobject_class;
774 gobject_class = G_OBJECT_CLASS (klass);
776 gobject_class->finalize = g_dbus_connection_finalize;
777 gobject_class->dispose = g_dbus_connection_dispose;
778 gobject_class->set_property = g_dbus_connection_set_property;
779 gobject_class->get_property = g_dbus_connection_get_property;
781 klass->closed = g_dbus_connection_real_closed;
784 * GDBusConnection:stream:
786 * The underlying #GIOStream used for I/O.
788 * If this is passed on construction and is a #GSocketConnection,
789 * then the corresponding #GSocket will be put into non-blocking mode.
791 * While the #GDBusConnection is active, it will interact with this
792 * stream from a worker thread, so it is not safe to interact with
793 * the stream directly.
797 g_object_class_install_property (gobject_class,
799 g_param_spec_object ("stream",
801 P_("The underlying streams used for I/O"),
805 G_PARAM_CONSTRUCT_ONLY |
806 G_PARAM_STATIC_NAME |
807 G_PARAM_STATIC_BLURB |
808 G_PARAM_STATIC_NICK));
811 * GDBusConnection:address:
813 * A D-Bus address specifying potential endpoints that can be used
814 * when establishing the connection.
818 g_object_class_install_property (gobject_class,
820 g_param_spec_string ("address",
822 P_("D-Bus address specifying potential socket endpoints"),
825 G_PARAM_CONSTRUCT_ONLY |
826 G_PARAM_STATIC_NAME |
827 G_PARAM_STATIC_BLURB |
828 G_PARAM_STATIC_NICK));
831 * GDBusConnection:flags:
833 * Flags from the #GDBusConnectionFlags enumeration.
837 g_object_class_install_property (gobject_class,
839 g_param_spec_flags ("flags",
842 G_TYPE_DBUS_CONNECTION_FLAGS,
843 G_DBUS_CONNECTION_FLAGS_NONE,
845 G_PARAM_CONSTRUCT_ONLY |
846 G_PARAM_STATIC_NAME |
847 G_PARAM_STATIC_BLURB |
848 G_PARAM_STATIC_NICK));
851 * GDBusConnection:guid:
853 * The GUID of the peer performing the role of server when
856 * If you are constructing a #GDBusConnection and pass
857 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
858 * #GDBusConnection:flags property then you MUST also set this
859 * property to a valid guid.
861 * If you are constructing a #GDBusConnection and pass
862 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
863 * #GDBusConnection:flags property you will be able to read the GUID
864 * of the other peer here after the connection has been successfully
869 g_object_class_install_property (gobject_class,
871 g_param_spec_string ("guid",
873 P_("GUID of the server peer"),
877 G_PARAM_CONSTRUCT_ONLY |
878 G_PARAM_STATIC_NAME |
879 G_PARAM_STATIC_BLURB |
880 G_PARAM_STATIC_NICK));
883 * GDBusConnection:unique-name:
885 * The unique name as assigned by the message bus or %NULL if the
886 * connection is not open or not a message bus connection.
890 g_object_class_install_property (gobject_class,
892 g_param_spec_string ("unique-name",
894 P_("Unique name of bus connection"),
897 G_PARAM_STATIC_NAME |
898 G_PARAM_STATIC_BLURB |
899 G_PARAM_STATIC_NICK));
902 * GDBusConnection:closed:
904 * A boolean specifying whether the connection has been closed.
908 g_object_class_install_property (gobject_class,
910 g_param_spec_boolean ("closed",
912 P_("Whether the connection is closed"),
915 G_PARAM_STATIC_NAME |
916 G_PARAM_STATIC_BLURB |
917 G_PARAM_STATIC_NICK));
920 * GDBusConnection:exit-on-close:
922 * A boolean specifying whether the process will be terminated (by
923 * calling <literal>raise(SIGTERM)</literal>) if the connection
924 * is closed by the remote peer.
928 g_object_class_install_property (gobject_class,
930 g_param_spec_boolean ("exit-on-close",
932 P_("Whether the process is terminated when the connection is closed"),
936 G_PARAM_STATIC_NAME |
937 G_PARAM_STATIC_BLURB |
938 G_PARAM_STATIC_NICK));
941 * GDBusConnection:capabilities:
943 * Flags from the #GDBusCapabilityFlags enumeration
944 * representing connection features negotiated with the other peer.
948 g_object_class_install_property (gobject_class,
949 PROP_CAPABILITY_FLAGS,
950 g_param_spec_flags ("capabilities",
953 G_TYPE_DBUS_CAPABILITY_FLAGS,
954 G_DBUS_CAPABILITY_FLAGS_NONE,
956 G_PARAM_STATIC_NAME |
957 G_PARAM_STATIC_BLURB |
958 G_PARAM_STATIC_NICK));
961 * GDBusConnection:authentication-observer:
963 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
967 g_object_class_install_property (gobject_class,
968 PROP_AUTHENTICATION_OBSERVER,
969 g_param_spec_object ("authentication-observer",
970 P_("Authentication Observer"),
971 P_("Object used to assist in the authentication process"),
972 G_TYPE_DBUS_AUTH_OBSERVER,
974 G_PARAM_CONSTRUCT_ONLY |
975 G_PARAM_STATIC_NAME |
976 G_PARAM_STATIC_BLURB |
977 G_PARAM_STATIC_NICK));
980 * GDBusConnection::closed:
981 * @connection: The #GDBusConnection emitting the signal.
982 * @remote_peer_vanished: %TRUE if @connection is closed because the
983 * remote peer closed its end of the connection.
984 * @error: A #GError with more details about the event or %NULL.
986 * Emitted when the connection is closed.
988 * The cause of this event can be
991 * If g_dbus_connection_close() is called. In this case
992 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
995 * If the remote peer closes the connection. In this case
996 * @remote_peer_vanished is set to %TRUE and @error is set.
999 * If the remote peer sends invalid or malformed data. In this
1000 * case @remote_peer_vanished is set to %FALSE and @error
1002 * </para></listitem>
1005 * Upon receiving this signal, you should give up your reference to
1006 * @connection. You are guaranteed that this signal is emitted only
1011 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1012 G_TYPE_DBUS_CONNECTION,
1014 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1025 g_dbus_connection_init (GDBusConnection *connection)
1027 g_mutex_init (&connection->lock);
1028 g_mutex_init (&connection->init_lock);
1030 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1032 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1034 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1036 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1039 (GDestroyNotify) g_ptr_array_unref);
1041 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1044 (GDestroyNotify) exported_object_free);
1046 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1049 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1052 (GDestroyNotify) exported_subtree_free);
1054 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1057 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1059 connection->filters = g_ptr_array_new ();
1063 * g_dbus_connection_get_stream:
1064 * @connection: a #GDBusConnection
1066 * Gets the underlying stream used for IO.
1068 * While the #GDBusConnection is active, it will interact with this
1069 * stream from a worker thread, so it is not safe to interact with
1070 * the stream directly.
1072 * Returns: (transfer none): the stream used for IO
1077 g_dbus_connection_get_stream (GDBusConnection *connection)
1079 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1081 /* do not use g_return_val_if_fail(), we want the memory barrier */
1082 if (!check_initialized (connection))
1085 return connection->stream;
1089 * g_dbus_connection_start_message_processing:
1090 * @connection: A #GDBusConnection.
1092 * If @connection was created with
1093 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1094 * starts processing messages. Does nothing on if @connection wasn't
1095 * created with this flag or if the method has already been called.
1100 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1102 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1104 /* do not use g_return_val_if_fail(), we want the memory barrier */
1105 if (!check_initialized (connection))
1108 g_assert (connection->worker != NULL);
1109 _g_dbus_worker_unfreeze (connection->worker);
1113 * g_dbus_connection_is_closed:
1114 * @connection: A #GDBusConnection.
1116 * Gets whether @connection is closed.
1118 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1123 g_dbus_connection_is_closed (GDBusConnection *connection)
1125 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1126 return connection->closed;
1130 * g_dbus_connection_get_capabilities:
1131 * @connection: A #GDBusConnection.
1133 * Gets the capabilities negotiated with the remote peer
1135 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1139 GDBusCapabilityFlags
1140 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1142 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1144 /* do not use g_return_val_if_fail(), we want the memory barrier */
1145 if (!check_initialized (connection))
1146 return G_DBUS_CAPABILITY_FLAGS_NONE;
1148 return connection->capabilities;
1151 /* ---------------------------------------------------------------------------------------------------- */
1153 /* Called in a temporary thread without holding locks. */
1155 flush_in_thread_func (GSimpleAsyncResult *res,
1157 GCancellable *cancellable)
1162 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1165 g_simple_async_result_take_error (res, error);
1169 * g_dbus_connection_flush:
1170 * @connection: A #GDBusConnection.
1171 * @cancellable: A #GCancellable or %NULL.
1172 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1173 * satisfied or %NULL if you don't care about the result.
1174 * @user_data: The data to pass to @callback.
1176 * Asynchronously flushes @connection, that is, writes all queued
1177 * outgoing message to the transport and then flushes the transport
1178 * (using g_output_stream_flush_async()). This is useful in programs
1179 * that wants to emit a D-Bus signal and then exit
1180 * immediately. Without flushing the connection, there is no guarantee
1181 * that the message has been sent to the networking buffers in the OS
1184 * This is an asynchronous method. When the operation is finished,
1185 * @callback will be invoked in the <link
1186 * linkend="g-main-context-push-thread-default">thread-default main
1187 * loop</link> of the thread you are calling this method from. You can
1188 * then call g_dbus_connection_flush_finish() to get the result of the
1189 * operation. See g_dbus_connection_flush_sync() for the synchronous
1195 g_dbus_connection_flush (GDBusConnection *connection,
1196 GCancellable *cancellable,
1197 GAsyncReadyCallback callback,
1200 GSimpleAsyncResult *simple;
1202 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1204 simple = g_simple_async_result_new (G_OBJECT (connection),
1207 g_dbus_connection_flush);
1208 g_simple_async_result_run_in_thread (simple,
1209 flush_in_thread_func,
1212 g_object_unref (simple);
1216 * g_dbus_connection_flush_finish:
1217 * @connection: A #GDBusConnection.
1218 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1219 * @error: Return location for error or %NULL.
1221 * Finishes an operation started with g_dbus_connection_flush().
1223 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1228 g_dbus_connection_flush_finish (GDBusConnection *connection,
1232 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1237 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1238 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1239 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1241 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1243 if (g_simple_async_result_propagate_error (simple, error))
1253 * g_dbus_connection_flush_sync:
1254 * @connection: A #GDBusConnection.
1255 * @cancellable: A #GCancellable or %NULL.
1256 * @error: Return location for error or %NULL.
1258 * Synchronously flushes @connection. The calling thread is blocked
1259 * until this is done. See g_dbus_connection_flush() for the
1260 * asynchronous version of this method and more details about what it
1263 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1268 g_dbus_connection_flush_sync (GDBusConnection *connection,
1269 GCancellable *cancellable,
1274 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1275 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1279 /* do not use g_return_val_if_fail(), we want the memory barrier */
1280 if (!check_initialized (connection))
1283 g_assert (connection->worker != NULL);
1285 if (connection->closed)
1287 g_set_error_literal (error,
1290 _("The connection is closed"));
1294 ret = _g_dbus_worker_flush_sync (connection->worker,
1302 /* ---------------------------------------------------------------------------------------------------- */
1306 GDBusConnection *connection;
1308 gboolean remote_peer_vanished;
1312 emit_closed_data_free (EmitClosedData *data)
1314 g_object_unref (data->connection);
1315 if (data->error != NULL)
1316 g_error_free (data->error);
1320 /* Called in a user thread that has acquired the main context that was
1321 * thread-default when the object was constructed
1324 emit_closed_in_idle (gpointer user_data)
1326 EmitClosedData *data = user_data;
1329 g_object_notify (G_OBJECT (data->connection), "closed");
1330 g_signal_emit (data->connection,
1331 signals[CLOSED_SIGNAL],
1333 data->remote_peer_vanished,
1339 /* Can be called from any thread, must hold lock */
1341 set_closed_unlocked (GDBusConnection *connection,
1342 gboolean remote_peer_vanished,
1345 GSource *idle_source;
1346 EmitClosedData *data;
1348 CONNECTION_ENSURE_LOCK (connection);
1350 g_assert (!connection->closed);
1352 connection->closed = TRUE;
1354 data = g_new0 (EmitClosedData, 1);
1355 data->connection = g_object_ref (connection);
1356 data->remote_peer_vanished = remote_peer_vanished;
1357 data->error = error != NULL ? g_error_copy (error) : NULL;
1359 idle_source = g_idle_source_new ();
1360 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1361 g_source_set_callback (idle_source,
1362 emit_closed_in_idle,
1364 (GDestroyNotify) emit_closed_data_free);
1365 g_source_attach (idle_source, connection->main_context_at_construction);
1366 g_source_unref (idle_source);
1369 /* ---------------------------------------------------------------------------------------------------- */
1372 * g_dbus_connection_close:
1373 * @connection: A #GDBusConnection.
1374 * @cancellable: A #GCancellable or %NULL.
1375 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1376 * satisfied or %NULL if you don't care about the result.
1377 * @user_data: The data to pass to @callback.
1379 * Closes @connection. Note that this never causes the process to
1380 * exit (this might only happen if the other end of a shared message
1381 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1383 * Once the connection is closed, operations such as sending a message
1384 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1385 * will not automatically flush the connection so queued messages may
1386 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1388 * If @connection is already closed, this method fails with
1389 * %G_IO_ERROR_CLOSED.
1391 * When @connection has been closed, the #GDBusConnection::closed
1392 * signal is emitted in the <link
1393 * linkend="g-main-context-push-thread-default">thread-default main
1394 * loop</link> of the thread that @connection was constructed in.
1396 * This is an asynchronous method. When the operation is finished,
1397 * @callback will be invoked in the <link
1398 * linkend="g-main-context-push-thread-default">thread-default main
1399 * loop</link> of the thread you are calling this method from. You can
1400 * then call g_dbus_connection_close_finish() to get the result of the
1401 * operation. See g_dbus_connection_close_sync() for the synchronous
1407 g_dbus_connection_close (GDBusConnection *connection,
1408 GCancellable *cancellable,
1409 GAsyncReadyCallback callback,
1412 GSimpleAsyncResult *simple;
1414 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1416 /* do not use g_return_val_if_fail(), we want the memory barrier */
1417 if (!check_initialized (connection))
1420 g_assert (connection->worker != NULL);
1422 simple = g_simple_async_result_new (G_OBJECT (connection),
1425 g_dbus_connection_close);
1426 _g_dbus_worker_close (connection->worker, cancellable, simple);
1427 g_object_unref (simple);
1431 * g_dbus_connection_close_finish:
1432 * @connection: A #GDBusConnection.
1433 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1434 * @error: Return location for error or %NULL.
1436 * Finishes an operation started with g_dbus_connection_close().
1438 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1443 g_dbus_connection_close_finish (GDBusConnection *connection,
1447 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1452 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1453 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1454 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1456 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1458 if (g_simple_async_result_propagate_error (simple, error))
1469 GAsyncResult *result;
1472 /* Can be called by any thread, without the connection lock */
1474 sync_close_cb (GObject *source_object,
1478 SyncCloseData *data = user_data;
1480 data->result = g_object_ref (res);
1481 g_main_loop_quit (data->loop);
1485 * g_dbus_connection_close_sync:
1486 * @connection: A #GDBusConnection.
1487 * @cancellable: A #GCancellable or %NULL.
1488 * @error: Return location for error or %NULL.
1490 * Synchronously closees @connection. The calling thread is blocked
1491 * until this is done. See g_dbus_connection_close() for the
1492 * asynchronous version of this method and more details about what it
1495 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1500 g_dbus_connection_close_sync (GDBusConnection *connection,
1501 GCancellable *cancellable,
1506 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1507 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1511 CONNECTION_LOCK (connection);
1512 if (!connection->closed)
1514 GMainContext *context;
1517 context = g_main_context_new ();
1518 g_main_context_push_thread_default (context);
1519 data.loop = g_main_loop_new (context, TRUE);
1522 CONNECTION_UNLOCK (connection);
1523 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1524 g_main_loop_run (data.loop);
1525 ret = g_dbus_connection_close_finish (connection, data.result, error);
1526 CONNECTION_LOCK (connection);
1528 g_object_unref (data.result);
1529 g_main_loop_unref (data.loop);
1530 g_main_context_pop_thread_default (context);
1531 g_main_context_unref (context);
1535 g_set_error_literal (error,
1538 _("The connection is closed"));
1540 CONNECTION_UNLOCK (connection);
1545 /* ---------------------------------------------------------------------------------------------------- */
1547 /* Can be called by any thread, with the connection lock held */
1549 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1550 GDBusMessage *message,
1551 GDBusSendMessageFlags flags,
1552 volatile guint32 *out_serial,
1557 guint32 serial_to_use;
1560 CONNECTION_ENSURE_LOCK (connection);
1562 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1563 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1565 /* TODO: check all necessary headers are present */
1570 if (out_serial != NULL)
1573 /* If we're in initable_init(), don't check for being initialized, to avoid
1574 * chicken-and-egg problems. initable_init() is responsible for setting up
1575 * our prerequisites (mainly connection->worker), and only calling us
1576 * from its own thread (so no memory barrier is needed).
1578 * In the case where we're not initializing, do not use
1579 * g_return_val_if_fail() - we want the memory barrier.
1581 if ((flags & SEND_MESSAGE_FLAGS_INITIALIZING) == 0 &&
1582 !check_initialized (connection))
1585 if (connection->closed)
1587 g_set_error_literal (error,
1590 _("The connection is closed"));
1594 blob = g_dbus_message_to_blob (message,
1596 connection->capabilities,
1601 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1602 serial_to_use = g_dbus_message_get_serial (message);
1604 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1609 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1612 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1615 g_assert_not_reached ();
1620 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1621 blob_size, serial_to_use, connection);
1622 g_printerr ("----\n");
1623 hexdump (blob, blob_size);
1624 g_printerr ("----\n");
1627 /* TODO: use connection->auth to encode the blob */
1629 if (out_serial != NULL)
1630 *out_serial = serial_to_use;
1632 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1633 g_dbus_message_set_serial (message, serial_to_use);
1635 g_dbus_message_lock (message);
1636 _g_dbus_worker_send_message (connection->worker,
1640 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1651 * g_dbus_connection_send_message:
1652 * @connection: A #GDBusConnection.
1653 * @message: A #GDBusMessage
1654 * @flags: Flags affecting how the message is sent.
1655 * @out_serial: (out) (allow-none): Return location for serial number assigned
1656 * to @message when sending it or %NULL.
1657 * @error: Return location for error or %NULL.
1659 * Asynchronously sends @message to the peer represented by @connection.
1661 * Unless @flags contain the
1662 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1663 * will be assigned by @connection and set on @message via
1664 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1665 * serial number used will be written to this location prior to
1666 * submitting the message to the underlying transport.
1668 * If @connection is closed then the operation will fail with
1669 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1670 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1672 * See <xref linkend="gdbus-server"/> and <xref
1673 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1674 * low-level API to send and receive UNIX file descriptors.
1676 * Note that @message must be unlocked, unless @flags contain the
1677 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1679 * Returns: %TRUE if the message was well-formed and queued for
1680 * transmission, %FALSE if @error is set.
1685 g_dbus_connection_send_message (GDBusConnection *connection,
1686 GDBusMessage *message,
1687 GDBusSendMessageFlags flags,
1688 volatile guint32 *out_serial,
1693 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1694 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1695 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1696 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1698 CONNECTION_LOCK (connection);
1699 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1700 CONNECTION_UNLOCK (connection);
1704 /* ---------------------------------------------------------------------------------------------------- */
1708 volatile gint ref_count;
1709 GDBusConnection *connection;
1711 GSimpleAsyncResult *simple;
1713 GMainContext *main_context;
1715 GCancellable *cancellable;
1717 gulong cancellable_handler_id;
1719 GSource *timeout_source;
1724 /* Can be called from any thread with or without lock held */
1725 static SendMessageData *
1726 send_message_data_ref (SendMessageData *data)
1728 g_atomic_int_inc (&data->ref_count);
1732 /* Can be called from any thread with or without lock held */
1734 send_message_data_unref (SendMessageData *data)
1736 if (g_atomic_int_dec_and_test (&data->ref_count))
1738 g_assert (data->timeout_source == NULL);
1739 g_assert (data->simple == NULL);
1740 g_assert (data->cancellable_handler_id == 0);
1741 g_object_unref (data->connection);
1742 if (data->cancellable != NULL)
1743 g_object_unref (data->cancellable);
1744 g_main_context_unref (data->main_context);
1749 /* ---------------------------------------------------------------------------------------------------- */
1751 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1753 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1755 CONNECTION_ENSURE_LOCK (data->connection);
1757 g_assert (!data->delivered);
1759 data->delivered = TRUE;
1761 g_simple_async_result_complete_in_idle (data->simple);
1762 g_object_unref (data->simple);
1763 data->simple = NULL;
1765 if (data->timeout_source != NULL)
1767 g_source_destroy (data->timeout_source);
1768 data->timeout_source = NULL;
1770 if (data->cancellable_handler_id > 0)
1772 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1773 data->cancellable_handler_id = 0;
1778 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1779 GUINT_TO_POINTER (data->serial)));
1782 send_message_data_unref (data);
1785 /* ---------------------------------------------------------------------------------------------------- */
1787 /* Can be called from any thread with lock held */
1789 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1790 GDBusMessage *reply)
1792 if (data->delivered)
1795 g_simple_async_result_set_op_res_gpointer (data->simple,
1796 g_object_ref (reply),
1799 send_message_with_reply_deliver (data, TRUE);
1805 /* ---------------------------------------------------------------------------------------------------- */
1807 /* Called from a user thread, lock is not held */
1809 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1811 SendMessageData *data = user_data;
1813 CONNECTION_LOCK (data->connection);
1814 if (data->delivered)
1817 g_simple_async_result_set_error (data->simple,
1819 G_IO_ERROR_CANCELLED,
1820 _("Operation was cancelled"));
1822 send_message_with_reply_deliver (data, TRUE);
1825 CONNECTION_UNLOCK (data->connection);
1829 /* Can be called from any thread with or without lock held */
1831 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1834 SendMessageData *data = user_data;
1835 GSource *idle_source;
1837 /* postpone cancellation to idle handler since we may be called directly
1838 * via g_cancellable_connect() (e.g. holding lock)
1840 idle_source = g_idle_source_new ();
1841 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1842 g_source_set_callback (idle_source,
1843 send_message_with_reply_cancelled_idle_cb,
1844 send_message_data_ref (data),
1845 (GDestroyNotify) send_message_data_unref);
1846 g_source_attach (idle_source, data->main_context);
1847 g_source_unref (idle_source);
1850 /* ---------------------------------------------------------------------------------------------------- */
1852 /* Called from a user thread, lock is not held */
1854 send_message_with_reply_timeout_cb (gpointer user_data)
1856 SendMessageData *data = user_data;
1858 CONNECTION_LOCK (data->connection);
1859 if (data->delivered)
1862 g_simple_async_result_set_error (data->simple,
1864 G_IO_ERROR_TIMED_OUT,
1865 _("Timeout was reached"));
1867 send_message_with_reply_deliver (data, TRUE);
1870 CONNECTION_UNLOCK (data->connection);
1875 /* ---------------------------------------------------------------------------------------------------- */
1877 /* Called from a user thread, connection's lock is held */
1879 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1880 GDBusMessage *message,
1881 GDBusSendMessageFlags flags,
1883 volatile guint32 *out_serial,
1884 GCancellable *cancellable,
1885 GAsyncReadyCallback callback,
1888 GSimpleAsyncResult *simple;
1889 SendMessageData *data;
1891 volatile guint32 serial;
1895 if (out_serial == NULL)
1896 out_serial = &serial;
1898 if (timeout_msec == -1)
1899 timeout_msec = 25 * 1000;
1901 simple = g_simple_async_result_new (G_OBJECT (connection),
1904 g_dbus_connection_send_message_with_reply);
1906 if (g_cancellable_is_cancelled (cancellable))
1908 g_simple_async_result_set_error (simple,
1910 G_IO_ERROR_CANCELLED,
1911 _("Operation was cancelled"));
1912 g_simple_async_result_complete_in_idle (simple);
1913 g_object_unref (simple);
1917 if (connection->closed)
1919 g_simple_async_result_set_error (simple,
1922 _("The connection is closed"));
1923 g_simple_async_result_complete_in_idle (simple);
1924 g_object_unref (simple);
1929 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1931 g_simple_async_result_take_error (simple, error);
1932 g_simple_async_result_complete_in_idle (simple);
1933 g_object_unref (simple);
1937 data = g_new0 (SendMessageData, 1);
1938 data->ref_count = 1;
1939 data->connection = g_object_ref (connection);
1940 data->simple = simple;
1941 data->serial = *out_serial;
1942 data->main_context = g_main_context_ref_thread_default ();
1944 if (cancellable != NULL)
1946 data->cancellable = g_object_ref (cancellable);
1947 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1948 G_CALLBACK (send_message_with_reply_cancelled_cb),
1949 send_message_data_ref (data),
1950 (GDestroyNotify) send_message_data_unref);
1951 g_object_set_data_full (G_OBJECT (simple),
1953 g_object_ref (cancellable),
1954 (GDestroyNotify) g_object_unref);
1957 if (timeout_msec != G_MAXINT)
1959 data->timeout_source = g_timeout_source_new (timeout_msec);
1960 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1961 g_source_set_callback (data->timeout_source,
1962 send_message_with_reply_timeout_cb,
1963 send_message_data_ref (data),
1964 (GDestroyNotify) send_message_data_unref);
1965 g_source_attach (data->timeout_source, data->main_context);
1966 g_source_unref (data->timeout_source);
1969 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1970 GUINT_TO_POINTER (*out_serial),
1978 * g_dbus_connection_send_message_with_reply:
1979 * @connection: A #GDBusConnection.
1980 * @message: A #GDBusMessage.
1981 * @flags: Flags affecting how the message is sent.
1982 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1983 * timeout or %G_MAXINT for no timeout.
1984 * @out_serial: (out) (allow-none): Return location for serial number assigned
1985 * to @message when sending it or %NULL.
1986 * @cancellable: A #GCancellable or %NULL.
1987 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1988 * satisfied or %NULL if you don't care about the result.
1989 * @user_data: The data to pass to @callback.
1991 * Asynchronously sends @message to the peer represented by @connection.
1993 * Unless @flags contain the
1994 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1995 * will be assigned by @connection and set on @message via
1996 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1997 * serial number used will be written to this location prior to
1998 * submitting the message to the underlying transport.
2000 * If @connection is closed then the operation will fail with
2001 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2002 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2003 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2005 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2006 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2007 * of the thread you are calling this method from. You can then call
2008 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2009 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2011 * Note that @message must be unlocked, unless @flags contain the
2012 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2014 * See <xref linkend="gdbus-server"/> and <xref
2015 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2016 * low-level API to send and receive UNIX file descriptors.
2021 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2022 GDBusMessage *message,
2023 GDBusSendMessageFlags flags,
2025 volatile guint32 *out_serial,
2026 GCancellable *cancellable,
2027 GAsyncReadyCallback callback,
2030 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2031 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2032 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2033 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2035 CONNECTION_LOCK (connection);
2036 g_dbus_connection_send_message_with_reply_unlocked (connection,
2044 CONNECTION_UNLOCK (connection);
2048 * g_dbus_connection_send_message_with_reply_finish:
2049 * @connection: a #GDBusConnection
2050 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2051 * @error: Return location for error or %NULL.
2053 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2055 * Note that @error is only set if a local in-process error
2056 * occurred. That is to say that the returned #GDBusMessage object may
2057 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2058 * g_dbus_message_to_gerror() to transcode this to a #GError.
2060 * See <xref linkend="gdbus-server"/> and <xref
2061 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2062 * low-level API to send and receive UNIX file descriptors.
2064 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2069 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2073 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2074 GDBusMessage *reply;
2075 GCancellable *cancellable;
2077 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2078 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2082 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2084 if (g_simple_async_result_propagate_error (simple, error))
2087 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2088 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2089 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2091 g_object_unref (reply);
2093 g_set_error_literal (error,
2095 G_IO_ERROR_CANCELLED,
2096 _("Operation was cancelled"));
2102 /* ---------------------------------------------------------------------------------------------------- */
2107 GMainContext *context;
2109 } SendMessageSyncData;
2111 /* Called from a user thread, lock is not held */
2113 send_message_with_reply_sync_cb (GDBusConnection *connection,
2117 SendMessageSyncData *data = user_data;
2118 data->res = g_object_ref (res);
2119 g_main_loop_quit (data->loop);
2123 * g_dbus_connection_send_message_with_reply_sync:
2124 * @connection: A #GDBusConnection.
2125 * @message: A #GDBusMessage.
2126 * @flags: Flags affecting how the message is sent.
2127 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2128 * timeout or %G_MAXINT for no timeout.
2129 * @out_serial: (out) (allow-none): Return location for serial number assigned
2130 * to @message when sending it or %NULL.
2131 * @cancellable: A #GCancellable or %NULL.
2132 * @error: Return location for error or %NULL.
2134 * Synchronously sends @message to the peer represented by @connection
2135 * and blocks the calling thread until a reply is received or the
2136 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2137 * for the asynchronous version of this method.
2139 * Unless @flags contain the
2140 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2141 * will be assigned by @connection and set on @message via
2142 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2143 * serial number used will be written to this location prior to
2144 * submitting the message to the underlying transport.
2146 * If @connection is closed then the operation will fail with
2147 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2148 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2149 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2151 * Note that @error is only set if a local in-process error
2152 * occurred. That is to say that the returned #GDBusMessage object may
2153 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2154 * g_dbus_message_to_gerror() to transcode this to a #GError.
2156 * See <xref linkend="gdbus-server"/> and <xref
2157 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2158 * low-level API to send and receive UNIX file descriptors.
2160 * Note that @message must be unlocked, unless @flags contain the
2161 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2163 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2168 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2169 GDBusMessage *message,
2170 GDBusSendMessageFlags flags,
2172 volatile guint32 *out_serial,
2173 GCancellable *cancellable,
2176 SendMessageSyncData *data;
2177 GDBusMessage *reply;
2179 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2180 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2181 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2182 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2183 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2185 data = g_new0 (SendMessageSyncData, 1);
2186 data->context = g_main_context_new ();
2187 data->loop = g_main_loop_new (data->context, FALSE);
2189 g_main_context_push_thread_default (data->context);
2191 g_dbus_connection_send_message_with_reply (connection,
2197 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2199 g_main_loop_run (data->loop);
2200 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2204 g_main_context_pop_thread_default (data->context);
2206 g_main_context_unref (data->context);
2207 g_main_loop_unref (data->loop);
2208 g_object_unref (data->res);
2214 /* ---------------------------------------------------------------------------------------------------- */
2218 GDBusMessageFilterFunction func;
2225 GDBusMessageFilterFunction filter_function;
2227 GDestroyNotify user_data_free_func;
2230 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2232 on_worker_message_received (GDBusWorker *worker,
2233 GDBusMessage *message,
2236 GDBusConnection *connection;
2237 FilterCallback *filters;
2242 G_LOCK (message_bus_lock);
2243 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
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 num_filters = connection->filters->len;
2263 filters = g_new0 (FilterCallback, num_filters);
2264 for (n = 0; n < num_filters; n++)
2266 FilterData *data = connection->filters->pdata[n];
2267 filters[n].func = data->filter_function;
2268 filters[n].user_data = data->user_data;
2270 CONNECTION_UNLOCK (connection);
2272 /* then call the filters in order (without holding the lock) */
2273 for (n = 0; n < num_filters; n++)
2275 message = filters[n].func (connection,
2278 filters[n].user_data);
2279 if (message == NULL)
2281 g_dbus_message_lock (message);
2284 /* Standard dispatch unless the filter ate the message - no need to
2285 * do anything if the message was altered
2287 if (message != NULL)
2289 GDBusMessageType message_type;
2291 message_type = g_dbus_message_get_message_type (message);
2292 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2294 guint32 reply_serial;
2295 SendMessageData *send_message_data;
2297 reply_serial = g_dbus_message_get_reply_serial (message);
2298 CONNECTION_LOCK (connection);
2299 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2300 GUINT_TO_POINTER (reply_serial));
2301 if (send_message_data != NULL)
2303 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2304 send_message_data_deliver_reply_unlocked (send_message_data, message);
2308 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2310 CONNECTION_UNLOCK (connection);
2312 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2314 CONNECTION_LOCK (connection);
2315 distribute_signals (connection, message);
2316 CONNECTION_UNLOCK (connection);
2318 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2320 CONNECTION_LOCK (connection);
2321 distribute_method_call (connection, message);
2322 CONNECTION_UNLOCK (connection);
2326 if (message != NULL)
2327 g_object_unref (message);
2328 g_object_unref (connection);
2332 /* Called in GDBusWorker's thread, lock is not held */
2333 static GDBusMessage *
2334 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2335 GDBusMessage *message,
2338 GDBusConnection *connection;
2339 FilterCallback *filters;
2344 G_LOCK (message_bus_lock);
2345 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2348 G_UNLOCK (message_bus_lock);
2351 connection = G_DBUS_CONNECTION (user_data);
2352 g_object_ref (connection);
2353 G_UNLOCK (message_bus_lock);
2355 //g_debug ("in on_worker_message_about_to_be_sent");
2357 /* First collect the set of callback functions */
2358 CONNECTION_LOCK (connection);
2359 num_filters = connection->filters->len;
2360 filters = g_new0 (FilterCallback, num_filters);
2361 for (n = 0; n < num_filters; n++)
2363 FilterData *data = connection->filters->pdata[n];
2364 filters[n].func = data->filter_function;
2365 filters[n].user_data = data->user_data;
2367 CONNECTION_UNLOCK (connection);
2369 /* then call the filters in order (without holding the lock) */
2370 for (n = 0; n < num_filters; n++)
2372 g_dbus_message_lock (message);
2373 message = filters[n].func (connection,
2376 filters[n].user_data);
2377 if (message == NULL)
2381 g_object_unref (connection);
2387 /* called with connection lock held, in GDBusWorker thread */
2389 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2391 SendMessageData *data = value;
2393 if (data->delivered)
2396 g_simple_async_result_set_error (data->simple,
2399 _("The connection is closed"));
2401 /* Ask send_message_with_reply_deliver not to remove the element from the
2402 * hash table - we're in the middle of a foreach; that would be unsafe.
2403 * Instead, return TRUE from this function so that it gets removed safely.
2405 send_message_with_reply_deliver (data, FALSE);
2409 /* Called in GDBusWorker's thread - we must not block - without lock held */
2411 on_worker_closed (GDBusWorker *worker,
2412 gboolean remote_peer_vanished,
2416 GDBusConnection *connection;
2419 G_LOCK (message_bus_lock);
2420 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2423 G_UNLOCK (message_bus_lock);
2426 connection = G_DBUS_CONNECTION (user_data);
2427 g_object_ref (connection);
2428 G_UNLOCK (message_bus_lock);
2430 //g_debug ("in on_worker_closed: %s", error->message);
2432 CONNECTION_LOCK (connection);
2433 if (!connection->closed)
2435 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2436 set_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 (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 get_offered_capabilities_max (connection),
2558 &connection->capabilities,
2560 &connection->initialization_error);
2561 if (connection->guid == NULL)
2565 if (connection->authentication_observer != NULL)
2567 g_object_unref (connection->authentication_observer);
2568 connection->authentication_observer = NULL;
2571 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2573 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2576 /* We want all IO operations to be non-blocking since they happen in
2577 * the worker thread which is shared by _all_ connections.
2579 if (G_IS_SOCKET_CONNECTION (connection->stream))
2581 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2585 G_LOCK (message_bus_lock);
2586 if (alive_connections == NULL)
2587 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2588 g_hash_table_insert (alive_connections, connection, connection);
2589 G_UNLOCK (message_bus_lock);
2591 connection->worker = _g_dbus_worker_new (connection->stream,
2592 connection->capabilities,
2593 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2594 on_worker_message_received,
2595 on_worker_message_about_to_be_sent,
2599 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2600 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2602 GVariant *hello_result;
2604 /* we could lift this restriction by adding code in gdbusprivate.c */
2605 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2607 g_set_error_literal (&connection->initialization_error,
2610 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2614 hello_result = g_dbus_connection_call_sync (connection,
2615 "org.freedesktop.DBus", /* name */
2616 "/org/freedesktop/DBus", /* path */
2617 "org.freedesktop.DBus", /* interface */
2619 NULL, /* parameters */
2620 G_VARIANT_TYPE ("(s)"),
2621 CALL_FLAGS_INITIALIZING,
2623 NULL, /* TODO: cancellable */
2624 &connection->initialization_error);
2625 if (hello_result == NULL)
2628 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2629 g_variant_unref (hello_result);
2630 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2637 g_assert (connection->initialization_error != NULL);
2638 g_propagate_error (error, g_error_copy (connection->initialization_error));
2641 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2642 g_mutex_unlock (&connection->init_lock);
2648 initable_iface_init (GInitableIface *initable_iface)
2650 initable_iface->init = initable_init;
2653 /* ---------------------------------------------------------------------------------------------------- */
2656 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2661 /* ---------------------------------------------------------------------------------------------------- */
2664 * g_dbus_connection_new:
2665 * @stream: A #GIOStream.
2666 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2667 * @flags: Flags describing how to make the connection.
2668 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2669 * @cancellable: A #GCancellable or %NULL.
2670 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2671 * @user_data: The data to pass to @callback.
2673 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2674 * with the end represented by @stream.
2676 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2677 * will be put into non-blocking mode.
2679 * The D-Bus connection will interact with @stream from a worker thread.
2680 * As a result, the caller should not interact with @stream after this
2681 * method has been called, except by calling g_object_unref() on it.
2683 * If @observer is not %NULL it may be used to control the
2684 * authentication process.
2686 * When the operation is finished, @callback will be invoked. You can
2687 * then call g_dbus_connection_new_finish() to get the result of the
2690 * This is a asynchronous failable constructor. See
2691 * g_dbus_connection_new_sync() for the synchronous
2697 g_dbus_connection_new (GIOStream *stream,
2699 GDBusConnectionFlags flags,
2700 GDBusAuthObserver *observer,
2701 GCancellable *cancellable,
2702 GAsyncReadyCallback callback,
2705 g_return_if_fail (G_IS_IO_STREAM (stream));
2706 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2714 "authentication-observer", observer,
2719 * g_dbus_connection_new_finish:
2720 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2721 * @error: Return location for error or %NULL.
2723 * Finishes an operation started with g_dbus_connection_new().
2725 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2730 g_dbus_connection_new_finish (GAsyncResult *res,
2734 GObject *source_object;
2736 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2737 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2739 source_object = g_async_result_get_source_object (res);
2740 g_assert (source_object != NULL);
2741 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2744 g_object_unref (source_object);
2746 return G_DBUS_CONNECTION (object);
2752 * g_dbus_connection_new_sync:
2753 * @stream: A #GIOStream.
2754 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2755 * @flags: Flags describing how to make the connection.
2756 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2757 * @cancellable: A #GCancellable or %NULL.
2758 * @error: Return location for error or %NULL.
2760 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2761 * with the end represented by @stream.
2763 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2764 * will be put into non-blocking mode.
2766 * The D-Bus connection will interact with @stream from a worker thread.
2767 * As a result, the caller should not interact with @stream after this
2768 * method has been called, except by calling g_object_unref() on it.
2770 * If @observer is not %NULL it may be used to control the
2771 * authentication process.
2773 * This is a synchronous failable constructor. See
2774 * g_dbus_connection_new() for the asynchronous version.
2776 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2781 g_dbus_connection_new_sync (GIOStream *stream,
2783 GDBusConnectionFlags flags,
2784 GDBusAuthObserver *observer,
2785 GCancellable *cancellable,
2788 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2789 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2790 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2796 "authentication-observer", observer,
2800 /* ---------------------------------------------------------------------------------------------------- */
2803 * g_dbus_connection_new_for_address:
2804 * @address: A D-Bus address.
2805 * @flags: Flags describing how to make the connection.
2806 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2807 * @cancellable: A #GCancellable or %NULL.
2808 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2809 * @user_data: The data to pass to @callback.
2811 * Asynchronously connects and sets up a D-Bus client connection for
2812 * exchanging D-Bus messages with an endpoint specified by @address
2813 * which must be in the D-Bus address format.
2815 * This constructor can only be used to initiate client-side
2816 * connections - use g_dbus_connection_new() if you need to act as the
2817 * server. In particular, @flags cannot contain the
2818 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2819 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2821 * When the operation is finished, @callback will be invoked. You can
2822 * then call g_dbus_connection_new_finish() to get the result of the
2825 * If @observer is not %NULL it may be used to control the
2826 * authentication process.
2828 * This is a asynchronous failable constructor. See
2829 * g_dbus_connection_new_for_address_sync() for the synchronous
2835 g_dbus_connection_new_for_address (const gchar *address,
2836 GDBusConnectionFlags flags,
2837 GDBusAuthObserver *observer,
2838 GCancellable *cancellable,
2839 GAsyncReadyCallback callback,
2842 g_return_if_fail (address != NULL);
2843 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2850 "authentication-observer", observer,
2855 * g_dbus_connection_new_for_address_finish:
2856 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2857 * @error: Return location for error or %NULL.
2859 * Finishes an operation started with g_dbus_connection_new_for_address().
2861 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2866 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2870 GObject *source_object;
2872 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2873 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2875 source_object = g_async_result_get_source_object (res);
2876 g_assert (source_object != NULL);
2877 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2880 g_object_unref (source_object);
2882 return G_DBUS_CONNECTION (object);
2888 * g_dbus_connection_new_for_address_sync:
2889 * @address: A D-Bus address.
2890 * @flags: Flags describing how to make the connection.
2891 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2892 * @cancellable: A #GCancellable or %NULL.
2893 * @error: Return location for error or %NULL.
2895 * Synchronously connects and sets up a D-Bus client connection for
2896 * exchanging D-Bus messages with an endpoint specified by @address
2897 * which must be in the D-Bus address format.
2899 * This constructor can only be used to initiate client-side
2900 * connections - use g_dbus_connection_new_sync() if you need to act
2901 * as the server. In particular, @flags cannot contain the
2902 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2903 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2905 * This is a synchronous failable constructor. See
2906 * g_dbus_connection_new_for_address() for the asynchronous version.
2908 * If @observer is not %NULL it may be used to control the
2909 * authentication process.
2911 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2916 g_dbus_connection_new_for_address_sync (const gchar *address,
2917 GDBusConnectionFlags flags,
2918 GDBusAuthObserver *observer,
2919 GCancellable *cancellable,
2922 g_return_val_if_fail (address != NULL, NULL);
2923 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2924 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2929 "authentication-observer", observer,
2933 /* ---------------------------------------------------------------------------------------------------- */
2936 * g_dbus_connection_set_exit_on_close:
2937 * @connection: A #GDBusConnection.
2938 * @exit_on_close: Whether the process should be terminated
2939 * when @connection is closed by the remote peer.
2941 * Sets whether the process should be terminated when @connection is
2942 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2945 * Note that this function should be used with care. Most modern UNIX
2946 * desktops tie the notion of a user session the session bus, and expect
2947 * all of a users applications to quit when their bus connection goes away.
2948 * If you are setting @exit_on_close to %FALSE for the shared session
2949 * bus connection, you should make sure that your application exits
2950 * when the user session ends.
2955 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2956 gboolean exit_on_close)
2958 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2961 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2963 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2968 * g_dbus_connection_get_exit_on_close:
2969 * @connection: A #GDBusConnection.
2971 * Gets whether the process is terminated when @connection is
2972 * closed by the remote peer. See
2973 * #GDBusConnection:exit-on-close for more details.
2975 * Returns: Whether the process is terminated when @connection is
2976 * closed by the remote peer.
2981 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2983 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2985 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
2992 * g_dbus_connection_get_guid:
2993 * @connection: A #GDBusConnection.
2995 * The GUID of the peer performing the role of server when
2996 * authenticating. See #GDBusConnection:guid for more details.
2998 * Returns: The GUID. Do not free this string, it is owned by
3004 g_dbus_connection_get_guid (GDBusConnection *connection)
3006 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3007 return connection->guid;
3011 * g_dbus_connection_get_unique_name:
3012 * @connection: A #GDBusConnection.
3014 * Gets the unique name of @connection as assigned by the message
3015 * bus. This can also be used to figure out if @connection is a
3016 * message bus connection.
3018 * Returns: The unique name or %NULL if @connection is not a message
3019 * bus connection. Do not free this string, it is owned by
3025 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3027 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3029 /* do not use g_return_val_if_fail(), we want the memory barrier */
3030 if (!check_initialized (connection))
3033 return connection->bus_unique_name;
3037 * g_dbus_connection_get_peer_credentials:
3038 * @connection: A #GDBusConnection.
3040 * Gets the credentials of the authenticated peer. This will always
3041 * return %NULL unless @connection acted as a server
3042 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3043 * when set up and the client passed credentials as part of the
3044 * authentication process.
3046 * In a message bus setup, the message bus is always the server and
3047 * each application is a client. So this method will always return
3048 * %NULL for message bus clients.
3050 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3051 * this object, it is owned by @connection.
3056 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3058 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3060 /* do not use g_return_val_if_fail(), we want the memory barrier */
3061 if (!check_initialized (connection))
3064 return connection->credentials;
3067 /* ---------------------------------------------------------------------------------------------------- */
3069 static guint _global_filter_id = 1;
3072 * g_dbus_connection_add_filter:
3073 * @connection: A #GDBusConnection.
3074 * @filter_function: A filter function.
3075 * @user_data: User data to pass to @filter_function.
3076 * @user_data_free_func: Function to free @user_data with when filter
3077 * is removed or %NULL.
3079 * Adds a message filter. Filters are handlers that are run on all
3080 * incoming and outgoing messages, prior to standard dispatch. Filters
3081 * are run in the order that they were added. The same handler can be
3082 * added as a filter more than once, in which case it will be run more
3083 * than once. Filters added during a filter callback won't be run on
3084 * the message being processed. Filter functions are allowed to modify
3085 * and even drop messages.
3087 * Note that filters are run in a dedicated message handling thread so
3088 * they can't block and, generally, can't do anything but signal a
3089 * worker thread. Also note that filters are rarely needed - use API
3090 * such as g_dbus_connection_send_message_with_reply(),
3091 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3093 * If a filter consumes an incoming message the message is not
3094 * dispatched anywhere else - not even the standard dispatch machinery
3095 * (that API such as g_dbus_connection_signal_subscribe() and
3096 * g_dbus_connection_send_message_with_reply() relies on) will see the
3097 * message. Similary, if a filter consumes an outgoing message, the
3098 * message will not be sent to the other peer.
3100 * Returns: A filter identifier that can be used with
3101 * g_dbus_connection_remove_filter().
3106 g_dbus_connection_add_filter (GDBusConnection *connection,
3107 GDBusMessageFilterFunction filter_function,
3109 GDestroyNotify user_data_free_func)
3113 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3114 g_return_val_if_fail (filter_function != NULL, 0);
3115 g_return_val_if_fail (check_initialized (connection), 0);
3117 CONNECTION_LOCK (connection);
3118 data = g_new0 (FilterData, 1);
3119 data->id = _global_filter_id++; /* TODO: overflow etc. */
3120 data->filter_function = filter_function;
3121 data->user_data = user_data;
3122 data->user_data_free_func = user_data_free_func;
3123 g_ptr_array_add (connection->filters, data);
3124 CONNECTION_UNLOCK (connection);
3129 /* only called from finalize(), removes all filters */
3131 purge_all_filters (GDBusConnection *connection)
3134 for (n = 0; n < connection->filters->len; n++)
3136 FilterData *data = connection->filters->pdata[n];
3137 if (data->user_data_free_func != NULL)
3138 data->user_data_free_func (data->user_data);
3144 * g_dbus_connection_remove_filter:
3145 * @connection: a #GDBusConnection
3146 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3153 g_dbus_connection_remove_filter (GDBusConnection *connection,
3157 FilterData *to_destroy;
3159 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3160 g_return_if_fail (check_initialized (connection));
3162 CONNECTION_LOCK (connection);
3164 for (n = 0; n < connection->filters->len; n++)
3166 FilterData *data = connection->filters->pdata[n];
3167 if (data->id == filter_id)
3169 g_ptr_array_remove_index (connection->filters, n);
3174 CONNECTION_UNLOCK (connection);
3176 /* do free without holding lock */
3177 if (to_destroy != NULL)
3179 if (to_destroy->user_data_free_func != NULL)
3180 to_destroy->user_data_free_func (to_destroy->user_data);
3181 g_free (to_destroy);
3185 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3189 /* ---------------------------------------------------------------------------------------------------- */
3195 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3196 gchar *interface_name;
3200 GArray *subscribers;
3205 GDBusSignalCallback callback;
3207 GDestroyNotify user_data_free_func;
3209 GMainContext *context;
3213 signal_data_free (SignalData *signal_data)
3215 g_free (signal_data->rule);
3216 g_free (signal_data->sender);
3217 g_free (signal_data->sender_unique_name);
3218 g_free (signal_data->interface_name);
3219 g_free (signal_data->member);
3220 g_free (signal_data->object_path);
3221 g_free (signal_data->arg0);
3222 g_array_free (signal_data->subscribers, TRUE);
3223 g_free (signal_data);
3227 args_to_rule (const gchar *sender,
3228 const gchar *interface_name,
3229 const gchar *member,
3230 const gchar *object_path,
3236 rule = g_string_new ("type='signal'");
3238 g_string_prepend_c (rule, '-');
3240 g_string_append_printf (rule, ",sender='%s'", sender);
3241 if (interface_name != NULL)
3242 g_string_append_printf (rule, ",interface='%s'", interface_name);
3244 g_string_append_printf (rule, ",member='%s'", member);
3245 if (object_path != NULL)
3246 g_string_append_printf (rule, ",path='%s'", object_path);
3248 g_string_append_printf (rule, ",arg0='%s'", arg0);
3250 return g_string_free (rule, FALSE);
3253 static guint _global_subscriber_id = 1;
3254 static guint _global_registration_id = 1;
3255 static guint _global_subtree_registration_id = 1;
3257 /* ---------------------------------------------------------------------------------------------------- */
3259 /* Called in a user thread, lock is held */
3261 add_match_rule (GDBusConnection *connection,
3262 const gchar *match_rule)
3265 GDBusMessage *message;
3267 if (match_rule[0] == '-')
3270 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3271 "/org/freedesktop/DBus", /* path */
3272 "org.freedesktop.DBus", /* interface */
3274 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3276 if (!g_dbus_connection_send_message_unlocked (connection,
3278 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3282 g_critical ("Error while sending AddMatch() message: %s", error->message);
3283 g_error_free (error);
3285 g_object_unref (message);
3288 /* ---------------------------------------------------------------------------------------------------- */
3290 /* Called in a user thread, lock is held */
3292 remove_match_rule (GDBusConnection *connection,
3293 const gchar *match_rule)
3296 GDBusMessage *message;
3298 if (match_rule[0] == '-')
3301 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3302 "/org/freedesktop/DBus", /* path */
3303 "org.freedesktop.DBus", /* interface */
3305 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3308 if (!g_dbus_connection_send_message_unlocked (connection,
3310 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3314 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3315 g_error_free (error);
3317 g_object_unref (message);
3320 /* ---------------------------------------------------------------------------------------------------- */
3323 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3325 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3326 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3327 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3328 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3329 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3332 /* ---------------------------------------------------------------------------------------------------- */
3335 * g_dbus_connection_signal_subscribe:
3336 * @connection: A #GDBusConnection.
3337 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3338 * or %NULL to listen from all senders.
3339 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3340 * match on all interfaces.
3341 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3342 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3343 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3344 * to match on all kinds of arguments.
3345 * @flags: Flags describing how to subscribe to the signal (currently unused).
3346 * @callback: Callback to invoke when there is a signal matching the requested data.
3347 * @user_data: User data to pass to @callback.
3348 * @user_data_free_func: (allow-none): Function to free @user_data with when
3349 * subscription is removed or %NULL.
3351 * Subscribes to signals on @connection and invokes @callback with a
3352 * whenever the signal is received. Note that @callback
3353 * will be invoked in the <link
3354 * linkend="g-main-context-push-thread-default">thread-default main
3355 * loop</link> of the thread you are calling this method from.
3357 * If @connection is not a message bus connection, @sender must be
3360 * If @sender is a well-known name note that @callback is invoked with
3361 * the unique name for the owner of @sender, not the well-known name
3362 * as one would expect. This is because the message bus rewrites the
3363 * name. As such, to avoid certain race conditions, users should be
3364 * tracking the name owner of the well-known name and use that when
3365 * processing the received signal.
3367 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3372 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3373 const gchar *sender,
3374 const gchar *interface_name,
3375 const gchar *member,
3376 const gchar *object_path,
3378 GDBusSignalFlags flags,
3379 GDBusSignalCallback callback,
3381 GDestroyNotify user_data_free_func)
3384 SignalData *signal_data;
3385 SignalSubscriber subscriber;
3386 GPtrArray *signal_data_array;
3387 const gchar *sender_unique_name;
3389 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3390 * an OOM condition. We might want to change that but that would involve making
3391 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3392 * handle that. And there's really no sensible way of handling this short of retrying
3393 * to add the match rule... and then there's the little thing that, hey, maybe there's
3394 * a reason the bus in an OOM condition.
3396 * Doable, but not really sure it's worth it...
3399 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3400 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3401 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3402 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3403 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3404 g_return_val_if_fail (callback != NULL, 0);
3405 g_return_val_if_fail (check_initialized (connection), 0);
3407 CONNECTION_LOCK (connection);
3409 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3410 * with a '-' character to prefix the rule (which will otherwise be
3413 * This allows us to hash the rule and do our lifecycle tracking in
3414 * the usual way, but the '-' prevents the match rule from ever
3415 * actually being send to the bus (either for add or remove).
3417 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3418 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3420 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3421 sender_unique_name = sender;
3423 sender_unique_name = "";
3425 subscriber.callback = callback;
3426 subscriber.user_data = user_data;
3427 subscriber.user_data_free_func = user_data_free_func;
3428 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3429 subscriber.context = g_main_context_ref_thread_default ();
3431 /* see if we've already have this rule */
3432 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3433 if (signal_data != NULL)
3435 g_array_append_val (signal_data->subscribers, subscriber);
3440 signal_data = g_new0 (SignalData, 1);
3441 signal_data->rule = rule;
3442 signal_data->sender = g_strdup (sender);
3443 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3444 signal_data->interface_name = g_strdup (interface_name);
3445 signal_data->member = g_strdup (member);
3446 signal_data->object_path = g_strdup (object_path);
3447 signal_data->arg0 = g_strdup (arg0);
3448 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3449 g_array_append_val (signal_data->subscribers, subscriber);
3451 g_hash_table_insert (connection->map_rule_to_signal_data,
3455 /* Add the match rule to the bus...
3457 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3458 * always send such messages to us.
3460 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3462 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3463 add_match_rule (connection, signal_data->rule);
3466 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3467 signal_data->sender_unique_name);
3468 if (signal_data_array == NULL)
3470 signal_data_array = g_ptr_array_new ();
3471 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3472 g_strdup (signal_data->sender_unique_name),
3475 g_ptr_array_add (signal_data_array, signal_data);
3478 g_hash_table_insert (connection->map_id_to_signal_data,
3479 GUINT_TO_POINTER (subscriber.id),
3482 CONNECTION_UNLOCK (connection);
3484 return subscriber.id;
3487 /* ---------------------------------------------------------------------------------------------------- */
3489 /* called in any thread */
3490 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3492 unsubscribe_id_internal (GDBusConnection *connection,
3493 guint subscription_id,
3494 GArray *out_removed_subscribers)
3496 SignalData *signal_data;
3497 GPtrArray *signal_data_array;
3500 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3501 GUINT_TO_POINTER (subscription_id));
3502 if (signal_data == NULL)
3504 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3508 for (n = 0; n < signal_data->subscribers->len; n++)
3510 SignalSubscriber *subscriber;
3512 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3513 if (subscriber->id != subscription_id)
3516 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3517 GUINT_TO_POINTER (subscription_id)));
3518 g_array_append_val (out_removed_subscribers, *subscriber);
3519 g_array_remove_index (signal_data->subscribers, n);
3521 if (signal_data->subscribers->len == 0)
3523 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3525 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3526 signal_data->sender_unique_name);
3527 g_warn_if_fail (signal_data_array != NULL);
3528 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3530 if (signal_data_array->len == 0)
3532 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3533 signal_data->sender_unique_name));
3536 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3537 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3539 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3540 if (!connection->closed && !connection->finalizing)
3541 remove_match_rule (connection, signal_data->rule);
3543 signal_data_free (signal_data);
3549 g_assert_not_reached ();
3556 * g_dbus_connection_signal_unsubscribe:
3557 * @connection: A #GDBusConnection.
3558 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3560 * Unsubscribes from signals.
3565 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3566 guint subscription_id)
3568 GArray *subscribers;
3571 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3572 g_return_if_fail (check_initialized (connection));
3574 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3576 CONNECTION_LOCK (connection);
3577 unsubscribe_id_internal (connection,
3580 CONNECTION_UNLOCK (connection);
3583 g_assert (subscribers->len == 0 || subscribers->len == 1);
3585 /* call GDestroyNotify without lock held */
3586 for (n = 0; n < subscribers->len; n++)
3588 SignalSubscriber *subscriber;
3589 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3590 call_destroy_notify (subscriber->context,
3591 subscriber->user_data_free_func,
3592 subscriber->user_data);
3593 g_main_context_unref (subscriber->context);
3596 g_array_free (subscribers, TRUE);
3599 /* ---------------------------------------------------------------------------------------------------- */
3603 guint subscription_id;
3604 GDBusSignalCallback callback;
3606 GDBusMessage *message;
3607 GDBusConnection *connection;
3608 const gchar *sender;
3610 const gchar *interface;
3611 const gchar *member;
3614 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3618 emit_signal_instance_in_idle_cb (gpointer data)
3620 SignalInstance *signal_instance = data;
3621 GVariant *parameters;
3622 gboolean has_subscription;
3624 parameters = g_dbus_message_get_body (signal_instance->message);
3625 if (parameters == NULL)
3627 parameters = g_variant_new ("()");
3628 g_variant_ref_sink (parameters);
3632 g_variant_ref_sink (parameters);
3636 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3637 signal_instance->subscription_id,
3638 signal_instance->sender,
3639 signal_instance->path,
3640 signal_instance->interface,
3641 signal_instance->member,
3642 g_variant_print (parameters, TRUE));
3645 /* Careful here, don't do the callback if we no longer has the subscription */
3646 CONNECTION_LOCK (signal_instance->connection);
3647 has_subscription = FALSE;
3648 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3649 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3650 has_subscription = TRUE;
3651 CONNECTION_UNLOCK (signal_instance->connection);
3653 if (has_subscription)
3654 signal_instance->callback (signal_instance->connection,
3655 signal_instance->sender,
3656 signal_instance->path,
3657 signal_instance->interface,
3658 signal_instance->member,
3660 signal_instance->user_data);
3662 g_variant_unref (parameters);
3668 signal_instance_free (SignalInstance *signal_instance)
3670 g_object_unref (signal_instance->message);
3671 g_object_unref (signal_instance->connection);
3672 g_free (signal_instance);
3675 /* called in GDBusWorker thread WITH lock held */
3677 schedule_callbacks (GDBusConnection *connection,
3678 GPtrArray *signal_data_array,
3679 GDBusMessage *message,
3680 const gchar *sender)
3683 const gchar *interface;
3684 const gchar *member;
3693 interface = g_dbus_message_get_interface (message);
3694 member = g_dbus_message_get_member (message);
3695 path = g_dbus_message_get_path (message);
3696 arg0 = g_dbus_message_get_arg0 (message);
3699 g_print ("In schedule_callbacks:\n"
3701 " interface = `%s'\n"
3712 /* TODO: if this is slow, then we can change signal_data_array into
3713 * map_object_path_to_signal_data_array or something.
3715 for (n = 0; n < signal_data_array->len; n++)
3717 SignalData *signal_data = signal_data_array->pdata[n];
3719 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3722 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3725 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3728 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3731 for (m = 0; m < signal_data->subscribers->len; m++)
3733 SignalSubscriber *subscriber;
3734 GSource *idle_source;
3735 SignalInstance *signal_instance;
3737 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3739 signal_instance = g_new0 (SignalInstance, 1);
3740 signal_instance->subscription_id = subscriber->id;
3741 signal_instance->callback = subscriber->callback;
3742 signal_instance->user_data = subscriber->user_data;
3743 signal_instance->message = g_object_ref (message);
3744 signal_instance->connection = g_object_ref (connection);
3745 signal_instance->sender = sender;
3746 signal_instance->path = path;
3747 signal_instance->interface = interface;
3748 signal_instance->member = member;
3750 idle_source = g_idle_source_new ();
3751 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3752 g_source_set_callback (idle_source,
3753 emit_signal_instance_in_idle_cb,
3755 (GDestroyNotify) signal_instance_free);
3756 g_source_attach (idle_source, subscriber->context);
3757 g_source_unref (idle_source);
3762 /* called in GDBusWorker thread with lock held */
3764 distribute_signals (GDBusConnection *connection,
3765 GDBusMessage *message)
3767 GPtrArray *signal_data_array;
3768 const gchar *sender;
3770 sender = g_dbus_message_get_sender (message);
3772 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3774 _g_dbus_debug_print_lock ();
3775 g_print ("========================================================================\n"
3776 "GDBus-debug:Signal:\n"
3777 " <<<< RECEIVED SIGNAL %s.%s\n"
3779 " sent by name %s\n",
3780 g_dbus_message_get_interface (message),
3781 g_dbus_message_get_member (message),
3782 g_dbus_message_get_path (message),
3783 sender != NULL ? sender : "(none)");
3784 _g_dbus_debug_print_unlock ();
3787 /* collect subscribers that match on sender */
3790 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3791 if (signal_data_array != NULL)
3792 schedule_callbacks (connection, signal_data_array, message, sender);
3795 /* collect subscribers not matching on sender */
3796 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3797 if (signal_data_array != NULL)
3798 schedule_callbacks (connection, signal_data_array, message, sender);
3801 /* ---------------------------------------------------------------------------------------------------- */
3803 /* only called from finalize(), removes all subscriptions */
3805 purge_all_signal_subscriptions (GDBusConnection *connection)
3807 GHashTableIter iter;
3810 GArray *subscribers;
3813 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3814 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3815 while (g_hash_table_iter_next (&iter, &key, NULL))
3817 guint subscription_id = GPOINTER_TO_UINT (key);
3818 g_array_append_val (ids, subscription_id);
3821 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3822 for (n = 0; n < ids->len; n++)
3824 guint subscription_id = g_array_index (ids, guint, n);
3825 unsubscribe_id_internal (connection,
3829 g_array_free (ids, TRUE);
3831 /* call GDestroyNotify without lock held */
3832 for (n = 0; n < subscribers->len; n++)
3834 SignalSubscriber *subscriber;
3835 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3836 call_destroy_notify (subscriber->context,
3837 subscriber->user_data_free_func,
3838 subscriber->user_data);
3839 g_main_context_unref (subscriber->context);
3842 g_array_free (subscribers, TRUE);
3845 /* ---------------------------------------------------------------------------------------------------- */
3847 static GDBusInterfaceVTable *
3848 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3850 /* Don't waste memory by copying padding - remember to update this
3851 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3853 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3857 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3862 /* ---------------------------------------------------------------------------------------------------- */
3864 static GDBusSubtreeVTable *
3865 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3867 /* Don't waste memory by copying padding - remember to update this
3868 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3870 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3874 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3879 /* ---------------------------------------------------------------------------------------------------- */
3881 struct ExportedObject
3884 GDBusConnection *connection;
3886 /* maps gchar* -> ExportedInterface* */
3887 GHashTable *map_if_name_to_ei;
3890 /* only called with lock held */
3892 exported_object_free (ExportedObject *eo)
3894 g_free (eo->object_path);
3895 g_hash_table_unref (eo->map_if_name_to_ei);
3904 gchar *interface_name;
3905 GDBusInterfaceVTable *vtable;
3906 GDBusInterfaceInfo *interface_info;
3908 GMainContext *context;
3910 GDestroyNotify user_data_free_func;
3911 } ExportedInterface;
3913 /* called with lock held */
3915 exported_interface_free (ExportedInterface *ei)
3917 g_dbus_interface_info_cache_release (ei->interface_info);
3918 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3920 call_destroy_notify (ei->context,
3921 ei->user_data_free_func,
3924 g_main_context_unref (ei->context);
3926 g_free (ei->interface_name);
3927 _g_dbus_interface_vtable_free (ei->vtable);
3931 /* ---------------------------------------------------------------------------------------------------- */
3933 /* Convenience function to check if @registration_id (if not zero) or
3934 * @subtree_registration_id (if not zero) has been unregistered. If
3935 * so, returns %TRUE.
3937 * May be called by any thread. Caller must *not* hold lock.
3940 has_object_been_unregistered (GDBusConnection *connection,
3941 guint registration_id,
3942 guint subtree_registration_id)
3946 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3950 CONNECTION_LOCK (connection);
3951 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3952 GUINT_TO_POINTER (registration_id)) == NULL)
3956 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3957 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3961 CONNECTION_UNLOCK (connection);
3966 /* ---------------------------------------------------------------------------------------------------- */
3970 GDBusConnection *connection;
3971 GDBusMessage *message;
3973 const gchar *property_name;
3974 const GDBusInterfaceVTable *vtable;
3975 GDBusInterfaceInfo *interface_info;
3976 const GDBusPropertyInfo *property_info;
3977 guint registration_id;
3978 guint subtree_registration_id;
3982 property_data_free (PropertyData *data)
3984 g_object_unref (data->connection);
3985 g_object_unref (data->message);
3989 /* called in thread where object was registered - no locks held */
3991 invoke_get_property_in_idle_cb (gpointer _data)
3993 PropertyData *data = _data;
3996 GDBusMessage *reply;
3998 if (has_object_been_unregistered (data->connection,
3999 data->registration_id,
4000 data->subtree_registration_id))
4002 reply = g_dbus_message_new_method_error (data->message,
4003 "org.freedesktop.DBus.Error.UnknownMethod",
4004 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4005 g_dbus_message_get_path (data->message));
4006 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4007 g_object_unref (reply);
4012 value = data->vtable->get_property (data->connection,
4013 g_dbus_message_get_sender (data->message),
4014 g_dbus_message_get_path (data->message),
4015 data->interface_info->name,
4016 data->property_name,
4023 g_assert_no_error (error);
4025 g_variant_take_ref (value);
4026 reply = g_dbus_message_new_method_reply (data->message);
4027 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4028 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4029 g_variant_unref (value);
4030 g_object_unref (reply);
4034 gchar *dbus_error_name;
4035 g_assert (error != NULL);
4036 dbus_error_name = g_dbus_error_encode_gerror (error);
4037 reply = g_dbus_message_new_method_error_literal (data->message,
4040 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4041 g_free (dbus_error_name);
4042 g_error_free (error);
4043 g_object_unref (reply);
4050 /* called in thread where object was registered - no locks held */
4052 invoke_set_property_in_idle_cb (gpointer _data)
4054 PropertyData *data = _data;
4056 GDBusMessage *reply;
4062 g_variant_get (g_dbus_message_get_body (data->message),
4068 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4069 * of the given value is wrong
4071 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4073 reply = g_dbus_message_new_method_error (data->message,
4074 "org.freedesktop.DBus.Error.InvalidArgs",
4075 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4076 data->property_info->name,
4077 data->property_info->signature,
4078 g_variant_get_type_string (value));
4082 if (!data->vtable->set_property (data->connection,
4083 g_dbus_message_get_sender (data->message),
4084 g_dbus_message_get_path (data->message),
4085 data->interface_info->name,
4086 data->property_name,
4091 gchar *dbus_error_name;
4092 g_assert (error != NULL);
4093 dbus_error_name = g_dbus_error_encode_gerror (error);
4094 reply = g_dbus_message_new_method_error_literal (data->message,
4097 g_free (dbus_error_name);
4098 g_error_free (error);
4102 reply = g_dbus_message_new_method_reply (data->message);
4106 g_assert (reply != NULL);
4107 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4108 g_object_unref (reply);
4109 g_variant_unref (value);
4114 /* called in any thread with connection's lock held */
4116 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4117 GDBusMessage *message,
4118 guint registration_id,
4119 guint subtree_registration_id,
4121 GDBusInterfaceInfo *interface_info,
4122 const GDBusInterfaceVTable *vtable,
4123 GMainContext *main_context,
4127 const char *interface_name;
4128 const char *property_name;
4129 const GDBusPropertyInfo *property_info;
4130 GSource *idle_source;
4131 PropertyData *property_data;
4132 GDBusMessage *reply;
4137 g_variant_get (g_dbus_message_get_body (message),
4142 g_variant_get (g_dbus_message_get_body (message),
4151 if (vtable == NULL || vtable->get_property == NULL)
4156 if (vtable == NULL || vtable->set_property == NULL)
4160 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4162 property_info = NULL;
4164 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4165 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4166 if (property_info == NULL)
4168 reply = g_dbus_message_new_method_error (message,
4169 "org.freedesktop.DBus.Error.InvalidArgs",
4170 _("No such property `%s'"),
4172 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4173 g_object_unref (reply);
4178 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4180 reply = g_dbus_message_new_method_error (message,
4181 "org.freedesktop.DBus.Error.InvalidArgs",
4182 _("Property `%s' is not readable"),
4184 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4185 g_object_unref (reply);
4189 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4191 reply = g_dbus_message_new_method_error (message,
4192 "org.freedesktop.DBus.Error.InvalidArgs",
4193 _("Property `%s' is not writable"),
4195 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4196 g_object_unref (reply);
4201 /* ok, got the property info - call user code in an idle handler */
4202 property_data = g_new0 (PropertyData, 1);
4203 property_data->connection = g_object_ref (connection);
4204 property_data->message = g_object_ref (message);
4205 property_data->user_data = user_data;
4206 property_data->property_name = property_name;
4207 property_data->vtable = vtable;
4208 property_data->interface_info = interface_info;
4209 property_data->property_info = property_info;
4210 property_data->registration_id = registration_id;
4211 property_data->subtree_registration_id = subtree_registration_id;
4213 idle_source = g_idle_source_new ();
4214 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4215 g_source_set_callback (idle_source,
4216 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4218 (GDestroyNotify) property_data_free);
4219 g_source_attach (idle_source, main_context);
4220 g_source_unref (idle_source);
4228 /* called in GDBusWorker thread with connection's lock held */
4230 handle_getset_property (GDBusConnection *connection,
4232 GDBusMessage *message,
4235 ExportedInterface *ei;
4237 const char *interface_name;
4238 const char *property_name;
4243 g_variant_get (g_dbus_message_get_body (message),
4248 g_variant_get (g_dbus_message_get_body (message),
4254 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4255 * no such interface registered
4257 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4260 GDBusMessage *reply;
4261 reply = g_dbus_message_new_method_error (message,
4262 "org.freedesktop.DBus.Error.InvalidArgs",
4263 _("No such interface `%s'"),
4265 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4266 g_object_unref (reply);
4271 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4284 /* ---------------------------------------------------------------------------------------------------- */
4288 GDBusConnection *connection;
4289 GDBusMessage *message;
4291 const GDBusInterfaceVTable *vtable;
4292 GDBusInterfaceInfo *interface_info;
4293 guint registration_id;
4294 guint subtree_registration_id;
4295 } PropertyGetAllData;
4298 property_get_all_data_free (PropertyData *data)
4300 g_object_unref (data->connection);
4301 g_object_unref (data->message);
4305 /* called in thread where object was registered - no locks held */
4307 invoke_get_all_properties_in_idle_cb (gpointer _data)
4309 PropertyGetAllData *data = _data;
4310 GVariantBuilder builder;
4311 GDBusMessage *reply;
4314 if (has_object_been_unregistered (data->connection,
4315 data->registration_id,
4316 data->subtree_registration_id))
4318 reply = g_dbus_message_new_method_error (data->message,
4319 "org.freedesktop.DBus.Error.UnknownMethod",
4320 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4321 g_dbus_message_get_path (data->message));
4322 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4323 g_object_unref (reply);
4327 /* TODO: Right now we never fail this call - we just omit values if
4328 * a get_property() call is failing.
4330 * We could fail the whole call if just a single get_property() call
4331 * returns an error. We need clarification in the D-Bus spec about this.
4333 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4334 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4335 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4337 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4340 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4343 value = data->vtable->get_property (data->connection,
4344 g_dbus_message_get_sender (data->message),
4345 g_dbus_message_get_path (data->message),
4346 data->interface_info->name,
4347 property_info->name,
4354 g_variant_take_ref (value);
4355 g_variant_builder_add (&builder,
4357 property_info->name,
4359 g_variant_unref (value);
4361 g_variant_builder_close (&builder);
4363 reply = g_dbus_message_new_method_reply (data->message);
4364 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4365 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4366 g_object_unref (reply);
4372 /* called in any thread with connection's lock held */
4374 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4375 GDBusMessage *message,
4376 guint registration_id,
4377 guint subtree_registration_id,
4378 GDBusInterfaceInfo *interface_info,
4379 const GDBusInterfaceVTable *vtable,
4380 GMainContext *main_context,
4384 const char *interface_name;
4385 GSource *idle_source;
4386 PropertyGetAllData *property_get_all_data;
4390 g_variant_get (g_dbus_message_get_body (message),
4394 if (vtable == NULL || vtable->get_property == NULL)
4397 /* ok, got the property info - call user in an idle handler */
4398 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4399 property_get_all_data->connection = g_object_ref (connection);
4400 property_get_all_data->message = g_object_ref (message);
4401 property_get_all_data->user_data = user_data;
4402 property_get_all_data->vtable = vtable;
4403 property_get_all_data->interface_info = interface_info;
4404 property_get_all_data->registration_id = registration_id;
4405 property_get_all_data->subtree_registration_id = subtree_registration_id;
4407 idle_source = g_idle_source_new ();
4408 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4409 g_source_set_callback (idle_source,
4410 invoke_get_all_properties_in_idle_cb,
4411 property_get_all_data,
4412 (GDestroyNotify) property_get_all_data_free);
4413 g_source_attach (idle_source, main_context);
4414 g_source_unref (idle_source);
4422 /* called in GDBusWorker thread with connection's lock held */
4424 handle_get_all_properties (GDBusConnection *connection,
4426 GDBusMessage *message)
4428 ExportedInterface *ei;
4430 const char *interface_name;
4434 g_variant_get (g_dbus_message_get_body (message),
4438 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4439 * no such interface registered
4441 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4444 GDBusMessage *reply;
4445 reply = g_dbus_message_new_method_error (message,
4446 "org.freedesktop.DBus.Error.InvalidArgs",
4447 _("No such interface"),
4449 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4450 g_object_unref (reply);
4455 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4467 /* ---------------------------------------------------------------------------------------------------- */
4469 static const gchar introspect_header[] =
4470 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4471 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4472 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4475 static const gchar introspect_tail[] =
4478 static const gchar introspect_properties_interface[] =
4479 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4480 " <method name=\"Get\">\n"
4481 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4482 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4483 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4485 " <method name=\"GetAll\">\n"
4486 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4487 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4489 " <method name=\"Set\">\n"
4490 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4491 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4492 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4494 " <signal name=\"PropertiesChanged\">\n"
4495 " <arg type=\"s\" name=\"interface_name\"/>\n"
4496 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4497 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4501 static const gchar introspect_introspectable_interface[] =
4502 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4503 " <method name=\"Introspect\">\n"
4504 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4507 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4508 " <method name=\"Ping\"/>\n"
4509 " <method name=\"GetMachineId\">\n"
4510 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4515 introspect_append_header (GString *s)
4517 g_string_append (s, introspect_header);
4521 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4523 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4529 begin = object_path + path_len;
4530 end = strchr (begin, '/');
4532 s = g_strndup (begin, end - begin);
4534 s = g_strdup (begin);
4536 if (g_hash_table_lookup (set, s) == NULL)
4537 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4543 /* TODO: we want a nicer public interface for this */
4544 /* called in any thread with connection's lock held */
4546 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4551 GHashTableIter hash_iter;
4552 const gchar *object_path;
4558 CONNECTION_ENSURE_LOCK (connection);
4560 path_len = strlen (path);
4564 set = g_hash_table_new (g_str_hash, g_str_equal);
4566 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4567 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4568 maybe_add_path (path, path_len, object_path, set);
4570 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4571 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4572 maybe_add_path (path, path_len, object_path, set);
4574 p = g_ptr_array_new ();
4575 keys = g_hash_table_get_keys (set);
4576 for (l = keys; l != NULL; l = l->next)
4577 g_ptr_array_add (p, l->data);
4578 g_hash_table_unref (set);
4581 g_ptr_array_add (p, NULL);
4582 ret = (gchar **) g_ptr_array_free (p, FALSE);
4586 /* called in any thread with connection's lock not held */
4588 g_dbus_connection_list_registered (GDBusConnection *connection,
4592 CONNECTION_LOCK (connection);
4593 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4594 CONNECTION_UNLOCK (connection);
4598 /* called in GDBusWorker thread with connection's lock held */
4600 handle_introspect (GDBusConnection *connection,
4602 GDBusMessage *message)
4606 GDBusMessage *reply;
4607 GHashTableIter hash_iter;
4608 ExportedInterface *ei;
4611 /* first the header with the standard interfaces */
4612 s = g_string_sized_new (sizeof (introspect_header) +
4613 sizeof (introspect_properties_interface) +
4614 sizeof (introspect_introspectable_interface) +
4615 sizeof (introspect_tail));
4616 introspect_append_header (s);
4617 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4618 "org.freedesktop.DBus.Properties"))
4619 g_string_append (s, introspect_properties_interface);
4621 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4622 "org.freedesktop.DBus.Introspectable"))
4623 g_string_append (s, introspect_introspectable_interface);
4625 /* then include the registered interfaces */
4626 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4627 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4628 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4630 /* finally include nodes registered below us */
4631 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4632 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4633 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4634 g_strfreev (registered);
4635 g_string_append (s, introspect_tail);
4637 reply = g_dbus_message_new_method_reply (message);
4638 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4639 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4640 g_object_unref (reply);
4641 g_string_free (s, TRUE);
4646 /* called in thread where object was registered - no locks held */
4648 call_in_idle_cb (gpointer user_data)
4650 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4651 GDBusInterfaceVTable *vtable;
4652 guint registration_id;
4653 guint subtree_registration_id;
4655 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4656 g_assert (vtable != NULL && vtable->method_call != NULL);
4658 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4659 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4661 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4663 subtree_registration_id))
4665 GDBusMessage *reply;
4666 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4667 "org.freedesktop.DBus.Error.UnknownMethod",
4668 _("No such interface `%s' on object at path %s"),
4669 g_dbus_method_invocation_get_interface_name (invocation),
4670 g_dbus_method_invocation_get_object_path (invocation));
4671 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4672 g_object_unref (reply);
4676 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4677 g_dbus_method_invocation_get_sender (invocation),
4678 g_dbus_method_invocation_get_object_path (invocation),
4679 g_dbus_method_invocation_get_interface_name (invocation),
4680 g_dbus_method_invocation_get_method_name (invocation),
4681 g_dbus_method_invocation_get_parameters (invocation),
4682 g_object_ref (invocation),
4683 g_dbus_method_invocation_get_user_data (invocation));
4689 /* called in GDBusWorker thread with connection's lock held */
4691 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4692 GDBusMessage *message,
4693 guint registration_id,
4694 guint subtree_registration_id,
4695 GDBusInterfaceInfo *interface_info,
4696 const GDBusInterfaceVTable *vtable,
4697 GMainContext *main_context,
4700 GDBusMethodInvocation *invocation;
4701 const GDBusMethodInfo *method_info;
4702 GDBusMessage *reply;
4703 GVariant *parameters;
4704 GSource *idle_source;
4706 GVariantType *in_type;
4710 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4711 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4713 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4714 * error to the caller
4716 if (method_info == NULL)
4718 reply = g_dbus_message_new_method_error (message,
4719 "org.freedesktop.DBus.Error.UnknownMethod",
4720 _("No such method `%s'"),
4721 g_dbus_message_get_member (message));
4722 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4723 g_object_unref (reply);
4728 parameters = g_dbus_message_get_body (message);
4729 if (parameters == NULL)
4731 parameters = g_variant_new ("()");
4732 g_variant_ref_sink (parameters);
4736 g_variant_ref (parameters);
4739 /* Check that the incoming args are of the right type - if they are not, return
4740 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4742 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4743 if (!g_variant_is_of_type (parameters, in_type))
4747 type_string = g_variant_type_dup_string (in_type);
4749 reply = g_dbus_message_new_method_error (message,
4750 "org.freedesktop.DBus.Error.InvalidArgs",
4751 _("Type of message, `%s', does not match expected type `%s'"),
4752 g_variant_get_type_string (parameters),
4754 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4755 g_variant_type_free (in_type);
4756 g_variant_unref (parameters);
4757 g_object_unref (reply);
4758 g_free (type_string);
4762 g_variant_type_free (in_type);
4764 /* schedule the call in idle */
4765 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4766 g_dbus_message_get_path (message),
4767 g_dbus_message_get_interface (message),
4768 g_dbus_message_get_member (message),
4774 g_variant_unref (parameters);
4776 /* TODO: would be nicer with a real MethodData like we already
4777 * have PropertyData and PropertyGetAllData... */
4778 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4779 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4780 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4782 idle_source = g_idle_source_new ();
4783 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4784 g_source_set_callback (idle_source,
4788 g_source_attach (idle_source, main_context);
4789 g_source_unref (idle_source);
4797 /* ---------------------------------------------------------------------------------------------------- */
4799 /* called in GDBusWorker thread with connection's lock held */
4801 obj_message_func (GDBusConnection *connection,
4803 GDBusMessage *message)
4805 const gchar *interface_name;
4806 const gchar *member;
4807 const gchar *signature;
4812 interface_name = g_dbus_message_get_interface (message);
4813 member = g_dbus_message_get_member (message);
4814 signature = g_dbus_message_get_signature (message);
4816 /* see if we have an interface for handling this call */
4817 if (interface_name != NULL)
4819 ExportedInterface *ei;
4820 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4823 /* we do - invoke the handler in idle in the right thread */
4825 /* handle no vtable or handler being present */
4826 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4829 handled = validate_and_maybe_schedule_method_call (connection,
4841 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4842 g_strcmp0 (member, "Introspect") == 0 &&
4843 g_strcmp0 (signature, "") == 0)
4845 handled = handle_introspect (connection, eo, message);
4848 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4849 g_strcmp0 (member, "Get") == 0 &&
4850 g_strcmp0 (signature, "ss") == 0)
4852 handled = handle_getset_property (connection, eo, message, TRUE);
4855 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4856 g_strcmp0 (member, "Set") == 0 &&
4857 g_strcmp0 (signature, "ssv") == 0)
4859 handled = handle_getset_property (connection, eo, message, FALSE);
4862 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4863 g_strcmp0 (member, "GetAll") == 0 &&
4864 g_strcmp0 (signature, "s") == 0)
4866 handled = handle_get_all_properties (connection, eo, message);
4875 * g_dbus_connection_register_object:
4876 * @connection: A #GDBusConnection.
4877 * @object_path: The object path to register at.
4878 * @interface_info: Introspection data for the interface.
4879 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4880 * @user_data: (allow-none): Data to pass to functions in @vtable.
4881 * @user_data_free_func: Function to call when the object path is unregistered.
4882 * @error: Return location for error or %NULL.
4884 * Registers callbacks for exported objects at @object_path with the
4885 * D-Bus interface that is described in @interface_info.
4887 * Calls to functions in @vtable (and @user_data_free_func) will
4888 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4889 * loop</link> of the thread you are calling this method from.
4891 * Note that all #GVariant values passed to functions in @vtable will match
4892 * the signature given in @interface_info - if a remote caller passes
4893 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4894 * is returned to the remote caller.
4896 * Additionally, if the remote caller attempts to invoke methods or
4897 * access properties not mentioned in @interface_info the
4898 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4899 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4900 * are returned to the caller.
4902 * It is considered a programming error if the
4903 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4904 * #GVariant of incorrect type.
4906 * If an existing callback is already registered at @object_path and
4907 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4909 * GDBus automatically implements the standard D-Bus interfaces
4910 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4911 * and org.freedesktop.Peer, so you don't have to implement those for
4912 * the objects you export. You <emphasis>can</emphasis> implement
4913 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4914 * and setting of properties asynchronously.
4916 * Note that the reference count on @interface_info will be
4917 * incremented by 1 (unless allocated statically, e.g. if the
4918 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4919 * as the object is exported. Also note that @vtable will be copied.
4921 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4923 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4924 * that can be used with g_dbus_connection_unregister_object() .
4929 g_dbus_connection_register_object (GDBusConnection *connection,
4930 const gchar *object_path,
4931 GDBusInterfaceInfo *interface_info,
4932 const GDBusInterfaceVTable *vtable,
4934 GDestroyNotify user_data_free_func,
4938 ExportedInterface *ei;
4941 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4942 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4943 g_return_val_if_fail (interface_info != NULL, 0);
4944 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4945 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4946 g_return_val_if_fail (check_initialized (connection), 0);
4950 CONNECTION_LOCK (connection);
4952 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4955 eo = g_new0 (ExportedObject, 1);
4956 eo->object_path = g_strdup (object_path);
4957 eo->connection = connection;
4958 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4961 (GDestroyNotify) exported_interface_free);
4962 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4965 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4971 _("An object is already exported for the interface %s at %s"),
4972 interface_info->name,
4977 ei = g_new0 (ExportedInterface, 1);
4978 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4980 ei->user_data = user_data;
4981 ei->user_data_free_func = user_data_free_func;
4982 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4983 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4984 g_dbus_interface_info_cache_build (ei->interface_info);
4985 ei->interface_name = g_strdup (interface_info->name);
4986 ei->context = g_main_context_ref_thread_default ();
4988 g_hash_table_insert (eo->map_if_name_to_ei,
4989 (gpointer) ei->interface_name,
4991 g_hash_table_insert (connection->map_id_to_ei,
4992 GUINT_TO_POINTER (ei->id),
4998 CONNECTION_UNLOCK (connection);
5004 * g_dbus_connection_unregister_object:
5005 * @connection: A #GDBusConnection.
5006 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5008 * Unregisters an object.
5010 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5015 g_dbus_connection_unregister_object (GDBusConnection *connection,
5016 guint registration_id)
5018 ExportedInterface *ei;
5022 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5023 g_return_val_if_fail (check_initialized (connection), FALSE);
5027 CONNECTION_LOCK (connection);
5029 ei = g_hash_table_lookup (connection->map_id_to_ei,
5030 GUINT_TO_POINTER (registration_id));
5036 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5037 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5038 /* unregister object path if we have no more exported interfaces */
5039 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5040 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5046 CONNECTION_UNLOCK (connection);
5051 /* ---------------------------------------------------------------------------------------------------- */
5054 * g_dbus_connection_emit_signal:
5055 * @connection: A #GDBusConnection.
5056 * @destination_bus_name: (allow-none): The unique bus name for the destination
5057 * for the signal or %NULL to emit to all listeners.
5058 * @object_path: Path of remote object.
5059 * @interface_name: D-Bus interface to emit a signal on.
5060 * @signal_name: The name of the signal to emit.
5061 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5062 * or %NULL if not passing parameters.
5063 * @error: Return location for error or %NULL.
5067 * If the parameters GVariant is floating, it is consumed.
5069 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5071 * Returns: %TRUE unless @error is set.
5076 g_dbus_connection_emit_signal (GDBusConnection *connection,
5077 const gchar *destination_bus_name,
5078 const gchar *object_path,
5079 const gchar *interface_name,
5080 const gchar *signal_name,
5081 GVariant *parameters,
5084 GDBusMessage *message;
5090 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5091 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5092 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5093 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5094 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5095 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5096 g_return_val_if_fail (check_initialized (connection), FALSE);
5098 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5100 _g_dbus_debug_print_lock ();
5101 g_print ("========================================================================\n"
5102 "GDBus-debug:Emission:\n"
5103 " >>>> SIGNAL EMISSION %s.%s()\n"
5105 " destination %s\n",
5106 interface_name, signal_name,
5108 destination_bus_name != NULL ? destination_bus_name : "(none)");
5109 _g_dbus_debug_print_unlock ();
5112 message = g_dbus_message_new_signal (object_path,
5116 if (destination_bus_name != NULL)
5117 g_dbus_message_set_header (message,
5118 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5119 g_variant_new_string (destination_bus_name));
5121 if (parameters != NULL)
5122 g_dbus_message_set_body (message, parameters);
5124 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5125 g_object_unref (message);
5131 add_call_flags (GDBusMessage *message,
5132 GDBusCallFlags flags)
5134 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5135 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5139 decode_method_reply (GDBusMessage *reply,
5140 const gchar *method_name,
5141 const GVariantType *reply_type,
5142 GUnixFDList **out_fd_list,
5148 switch (g_dbus_message_get_message_type (reply))
5150 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5151 result = g_dbus_message_get_body (reply);
5154 result = g_variant_new ("()");
5155 g_variant_ref_sink (result);
5159 g_variant_ref (result);
5162 if (!g_variant_is_of_type (result, reply_type))
5164 gchar *type_string = g_variant_type_dup_string (reply_type);
5168 G_IO_ERROR_INVALID_ARGUMENT,
5169 _("Method `%s' returned type `%s', but expected `%s'"),
5170 method_name, g_variant_get_type_string (result), type_string);
5172 g_variant_unref (result);
5173 g_free (type_string);
5180 if (out_fd_list != NULL)
5182 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5183 if (*out_fd_list != NULL)
5184 g_object_ref (*out_fd_list);
5190 case G_DBUS_MESSAGE_TYPE_ERROR:
5191 g_dbus_message_to_gerror (reply, error);
5195 g_assert_not_reached ();
5205 GSimpleAsyncResult *simple;
5206 GVariantType *reply_type;
5207 gchar *method_name; /* for error message */
5211 GUnixFDList *fd_list;
5215 call_state_free (CallState *state)
5217 g_variant_type_free (state->reply_type);
5218 g_free (state->method_name);
5220 if (state->value != NULL)
5221 g_variant_unref (state->value);
5222 if (state->fd_list != NULL)
5223 g_object_unref (state->fd_list);
5224 g_slice_free (CallState, state);
5227 /* called in any thread, with the connection's lock not held */
5229 g_dbus_connection_call_done (GObject *source,
5230 GAsyncResult *result,
5233 GSimpleAsyncResult *simple;
5234 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5235 CallState *state = user_data;
5237 GDBusMessage *reply;
5240 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5244 if (G_UNLIKELY (_g_dbus_debug_call ()))
5246 _g_dbus_debug_print_lock ();
5247 g_print ("========================================================================\n"
5248 "GDBus-debug:Call:\n"
5249 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5255 g_print ("SUCCESS\n");
5259 g_print ("FAILED: %s\n",
5262 _g_dbus_debug_print_unlock ();
5266 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5268 simple = state->simple; /* why? because state is freed before we unref simple.. */
5271 g_simple_async_result_take_error (state->simple, error);
5272 g_simple_async_result_complete (state->simple);
5273 call_state_free (state);
5277 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5278 g_simple_async_result_complete (state->simple);
5279 g_object_unref (reply);
5281 g_object_unref (simple);
5284 /* called in any thread, with the connection's lock not held */
5286 g_dbus_connection_call_internal (GDBusConnection *connection,
5287 const gchar *bus_name,
5288 const gchar *object_path,
5289 const gchar *interface_name,
5290 const gchar *method_name,
5291 GVariant *parameters,
5292 const GVariantType *reply_type,
5293 GDBusCallFlags flags,
5295 GUnixFDList *fd_list,
5296 GCancellable *cancellable,
5297 GAsyncReadyCallback callback,
5300 GDBusMessage *message;
5303 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5304 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5305 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5306 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5307 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5308 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5309 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5310 g_return_if_fail (check_initialized (connection));
5312 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5314 g_return_if_fail (fd_list == NULL);
5317 state = g_slice_new0 (CallState);
5318 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5319 callback, user_data,
5320 g_dbus_connection_call_internal);
5321 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5323 if (reply_type == NULL)
5324 reply_type = G_VARIANT_TYPE_ANY;
5326 state->reply_type = g_variant_type_copy (reply_type);
5328 message = g_dbus_message_new_method_call (bus_name,
5332 add_call_flags (message, flags);
5333 if (parameters != NULL)
5334 g_dbus_message_set_body (message, parameters);
5337 if (fd_list != NULL)
5338 g_dbus_message_set_unix_fd_list (message, fd_list);
5341 g_dbus_connection_send_message_with_reply (connection,
5343 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5347 g_dbus_connection_call_done,
5350 if (G_UNLIKELY (_g_dbus_debug_call ()))
5352 _g_dbus_debug_print_lock ();
5353 g_print ("========================================================================\n"
5354 "GDBus-debug:Call:\n"
5355 " >>>> ASYNC %s.%s()\n"
5357 " owned by name %s (serial %d)\n",
5361 bus_name != NULL ? bus_name : "(none)",
5363 _g_dbus_debug_print_unlock ();
5366 if (message != NULL)
5367 g_object_unref (message);
5370 /* called in any thread, with the connection's lock not held */
5372 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5373 GUnixFDList **out_fd_list,
5377 GSimpleAsyncResult *simple;
5380 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5381 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5382 g_dbus_connection_call_internal), NULL);
5383 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5385 simple = G_SIMPLE_ASYNC_RESULT (res);
5387 if (g_simple_async_result_propagate_error (simple, error))
5390 state = g_simple_async_result_get_op_res_gpointer (simple);
5391 if (out_fd_list != NULL)
5392 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5393 return g_variant_ref (state->value);
5396 /* called in any user thread, with the connection's lock not held */
5398 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5399 const gchar *bus_name,
5400 const gchar *object_path,
5401 const gchar *interface_name,
5402 const gchar *method_name,
5403 GVariant *parameters,
5404 const GVariantType *reply_type,
5405 GDBusCallFlags flags,
5407 GUnixFDList *fd_list,
5408 GUnixFDList **out_fd_list,
5409 GCancellable *cancellable,
5412 GDBusMessage *message;
5413 GDBusMessage *reply;
5415 GError *local_error;
5416 GDBusSendMessageFlags send_flags;
5422 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5423 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5424 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5425 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5426 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5427 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5428 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5430 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5432 g_return_val_if_fail (fd_list == NULL, NULL);
5434 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5436 if (!(flags & CALL_FLAGS_INITIALIZING))
5437 g_return_val_if_fail (check_initialized (connection), FALSE);
5439 if (reply_type == NULL)
5440 reply_type = G_VARIANT_TYPE_ANY;
5442 message = g_dbus_message_new_method_call (bus_name,
5446 add_call_flags (message, flags);
5447 if (parameters != NULL)
5448 g_dbus_message_set_body (message, parameters);
5451 if (fd_list != NULL)
5452 g_dbus_message_set_unix_fd_list (message, fd_list);
5455 if (G_UNLIKELY (_g_dbus_debug_call ()))
5457 _g_dbus_debug_print_lock ();
5458 g_print ("========================================================================\n"
5459 "GDBus-debug:Call:\n"
5460 " >>>> SYNC %s.%s()\n"
5462 " owned by name %s\n",
5466 bus_name != NULL ? bus_name : "(none)");
5467 _g_dbus_debug_print_unlock ();
5472 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5474 /* translate from one flavour of flags to another... */
5475 if (flags & CALL_FLAGS_INITIALIZING)
5476 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5478 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5482 NULL, /* volatile guint32 *out_serial */
5486 if (G_UNLIKELY (_g_dbus_debug_call ()))
5488 _g_dbus_debug_print_lock ();
5489 g_print ("========================================================================\n"
5490 "GDBus-debug:Call:\n"
5491 " <<<< SYNC COMPLETE %s.%s()\n"
5497 g_print ("SUCCESS\n");
5501 g_print ("FAILED: %s\n",
5502 local_error->message);
5504 _g_dbus_debug_print_unlock ();
5510 *error = local_error;
5512 g_error_free (local_error);
5516 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5519 if (message != NULL)
5520 g_object_unref (message);
5522 g_object_unref (reply);
5527 /* ---------------------------------------------------------------------------------------------------- */
5530 * g_dbus_connection_call:
5531 * @connection: A #GDBusConnection.
5532 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5533 * @connection is not a message bus connection.
5534 * @object_path: Path of remote object.
5535 * @interface_name: D-Bus interface to invoke method on.
5536 * @method_name: The name of the method to invoke.
5537 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5538 * or %NULL if not passing parameters.
5539 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5540 * @flags: Flags from the #GDBusCallFlags enumeration.
5541 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5542 * timeout or %G_MAXINT for no timeout.
5543 * @cancellable: A #GCancellable or %NULL.
5544 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5545 * satisfied or %NULL if you don't * care about the result of the
5546 * method invocation.
5547 * @user_data: The data to pass to @callback.
5549 * Asynchronously invokes the @method_name method on the
5550 * @interface_name D-Bus interface on the remote object at
5551 * @object_path owned by @bus_name.
5553 * If @connection is closed then the operation will fail with
5554 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5555 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5556 * not compatible with the D-Bus protocol, the operation fails with
5557 * %G_IO_ERROR_INVALID_ARGUMENT.
5559 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5560 * error will be raised if it does not match. Said another way, if you give a @reply_type
5561 * then any non-%NULL return value will be of this type.
5563 * If the @parameters #GVariant is floating, it is consumed. This allows
5564 * convenient 'inline' use of g_variant_new(), e.g.:
5566 * g_dbus_connection_call (connection,
5567 * "org.freedesktop.StringThings",
5568 * "/org/freedesktop/StringThings",
5569 * "org.freedesktop.StringThings",
5571 * g_variant_new ("(ss)",
5575 * G_DBUS_CALL_FLAGS_NONE,
5578 * (GAsyncReadyCallback) two_strings_done,
5582 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5583 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5584 * of the thread you are calling this method from. You can then call
5585 * g_dbus_connection_call_finish() to get the result of the operation.
5586 * See g_dbus_connection_call_sync() for the synchronous version of this
5592 g_dbus_connection_call (GDBusConnection *connection,
5593 const gchar *bus_name,
5594 const gchar *object_path,
5595 const gchar *interface_name,
5596 const gchar *method_name,
5597 GVariant *parameters,
5598 const GVariantType *reply_type,
5599 GDBusCallFlags flags,
5601 GCancellable *cancellable,
5602 GAsyncReadyCallback callback,
5605 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);
5609 * g_dbus_connection_call_finish:
5610 * @connection: A #GDBusConnection.
5611 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5612 * @error: Return location for error or %NULL.
5614 * Finishes an operation started with g_dbus_connection_call().
5616 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5617 * return values. Free with g_variant_unref().
5622 g_dbus_connection_call_finish (GDBusConnection *connection,
5626 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5630 * g_dbus_connection_call_sync:
5631 * @connection: A #GDBusConnection.
5632 * @bus_name: A unique or well-known bus name.
5633 * @object_path: Path of remote object.
5634 * @interface_name: D-Bus interface to invoke method on.
5635 * @method_name: The name of the method to invoke.
5636 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5637 * or %NULL if not passing parameters.
5638 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5639 * @flags: Flags from the #GDBusCallFlags enumeration.
5640 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5641 * timeout or %G_MAXINT for no timeout.
5642 * @cancellable: A #GCancellable or %NULL.
5643 * @error: Return location for error or %NULL.
5645 * Synchronously invokes the @method_name method on the
5646 * @interface_name D-Bus interface on the remote object at
5647 * @object_path owned by @bus_name.
5649 * If @connection is closed then the operation will fail with
5650 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5651 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5652 * contains a value not compatible with the D-Bus protocol, the operation
5653 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5655 * If @reply_type is non-%NULL then the reply will be checked for having
5656 * this type and an error will be raised if it does not match. Said
5657 * another way, if you give a @reply_type then any non-%NULL return
5658 * value will be of this type.
5660 * If the @parameters #GVariant is floating, it is consumed.
5661 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5663 * g_dbus_connection_call_sync (connection,
5664 * "org.freedesktop.StringThings",
5665 * "/org/freedesktop/StringThings",
5666 * "org.freedesktop.StringThings",
5668 * g_variant_new ("(ss)",
5672 * G_DBUS_CALL_FLAGS_NONE,
5678 * The calling thread is blocked until a reply is received. See
5679 * g_dbus_connection_call() for the asynchronous version of
5682 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5683 * return values. Free with g_variant_unref().
5688 g_dbus_connection_call_sync (GDBusConnection *connection,
5689 const gchar *bus_name,
5690 const gchar *object_path,
5691 const gchar *interface_name,
5692 const gchar *method_name,
5693 GVariant *parameters,
5694 const GVariantType *reply_type,
5695 GDBusCallFlags flags,
5697 GCancellable *cancellable,
5700 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);
5703 /* ---------------------------------------------------------------------------------------------------- */
5708 * g_dbus_connection_call_with_unix_fd_list:
5709 * @connection: A #GDBusConnection.
5710 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5711 * @connection is not a message bus connection.
5712 * @object_path: Path of remote object.
5713 * @interface_name: D-Bus interface to invoke method on.
5714 * @method_name: The name of the method to invoke.
5715 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5716 * or %NULL if not passing parameters.
5717 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5718 * @flags: Flags from the #GDBusCallFlags enumeration.
5719 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5720 * timeout or %G_MAXINT for no timeout.
5721 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5722 * @cancellable: A #GCancellable or %NULL.
5723 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5724 * satisfied or %NULL if you don't * care about the result of the
5725 * method invocation.
5726 * @user_data: The data to pass to @callback.
5728 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5730 * This method is only available on UNIX.
5735 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5736 const gchar *bus_name,
5737 const gchar *object_path,
5738 const gchar *interface_name,
5739 const gchar *method_name,
5740 GVariant *parameters,
5741 const GVariantType *reply_type,
5742 GDBusCallFlags flags,
5744 GUnixFDList *fd_list,
5745 GCancellable *cancellable,
5746 GAsyncReadyCallback callback,
5749 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);
5753 * g_dbus_connection_call_with_unix_fd_list_finish:
5754 * @connection: A #GDBusConnection.
5755 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5756 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5757 * @error: Return location for error or %NULL.
5759 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5761 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5762 * return values. Free with g_variant_unref().
5767 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5768 GUnixFDList **out_fd_list,
5772 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5776 * g_dbus_connection_call_with_unix_fd_list_sync:
5777 * @connection: A #GDBusConnection.
5778 * @bus_name: A unique or well-known bus name.
5779 * @object_path: Path of remote object.
5780 * @interface_name: D-Bus interface to invoke method on.
5781 * @method_name: The name of the method to invoke.
5782 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5783 * or %NULL if not passing parameters.
5784 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5785 * @flags: Flags from the #GDBusCallFlags enumeration.
5786 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5787 * timeout or %G_MAXINT for no timeout.
5788 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5789 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5790 * @cancellable: A #GCancellable or %NULL.
5791 * @error: Return location for error or %NULL.
5793 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5795 * This method is only available on UNIX.
5797 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5798 * return values. Free with g_variant_unref().
5803 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5804 const gchar *bus_name,
5805 const gchar *object_path,
5806 const gchar *interface_name,
5807 const gchar *method_name,
5808 GVariant *parameters,
5809 const GVariantType *reply_type,
5810 GDBusCallFlags flags,
5812 GUnixFDList *fd_list,
5813 GUnixFDList **out_fd_list,
5814 GCancellable *cancellable,
5817 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);
5820 #endif /* G_OS_UNIX */
5822 /* ---------------------------------------------------------------------------------------------------- */
5824 struct ExportedSubtree
5828 GDBusConnection *connection;
5829 GDBusSubtreeVTable *vtable;
5830 GDBusSubtreeFlags flags;
5832 GMainContext *context;
5834 GDestroyNotify user_data_free_func;
5838 exported_subtree_free (ExportedSubtree *es)
5840 call_destroy_notify (es->context,
5841 es->user_data_free_func,
5844 g_main_context_unref (es->context);
5846 _g_dbus_subtree_vtable_free (es->vtable);
5847 g_free (es->object_path);
5851 /* called without lock held in the thread where the caller registered
5855 handle_subtree_introspect (GDBusConnection *connection,
5856 ExportedSubtree *es,
5857 GDBusMessage *message)
5861 GDBusMessage *reply;
5864 const gchar *sender;
5865 const gchar *requested_object_path;
5866 const gchar *requested_node;
5867 GDBusInterfaceInfo **interfaces;
5869 gchar **subnode_paths;
5870 gboolean has_properties_interface;
5871 gboolean has_introspectable_interface;
5875 requested_object_path = g_dbus_message_get_path (message);
5876 sender = g_dbus_message_get_sender (message);
5877 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5879 s = g_string_new (NULL);
5880 introspect_append_header (s);
5882 /* Strictly we don't need the children in dynamic mode, but we avoid the
5883 * conditionals to preserve code clarity
5885 children = es->vtable->enumerate (es->connection,
5892 requested_node = strrchr (requested_object_path, '/') + 1;
5894 /* Assert existence of object if we are not dynamic */
5895 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5896 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5901 requested_node = NULL;
5904 interfaces = es->vtable->introspect (es->connection,
5909 if (interfaces != NULL)
5911 has_properties_interface = FALSE;
5912 has_introspectable_interface = FALSE;
5914 for (n = 0; interfaces[n] != NULL; n++)
5916 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5917 has_properties_interface = TRUE;
5918 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5919 has_introspectable_interface = TRUE;
5921 if (!has_properties_interface)
5922 g_string_append (s, introspect_properties_interface);
5923 if (!has_introspectable_interface)
5924 g_string_append (s, introspect_introspectable_interface);
5926 for (n = 0; interfaces[n] != NULL; n++)
5928 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5929 g_dbus_interface_info_unref (interfaces[n]);
5931 g_free (interfaces);
5934 /* then include <node> entries from the Subtree for the root */
5937 for (n = 0; children != NULL && children[n] != NULL; n++)
5938 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5941 /* finally include nodes registered below us */
5942 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5943 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5944 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5945 g_strfreev (subnode_paths);
5947 g_string_append (s, "</node>\n");
5949 reply = g_dbus_message_new_method_reply (message);
5950 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5951 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5952 g_object_unref (reply);
5957 g_string_free (s, TRUE);
5958 g_strfreev (children);
5962 /* called without lock held in the thread where the caller registered
5966 handle_subtree_method_invocation (GDBusConnection *connection,
5967 ExportedSubtree *es,
5968 GDBusMessage *message)
5971 const gchar *sender;
5972 const gchar *interface_name;
5973 const gchar *member;
5974 const gchar *signature;
5975 const gchar *requested_object_path;
5976 const gchar *requested_node;
5978 GDBusInterfaceInfo *interface_info;
5979 const GDBusInterfaceVTable *interface_vtable;
5980 gpointer interface_user_data;
5982 GDBusInterfaceInfo **interfaces;
5983 gboolean is_property_get;
5984 gboolean is_property_set;
5985 gboolean is_property_get_all;
5990 requested_object_path = g_dbus_message_get_path (message);
5991 sender = g_dbus_message_get_sender (message);
5992 interface_name = g_dbus_message_get_interface (message);
5993 member = g_dbus_message_get_member (message);
5994 signature = g_dbus_message_get_signature (message);
5995 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5997 is_property_get = FALSE;
5998 is_property_set = FALSE;
5999 is_property_get_all = FALSE;
6000 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6002 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6003 is_property_get = TRUE;
6004 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6005 is_property_set = TRUE;
6006 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6007 is_property_get_all = TRUE;
6012 requested_node = strrchr (requested_object_path, '/') + 1;
6014 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6016 /* We don't want to dispatch to unenumerated
6017 * nodes, so ensure that the child exists.
6022 children = es->vtable->enumerate (es->connection,
6027 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6028 g_strfreev (children);
6036 requested_node = NULL;
6039 /* get introspection data for the node */
6040 interfaces = es->vtable->introspect (es->connection,
6042 requested_object_path,
6046 if (interfaces == NULL)
6049 interface_info = NULL;
6050 for (n = 0; interfaces[n] != NULL; n++)
6052 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6053 interface_info = interfaces[n];
6056 /* dispatch the call if the user wants to handle it */
6057 if (interface_info != NULL)
6059 /* figure out where to dispatch the method call */
6060 interface_user_data = NULL;
6061 interface_vtable = es->vtable->dispatch (es->connection,
6066 &interface_user_data,
6068 if (interface_vtable == NULL)
6071 CONNECTION_LOCK (connection);
6072 handled = validate_and_maybe_schedule_method_call (es->connection,
6079 interface_user_data);
6080 CONNECTION_UNLOCK (connection);
6082 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6083 else if (is_property_get || is_property_set || is_property_get_all)
6085 if (is_property_get)
6086 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6087 else if (is_property_set)
6088 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6089 else if (is_property_get_all)
6090 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6092 g_assert_not_reached ();
6094 /* see if the object supports this interface at all */
6095 for (n = 0; interfaces[n] != NULL; n++)
6097 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6098 interface_info = interfaces[n];
6101 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6102 * claims it won't support the interface
6104 if (interface_info == NULL)
6106 GDBusMessage *reply;
6107 reply = g_dbus_message_new_method_error (message,
6108 "org.freedesktop.DBus.Error.InvalidArgs",
6109 _("No such interface `%s'"),
6111 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6112 g_object_unref (reply);
6117 /* figure out where to dispatch the property get/set/getall calls */
6118 interface_user_data = NULL;
6119 interface_vtable = es->vtable->dispatch (es->connection,
6124 &interface_user_data,
6126 if (interface_vtable == NULL)
6128 g_warning ("The subtree introspection function indicates that '%s' "
6129 "is a valid interface name, but calling the dispatch "
6130 "function on that interface gave us NULL", interface_name);
6134 if (is_property_get || is_property_set)
6136 CONNECTION_LOCK (connection);
6137 handled = validate_and_maybe_schedule_property_getset (es->connection,
6145 interface_user_data);
6146 CONNECTION_UNLOCK (connection);
6148 else if (is_property_get_all)
6150 CONNECTION_LOCK (connection);
6151 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6158 interface_user_data);
6159 CONNECTION_UNLOCK (connection);
6164 if (interfaces != NULL)
6166 for (n = 0; interfaces[n] != NULL; n++)
6167 g_dbus_interface_info_unref (interfaces[n]);
6168 g_free (interfaces);
6176 GDBusMessage *message;
6177 ExportedSubtree *es;
6178 } SubtreeDeferredData;
6181 subtree_deferred_data_free (SubtreeDeferredData *data)
6183 g_object_unref (data->message);
6187 /* called without lock held in the thread where the caller registered the subtree */
6189 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6191 SubtreeDeferredData *data = _data;
6196 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6197 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6198 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6199 handled = handle_subtree_introspect (data->es->connection,
6203 handled = handle_subtree_method_invocation (data->es->connection,
6209 CONNECTION_LOCK (data->es->connection);
6210 handled = handle_generic_unlocked (data->es->connection, data->message);
6211 CONNECTION_UNLOCK (data->es->connection);
6214 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6217 GDBusMessage *reply;
6218 reply = g_dbus_message_new_method_error (data->message,
6219 "org.freedesktop.DBus.Error.UnknownMethod",
6220 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6221 g_dbus_message_get_member (data->message),
6222 g_dbus_message_get_interface (data->message),
6223 g_dbus_message_get_signature (data->message));
6224 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6225 g_object_unref (reply);
6231 /* called in GDBusWorker thread with connection's lock held */
6233 subtree_message_func (GDBusConnection *connection,
6234 ExportedSubtree *es,
6235 GDBusMessage *message)
6237 GSource *idle_source;
6238 SubtreeDeferredData *data;
6240 data = g_new0 (SubtreeDeferredData, 1);
6241 data->message = g_object_ref (message);
6244 /* defer this call to an idle handler in the right thread */
6245 idle_source = g_idle_source_new ();
6246 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6247 g_source_set_callback (idle_source,
6248 process_subtree_vtable_message_in_idle_cb,
6250 (GDestroyNotify) subtree_deferred_data_free);
6251 g_source_attach (idle_source, es->context);
6252 g_source_unref (idle_source);
6254 /* since we own the entire subtree, handlers for objects not in the subtree have been
6255 * tried already by libdbus-1 - so we just need to ensure that we're always going
6256 * to reply to the message
6262 * g_dbus_connection_register_subtree:
6263 * @connection: A #GDBusConnection.
6264 * @object_path: The object path to register the subtree at.
6265 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6266 * @flags: Flags used to fine tune the behavior of the subtree.
6267 * @user_data: Data to pass to functions in @vtable.
6268 * @user_data_free_func: Function to call when the subtree is unregistered.
6269 * @error: Return location for error or %NULL.
6271 * Registers a whole subtree of <quote>dynamic</quote> objects.
6273 * The @enumerate and @introspection functions in @vtable are used to
6274 * convey, to remote callers, what nodes exist in the subtree rooted
6277 * When handling remote calls into any node in the subtree, first the
6278 * @enumerate function is used to check if the node exists. If the node exists
6279 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6280 * the @introspection function is used to check if the node supports the
6281 * requested method. If so, the @dispatch function is used to determine
6282 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6283 * #gpointer will be used to call into the interface vtable for processing
6286 * All calls into user-provided code will be invoked in the <link
6287 * linkend="g-main-context-push-thread-default">thread-default main
6288 * loop</link> of the thread you are calling this method from.
6290 * If an existing subtree is already registered at @object_path or
6291 * then @error is set to #G_IO_ERROR_EXISTS.
6293 * Note that it is valid to register regular objects (using
6294 * g_dbus_connection_register_object()) in a subtree registered with
6295 * g_dbus_connection_register_subtree() - if so, the subtree handler
6296 * is tried as the last resort. One way to think about a subtree
6297 * handler is to consider it a <quote>fallback handler</quote>
6298 * for object paths not registered via g_dbus_connection_register_object()
6299 * or other bindings.
6301 * Note that @vtable will be copied so you cannot change it after
6304 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6306 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6307 * that can be used with g_dbus_connection_unregister_subtree() .
6312 g_dbus_connection_register_subtree (GDBusConnection *connection,
6313 const gchar *object_path,
6314 const GDBusSubtreeVTable *vtable,
6315 GDBusSubtreeFlags flags,
6317 GDestroyNotify user_data_free_func,
6321 ExportedSubtree *es;
6323 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6324 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6325 g_return_val_if_fail (vtable != NULL, 0);
6326 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6327 g_return_val_if_fail (check_initialized (connection), 0);
6331 CONNECTION_LOCK (connection);
6333 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6339 _("A subtree is already exported for %s"),
6344 es = g_new0 (ExportedSubtree, 1);
6345 es->object_path = g_strdup (object_path);
6346 es->connection = connection;
6348 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6350 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6351 es->user_data = user_data;
6352 es->user_data_free_func = user_data_free_func;
6353 es->context = g_main_context_ref_thread_default ();
6355 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6356 g_hash_table_insert (connection->map_id_to_es,
6357 GUINT_TO_POINTER (es->id),
6363 CONNECTION_UNLOCK (connection);
6368 /* ---------------------------------------------------------------------------------------------------- */
6371 * g_dbus_connection_unregister_subtree:
6372 * @connection: A #GDBusConnection.
6373 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6375 * Unregisters a subtree.
6377 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6382 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6383 guint registration_id)
6385 ExportedSubtree *es;
6388 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6389 g_return_val_if_fail (check_initialized (connection), FALSE);
6393 CONNECTION_LOCK (connection);
6395 es = g_hash_table_lookup (connection->map_id_to_es,
6396 GUINT_TO_POINTER (registration_id));
6400 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6401 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6406 CONNECTION_UNLOCK (connection);
6411 /* ---------------------------------------------------------------------------------------------------- */
6413 /* may be called in any thread, with connection's lock held */
6415 handle_generic_ping_unlocked (GDBusConnection *connection,
6416 const gchar *object_path,
6417 GDBusMessage *message)
6419 GDBusMessage *reply;
6420 reply = g_dbus_message_new_method_reply (message);
6421 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6422 g_object_unref (reply);
6425 /* may be called in any thread, with connection's lock held */
6427 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6428 const gchar *object_path,
6429 GDBusMessage *message)
6431 GDBusMessage *reply;
6434 if (connection->machine_id == NULL)
6439 connection->machine_id = _g_dbus_get_machine_id (&error);
6440 if (connection->machine_id == NULL)
6442 reply = g_dbus_message_new_method_error_literal (message,
6443 "org.freedesktop.DBus.Error.Failed",
6445 g_error_free (error);
6451 reply = g_dbus_message_new_method_reply (message);
6452 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6454 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6455 g_object_unref (reply);
6458 /* may be called in any thread, with connection's lock held */
6460 handle_generic_introspect_unlocked (GDBusConnection *connection,
6461 const gchar *object_path,
6462 GDBusMessage *message)
6467 GDBusMessage *reply;
6469 /* first the header */
6470 s = g_string_new (NULL);
6471 introspect_append_header (s);
6473 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6474 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6475 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6476 g_strfreev (registered);
6477 g_string_append (s, "</node>\n");
6479 reply = g_dbus_message_new_method_reply (message);
6480 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6481 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6482 g_object_unref (reply);
6483 g_string_free (s, TRUE);
6486 /* may be called in any thread, with connection's lock held */
6488 handle_generic_unlocked (GDBusConnection *connection,
6489 GDBusMessage *message)
6492 const gchar *interface_name;
6493 const gchar *member;
6494 const gchar *signature;
6497 CONNECTION_ENSURE_LOCK (connection);
6501 interface_name = g_dbus_message_get_interface (message);
6502 member = g_dbus_message_get_member (message);
6503 signature = g_dbus_message_get_signature (message);
6504 path = g_dbus_message_get_path (message);
6506 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6507 g_strcmp0 (member, "Introspect") == 0 &&
6508 g_strcmp0 (signature, "") == 0)
6510 handle_generic_introspect_unlocked (connection, path, message);
6513 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6514 g_strcmp0 (member, "Ping") == 0 &&
6515 g_strcmp0 (signature, "") == 0)
6517 handle_generic_ping_unlocked (connection, path, message);
6520 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6521 g_strcmp0 (member, "GetMachineId") == 0 &&
6522 g_strcmp0 (signature, "") == 0)
6524 handle_generic_get_machine_id_unlocked (connection, path, message);
6531 /* ---------------------------------------------------------------------------------------------------- */
6533 /* called in GDBusWorker thread with connection's lock held */
6535 distribute_method_call (GDBusConnection *connection,
6536 GDBusMessage *message)
6538 GDBusMessage *reply;
6540 ExportedSubtree *es;
6541 const gchar *object_path;
6542 const gchar *interface_name;
6543 const gchar *member;
6545 gchar *subtree_path;
6548 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6550 interface_name = g_dbus_message_get_interface (message);
6551 member = g_dbus_message_get_member (message);
6552 path = g_dbus_message_get_path (message);
6553 subtree_path = g_strdup (path);
6554 needle = strrchr (subtree_path, '/');
6555 if (needle != NULL && needle != subtree_path)
6561 g_free (subtree_path);
6562 subtree_path = NULL;
6566 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6568 _g_dbus_debug_print_lock ();
6569 g_print ("========================================================================\n"
6570 "GDBus-debug:Incoming:\n"
6571 " <<<< METHOD INVOCATION %s.%s()\n"
6573 " invoked by name %s\n"
6575 interface_name, member,
6577 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6578 g_dbus_message_get_serial (message));
6579 _g_dbus_debug_print_unlock ();
6582 object_path = g_dbus_message_get_path (message);
6583 g_assert (object_path != NULL);
6585 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6588 if (obj_message_func (connection, eo, message))
6592 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6595 if (subtree_message_func (connection, es, message))
6599 if (subtree_path != NULL)
6601 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6604 if (subtree_message_func (connection, es, message))
6609 if (handle_generic_unlocked (connection, message))
6612 /* if we end up here, the message has not been not handled - so return an error saying this */
6613 reply = g_dbus_message_new_method_error (message,
6614 "org.freedesktop.DBus.Error.UnknownMethod",
6615 _("No such interface `%s' on object at path %s"),
6618 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6619 g_object_unref (reply);
6622 g_free (subtree_path);
6625 /* ---------------------------------------------------------------------------------------------------- */
6627 /* Called in any user thread, with the message_bus_lock held. */
6628 static GDBusConnection **
6629 message_bus_get_singleton (GBusType bus_type,
6632 GDBusConnection **ret;
6633 const gchar *starter_bus;
6639 case G_BUS_TYPE_SESSION:
6640 ret = &the_session_bus;
6643 case G_BUS_TYPE_SYSTEM:
6644 ret = &the_system_bus;
6647 case G_BUS_TYPE_STARTER:
6648 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6649 if (g_strcmp0 (starter_bus, "session") == 0)
6651 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6654 else if (g_strcmp0 (starter_bus, "system") == 0)
6656 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6661 if (starter_bus != NULL)
6665 G_IO_ERROR_INVALID_ARGUMENT,
6666 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6667 " - unknown value `%s'"),
6672 g_set_error_literal (error,
6674 G_IO_ERROR_INVALID_ARGUMENT,
6675 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6676 "variable is not set"));
6682 g_assert_not_reached ();
6690 /* Called in any user thread, without holding locks. */
6691 static GDBusConnection *
6692 get_uninitialized_connection (GBusType bus_type,
6693 GCancellable *cancellable,
6696 GDBusConnection **singleton;
6697 GDBusConnection *ret;
6701 G_LOCK (message_bus_lock);
6702 singleton = message_bus_get_singleton (bus_type, error);
6703 if (singleton == NULL)
6706 if (*singleton == NULL)
6709 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6710 if (address == NULL)
6712 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6714 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6715 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6716 "exit-on-close", TRUE,
6722 ret = g_object_ref (*singleton);
6725 g_assert (ret != NULL);
6728 G_UNLOCK (message_bus_lock);
6734 * @bus_type: A #GBusType.
6735 * @cancellable: A #GCancellable or %NULL.
6736 * @error: Return location for error or %NULL.
6738 * Synchronously connects to the message bus specified by @bus_type.
6739 * Note that the returned object may shared with other callers,
6740 * e.g. if two separate parts of a process calls this function with
6741 * the same @bus_type, they will share the same object.
6743 * This is a synchronous failable function. See g_bus_get() and
6744 * g_bus_get_finish() for the asynchronous version.
6746 * The returned object is a singleton, that is, shared with other
6747 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6748 * event that you need a private message bus connection, use
6749 * g_dbus_address_get_for_bus_sync() and
6750 * g_dbus_connection_new_for_address().
6752 * Note that the returned #GDBusConnection object will (usually) have
6753 * the #GDBusConnection:exit-on-close property set to %TRUE.
6755 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6760 g_bus_get_sync (GBusType bus_type,
6761 GCancellable *cancellable,
6764 GDBusConnection *connection;
6766 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6768 connection = get_uninitialized_connection (bus_type, cancellable, error);
6769 if (connection == NULL)
6772 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6774 g_object_unref (connection);
6783 bus_get_async_initable_cb (GObject *source_object,
6787 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6791 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6795 g_assert (error != NULL);
6796 g_simple_async_result_take_error (simple, error);
6797 g_object_unref (source_object);
6801 g_simple_async_result_set_op_res_gpointer (simple,
6805 g_simple_async_result_complete_in_idle (simple);
6806 g_object_unref (simple);
6811 * @bus_type: A #GBusType.
6812 * @cancellable: A #GCancellable or %NULL.
6813 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6814 * @user_data: The data to pass to @callback.
6816 * Asynchronously connects to the message bus specified by @bus_type.
6818 * When the operation is finished, @callback will be invoked. You can
6819 * then call g_bus_get_finish() to get the result of the operation.
6821 * This is a asynchronous failable function. See g_bus_get_sync() for
6822 * the synchronous version.
6827 g_bus_get (GBusType bus_type,
6828 GCancellable *cancellable,
6829 GAsyncReadyCallback callback,
6832 GDBusConnection *connection;
6833 GSimpleAsyncResult *simple;
6836 simple = g_simple_async_result_new (NULL,
6842 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6843 if (connection == NULL)
6845 g_assert (error != NULL);
6846 g_simple_async_result_take_error (simple, error);
6847 g_simple_async_result_complete_in_idle (simple);
6848 g_object_unref (simple);
6852 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6855 bus_get_async_initable_cb,
6862 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6863 * @error: Return location for error or %NULL.
6865 * Finishes an operation started with g_bus_get().
6867 * The returned object is a singleton, that is, shared with other
6868 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6869 * event that you need a private message bus connection, use
6870 * g_dbus_address_get_for_bus_sync() and
6871 * g_dbus_connection_new_for_address().
6873 * Note that the returned #GDBusConnection object will (usually) have
6874 * the #GDBusConnection:exit-on-close property set to %TRUE.
6876 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6881 g_bus_get_finish (GAsyncResult *res,
6884 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6886 GDBusConnection *ret;
6888 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6890 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6894 if (g_simple_async_result_propagate_error (simple, error))
6897 object = g_simple_async_result_get_op_res_gpointer (simple);
6898 g_assert (object != NULL);
6899 ret = g_object_ref (G_DBUS_CONNECTION (object));
6905 /* ---------------------------------------------------------------------------------------------------- */