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
338 * The #GDBusConnection structure contains only private data and
339 * should only be accessed using the provided API.
343 struct _GDBusConnection
346 GObject parent_instance;
348 /* ------------------------------------------------------------------------ */
349 /* -- General object state ------------------------------------------------ */
350 /* ------------------------------------------------------------------------ */
352 /* object-wide lock */
355 /* A lock used in the init() method of the GInitable interface - see comments
356 * in initable_init() for why a separate lock is needed
360 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
361 * someone calls org.freedesktop.DBus.GetMachineId()
365 /* The underlying stream used for communication
366 * Read-only after initable_init(), so it may be read if you either
367 * hold @init_lock or check for initialization first.
371 /* The object used for authentication (if any).
372 * Read-only after initable_init(), so it may be read if you either
373 * hold @init_lock or check for initialization first.
377 /* Set to TRUE if the connection has been closed */
380 /* Last serial used */
383 /* The object used to send/receive messages.
384 * Read-only after initable_init(), so it may be read if you either
385 * hold @init_lock or check for initialization first.
389 /* If connected to a message bus, this contains the unique name assigned to
390 * us by the bus (e.g. ":1.42").
391 * Read-only after initable_init(), so it may be read if you either
392 * hold @init_lock or check for initialization first.
394 gchar *bus_unique_name;
396 /* The GUID returned by the other side if we authenticed as a client or
397 * the GUID to use if authenticating as a server.
398 * Read-only after initable_init(), so it may be read if you either
399 * hold @init_lock or check for initialization first.
403 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
404 * Inspect @initialization_error to see whether it succeeded or failed.
406 volatile gint atomic_flags;
408 /* If the connection could not be established during initable_init(),
409 * this GError will be set.
410 * Read-only after initable_init(), so it may be read if you either
411 * hold @init_lock or check for initialization first.
413 GError *initialization_error;
415 /* The result of g_main_context_ref_thread_default() when the object
416 * was created (the GObject _init() function) - this is used for delivery
417 * of the :closed GObject signal.
419 GMainContext *main_context_at_construction;
421 /* construct properties */
423 GDBusConnectionFlags flags;
425 /* Map used for managing method replies */
426 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
428 /* Maps used for managing signal subscription */
429 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
430 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
431 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
433 /* Maps used for managing exported objects and subtrees */
434 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
435 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
436 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
437 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
439 /* Structure used for message filters */
442 /* Whether to exit on close */
443 gboolean exit_on_close;
445 /* Capabilities negotiated during authentication
446 * Read-only after initable_init(), so it may be read without holding a
447 * lock, if you check for initialization first.
449 GDBusCapabilityFlags capabilities;
451 GDBusAuthObserver *authentication_observer;
453 /* Read-only after initable_init(), so it may be read if you either
454 * hold @init_lock or check for initialization first.
456 GCredentials *credentials;
458 /* set to TRUE when finalizing */
462 typedef struct ExportedObject ExportedObject;
463 static void exported_object_free (ExportedObject *eo);
465 typedef struct ExportedSubtree ExportedSubtree;
466 static void exported_subtree_free (ExportedSubtree *es);
484 PROP_CAPABILITY_FLAGS,
485 PROP_AUTHENTICATION_OBSERVER,
488 static void distribute_signals (GDBusConnection *connection,
489 GDBusMessage *message);
491 static void distribute_method_call (GDBusConnection *connection,
492 GDBusMessage *message);
494 static gboolean handle_generic_unlocked (GDBusConnection *connection,
495 GDBusMessage *message);
498 static void purge_all_signal_subscriptions (GDBusConnection *connection);
499 static void purge_all_filters (GDBusConnection *connection);
501 #define _G_ENSURE_LOCK(name) do { \
502 if (G_UNLIKELY (G_TRYLOCK(name))) \
504 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
505 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
509 static guint signals[LAST_SIGNAL] = { 0 };
511 static void initable_iface_init (GInitableIface *initable_iface);
512 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
514 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
515 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
516 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
520 * Check that all members of @connection that can only be accessed after
521 * the connection is initialized can safely be accessed. If not,
522 * log a critical warning. This function is a memory barrier.
524 * Returns: %TRUE if initialized
527 check_initialized (GDBusConnection *connection)
529 /* The access to @atomic_flags isn't conditional, so that this function
530 * provides a memory barrier for thread-safety even if checks are disabled.
531 * (If you don't want this stricter guarantee, you can call
532 * g_return_if_fail (check_initialized (c)).)
534 * This isn't strictly necessary now that we've decided use of an
535 * uninitialized GDBusConnection is undefined behaviour, but it seems
536 * better to be as deterministic as is feasible.
538 * (Anything that could suffer a crash from seeing undefined values
539 * must have a race condition - thread A initializes the connection while
540 * thread B calls a method without initialization, hoping that thread A will
541 * win the race - so its behaviour is undefined anyway.)
543 gint flags = g_atomic_int_get (&connection->atomic_flags);
545 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
547 /* We can safely access this, due to the memory barrier above */
548 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
553 static GHashTable *alive_connections = NULL;
556 g_dbus_connection_dispose (GObject *object)
558 GDBusConnection *connection = G_DBUS_CONNECTION (object);
560 G_LOCK (message_bus_lock);
561 if (connection == the_session_bus)
563 the_session_bus = NULL;
565 else if (connection == the_system_bus)
567 the_system_bus = NULL;
569 CONNECTION_LOCK (connection);
570 if (connection->worker != NULL)
572 _g_dbus_worker_stop (connection->worker);
573 connection->worker = NULL;
574 if (alive_connections != NULL)
575 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
579 if (alive_connections != NULL)
580 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
582 CONNECTION_UNLOCK (connection);
583 G_UNLOCK (message_bus_lock);
585 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
586 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
590 g_dbus_connection_finalize (GObject *object)
592 GDBusConnection *connection = G_DBUS_CONNECTION (object);
594 connection->finalizing = TRUE;
596 purge_all_signal_subscriptions (connection);
598 purge_all_filters (connection);
599 g_ptr_array_unref (connection->filters);
601 if (connection->authentication_observer != NULL)
602 g_object_unref (connection->authentication_observer);
604 if (connection->auth != NULL)
605 g_object_unref (connection->auth);
607 if (connection->credentials)
608 g_object_unref (connection->credentials);
610 if (connection->stream != NULL)
612 g_object_unref (connection->stream);
613 connection->stream = NULL;
616 g_free (connection->address);
618 g_free (connection->guid);
619 g_free (connection->bus_unique_name);
621 if (connection->initialization_error != NULL)
622 g_error_free (connection->initialization_error);
624 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
626 g_hash_table_unref (connection->map_rule_to_signal_data);
627 g_hash_table_unref (connection->map_id_to_signal_data);
628 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
630 g_hash_table_unref (connection->map_id_to_ei);
631 g_hash_table_unref (connection->map_object_path_to_eo);
632 g_hash_table_unref (connection->map_id_to_es);
633 g_hash_table_unref (connection->map_object_path_to_es);
635 g_main_context_unref (connection->main_context_at_construction);
637 g_free (connection->machine_id);
639 g_mutex_clear (&connection->init_lock);
640 g_mutex_clear (&connection->lock);
642 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
646 g_dbus_connection_get_property (GObject *object,
651 GDBusConnection *connection = G_DBUS_CONNECTION (object);
656 g_value_set_object (value, g_dbus_connection_get_stream (connection));
660 g_value_set_string (value, g_dbus_connection_get_guid (connection));
663 case PROP_UNIQUE_NAME:
664 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
668 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
671 case PROP_EXIT_ON_CLOSE:
672 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
675 case PROP_CAPABILITY_FLAGS:
676 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
680 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
686 g_dbus_connection_set_property (GObject *object,
691 GDBusConnection *connection = G_DBUS_CONNECTION (object);
696 connection->stream = g_value_dup_object (value);
700 connection->guid = g_value_dup_string (value);
704 connection->address = g_value_dup_string (value);
708 connection->flags = g_value_get_flags (value);
711 case PROP_EXIT_ON_CLOSE:
712 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
715 case PROP_AUTHENTICATION_OBSERVER:
716 connection->authentication_observer = g_value_dup_object (value);
720 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
726 g_dbus_connection_real_closed (GDBusConnection *connection,
727 gboolean remote_peer_vanished,
730 gint flags = g_atomic_int_get (&connection->atomic_flags);
732 /* Because atomic int access is a memory barrier, we can safely read
733 * initialization_error without a lock, as long as we do it afterwards.
735 if (remote_peer_vanished && connection->exit_on_close &&
736 (flags & FLAG_INITIALIZED) != 0 &&
737 connection->initialization_error == NULL)
741 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
744 g_quark_to_string (error->domain), error->code);
748 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
755 g_dbus_connection_class_init (GDBusConnectionClass *klass)
757 GObjectClass *gobject_class;
759 gobject_class = G_OBJECT_CLASS (klass);
761 gobject_class->finalize = g_dbus_connection_finalize;
762 gobject_class->dispose = g_dbus_connection_dispose;
763 gobject_class->set_property = g_dbus_connection_set_property;
764 gobject_class->get_property = g_dbus_connection_get_property;
766 klass->closed = g_dbus_connection_real_closed;
769 * GDBusConnection:stream:
771 * The underlying #GIOStream used for I/O.
773 * If this is passed on construction and is a #GSocketConnection,
774 * then the corresponding #GSocket will be put into non-blocking mode.
776 * While the #GDBusConnection is active, it will interact with this
777 * stream from a worker thread, so it is not safe to interact with
778 * the stream directly.
782 g_object_class_install_property (gobject_class,
784 g_param_spec_object ("stream",
786 P_("The underlying streams used for I/O"),
790 G_PARAM_CONSTRUCT_ONLY |
791 G_PARAM_STATIC_NAME |
792 G_PARAM_STATIC_BLURB |
793 G_PARAM_STATIC_NICK));
796 * GDBusConnection:address:
798 * A D-Bus address specifying potential endpoints that can be used
799 * when establishing the connection.
803 g_object_class_install_property (gobject_class,
805 g_param_spec_string ("address",
807 P_("D-Bus address specifying potential socket endpoints"),
810 G_PARAM_CONSTRUCT_ONLY |
811 G_PARAM_STATIC_NAME |
812 G_PARAM_STATIC_BLURB |
813 G_PARAM_STATIC_NICK));
816 * GDBusConnection:flags:
818 * Flags from the #GDBusConnectionFlags enumeration.
822 g_object_class_install_property (gobject_class,
824 g_param_spec_flags ("flags",
827 G_TYPE_DBUS_CONNECTION_FLAGS,
828 G_DBUS_CONNECTION_FLAGS_NONE,
830 G_PARAM_CONSTRUCT_ONLY |
831 G_PARAM_STATIC_NAME |
832 G_PARAM_STATIC_BLURB |
833 G_PARAM_STATIC_NICK));
836 * GDBusConnection:guid:
838 * The GUID of the peer performing the role of server when
841 * If you are constructing a #GDBusConnection and pass
842 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
843 * #GDBusConnection:flags property then you MUST also set this
844 * property to a valid guid.
846 * If you are constructing a #GDBusConnection and pass
847 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
848 * #GDBusConnection:flags property you will be able to read the GUID
849 * of the other peer here after the connection has been successfully
854 g_object_class_install_property (gobject_class,
856 g_param_spec_string ("guid",
858 P_("GUID of the server peer"),
862 G_PARAM_CONSTRUCT_ONLY |
863 G_PARAM_STATIC_NAME |
864 G_PARAM_STATIC_BLURB |
865 G_PARAM_STATIC_NICK));
868 * GDBusConnection:unique-name:
870 * The unique name as assigned by the message bus or %NULL if the
871 * connection is not open or not a message bus connection.
875 g_object_class_install_property (gobject_class,
877 g_param_spec_string ("unique-name",
879 P_("Unique name of bus connection"),
882 G_PARAM_STATIC_NAME |
883 G_PARAM_STATIC_BLURB |
884 G_PARAM_STATIC_NICK));
887 * GDBusConnection:closed:
889 * A boolean specifying whether the connection has been closed.
893 g_object_class_install_property (gobject_class,
895 g_param_spec_boolean ("closed",
897 P_("Whether the connection is closed"),
900 G_PARAM_STATIC_NAME |
901 G_PARAM_STATIC_BLURB |
902 G_PARAM_STATIC_NICK));
905 * GDBusConnection:exit-on-close:
907 * A boolean specifying whether the process will be terminated (by
908 * calling <literal>raise(SIGTERM)</literal>) if the connection
909 * is closed by the remote peer.
913 g_object_class_install_property (gobject_class,
915 g_param_spec_boolean ("exit-on-close",
917 P_("Whether the process is terminated when the connection is closed"),
921 G_PARAM_STATIC_NAME |
922 G_PARAM_STATIC_BLURB |
923 G_PARAM_STATIC_NICK));
926 * GDBusConnection:capabilities:
928 * Flags from the #GDBusCapabilityFlags enumeration
929 * representing connection features negotiated with the other peer.
933 g_object_class_install_property (gobject_class,
934 PROP_CAPABILITY_FLAGS,
935 g_param_spec_flags ("capabilities",
938 G_TYPE_DBUS_CAPABILITY_FLAGS,
939 G_DBUS_CAPABILITY_FLAGS_NONE,
941 G_PARAM_STATIC_NAME |
942 G_PARAM_STATIC_BLURB |
943 G_PARAM_STATIC_NICK));
946 * GDBusConnection:authentication-observer:
948 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
952 g_object_class_install_property (gobject_class,
953 PROP_AUTHENTICATION_OBSERVER,
954 g_param_spec_object ("authentication-observer",
955 P_("Authentication Observer"),
956 P_("Object used to assist in the authentication process"),
957 G_TYPE_DBUS_AUTH_OBSERVER,
959 G_PARAM_CONSTRUCT_ONLY |
960 G_PARAM_STATIC_NAME |
961 G_PARAM_STATIC_BLURB |
962 G_PARAM_STATIC_NICK));
965 * GDBusConnection::closed:
966 * @connection: The #GDBusConnection emitting the signal.
967 * @remote_peer_vanished: %TRUE if @connection is closed because the
968 * remote peer closed its end of the connection.
969 * @error: A #GError with more details about the event or %NULL.
971 * Emitted when the connection is closed.
973 * The cause of this event can be
976 * If g_dbus_connection_close() is called. In this case
977 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
980 * If the remote peer closes the connection. In this case
981 * @remote_peer_vanished is set to %TRUE and @error is set.
984 * If the remote peer sends invalid or malformed data. In this
985 * case @remote_peer_vanished is set to %FALSE and @error
990 * Upon receiving this signal, you should give up your reference to
991 * @connection. You are guaranteed that this signal is emitted only
996 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
997 G_TYPE_DBUS_CONNECTION,
999 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1010 g_dbus_connection_init (GDBusConnection *connection)
1012 g_mutex_init (&connection->lock);
1013 g_mutex_init (&connection->init_lock);
1015 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1017 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1019 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1021 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1024 (GDestroyNotify) g_ptr_array_unref);
1026 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1029 (GDestroyNotify) exported_object_free);
1031 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1034 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1037 (GDestroyNotify) exported_subtree_free);
1039 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1042 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1044 connection->filters = g_ptr_array_new ();
1048 * g_dbus_connection_get_stream:
1049 * @connection: a #GDBusConnection
1051 * Gets the underlying stream used for IO.
1053 * While the #GDBusConnection is active, it will interact with this
1054 * stream from a worker thread, so it is not safe to interact with
1055 * the stream directly.
1057 * Returns: (transfer none): the stream used for IO
1062 g_dbus_connection_get_stream (GDBusConnection *connection)
1064 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1066 /* do not use g_return_val_if_fail(), we want the memory barrier */
1067 if (!check_initialized (connection))
1070 return connection->stream;
1074 * g_dbus_connection_start_message_processing:
1075 * @connection: A #GDBusConnection.
1077 * If @connection was created with
1078 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1079 * starts processing messages. Does nothing on if @connection wasn't
1080 * created with this flag or if the method has already been called.
1085 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1087 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1089 /* do not use g_return_val_if_fail(), we want the memory barrier */
1090 if (!check_initialized (connection))
1093 g_assert (connection->worker != NULL);
1094 _g_dbus_worker_unfreeze (connection->worker);
1098 * g_dbus_connection_is_closed:
1099 * @connection: A #GDBusConnection.
1101 * Gets whether @connection is closed.
1103 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1108 g_dbus_connection_is_closed (GDBusConnection *connection)
1110 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1111 return connection->closed;
1115 * g_dbus_connection_get_capabilities:
1116 * @connection: A #GDBusConnection.
1118 * Gets the capabilities negotiated with the remote peer
1120 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1124 GDBusCapabilityFlags
1125 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1127 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1129 /* do not use g_return_val_if_fail(), we want the memory barrier */
1130 if (!check_initialized (connection))
1131 return G_DBUS_CAPABILITY_FLAGS_NONE;
1133 return connection->capabilities;
1136 /* ---------------------------------------------------------------------------------------------------- */
1139 flush_in_thread_func (GSimpleAsyncResult *res,
1141 GCancellable *cancellable)
1146 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1149 g_simple_async_result_take_error (res, error);
1153 * g_dbus_connection_flush:
1154 * @connection: A #GDBusConnection.
1155 * @cancellable: A #GCancellable or %NULL.
1156 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1157 * satisfied or %NULL if you don't care about the result.
1158 * @user_data: The data to pass to @callback.
1160 * Asynchronously flushes @connection, that is, writes all queued
1161 * outgoing message to the transport and then flushes the transport
1162 * (using g_output_stream_flush_async()). This is useful in programs
1163 * that wants to emit a D-Bus signal and then exit
1164 * immediately. Without flushing the connection, there is no guarantee
1165 * that the message has been sent to the networking buffers in the OS
1168 * This is an asynchronous method. When the operation is finished,
1169 * @callback will be invoked in the <link
1170 * linkend="g-main-context-push-thread-default">thread-default main
1171 * loop</link> of the thread you are calling this method from. You can
1172 * then call g_dbus_connection_flush_finish() to get the result of the
1173 * operation. See g_dbus_connection_flush_sync() for the synchronous
1179 g_dbus_connection_flush (GDBusConnection *connection,
1180 GCancellable *cancellable,
1181 GAsyncReadyCallback callback,
1184 GSimpleAsyncResult *simple;
1186 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1188 simple = g_simple_async_result_new (G_OBJECT (connection),
1191 g_dbus_connection_flush);
1192 g_simple_async_result_run_in_thread (simple,
1193 flush_in_thread_func,
1196 g_object_unref (simple);
1200 * g_dbus_connection_flush_finish:
1201 * @connection: A #GDBusConnection.
1202 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1203 * @error: Return location for error or %NULL.
1205 * Finishes an operation started with g_dbus_connection_flush().
1207 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1212 g_dbus_connection_flush_finish (GDBusConnection *connection,
1216 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1221 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1222 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1223 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1225 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1227 if (g_simple_async_result_propagate_error (simple, error))
1237 * g_dbus_connection_flush_sync:
1238 * @connection: A #GDBusConnection.
1239 * @cancellable: A #GCancellable or %NULL.
1240 * @error: Return location for error or %NULL.
1242 * Synchronously flushes @connection. The calling thread is blocked
1243 * until this is done. See g_dbus_connection_flush() for the
1244 * asynchronous version of this method and more details about what it
1247 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1252 g_dbus_connection_flush_sync (GDBusConnection *connection,
1253 GCancellable *cancellable,
1258 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1259 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1263 /* do not use g_return_val_if_fail(), we want the memory barrier */
1264 if (!check_initialized (connection))
1267 g_assert (connection->worker != NULL);
1269 if (connection->closed)
1271 g_set_error_literal (error,
1274 _("The connection is closed"));
1278 ret = _g_dbus_worker_flush_sync (connection->worker,
1286 /* ---------------------------------------------------------------------------------------------------- */
1290 GDBusConnection *connection;
1292 gboolean remote_peer_vanished;
1296 emit_closed_data_free (EmitClosedData *data)
1298 g_object_unref (data->connection);
1299 if (data->error != NULL)
1300 g_error_free (data->error);
1305 emit_closed_in_idle (gpointer user_data)
1307 EmitClosedData *data = user_data;
1310 g_object_notify (G_OBJECT (data->connection), "closed");
1311 g_signal_emit (data->connection,
1312 signals[CLOSED_SIGNAL],
1314 data->remote_peer_vanished,
1320 /* Can be called from any thread, must hold lock */
1322 set_closed_unlocked (GDBusConnection *connection,
1323 gboolean remote_peer_vanished,
1326 GSource *idle_source;
1327 EmitClosedData *data;
1329 CONNECTION_ENSURE_LOCK (connection);
1331 g_assert (!connection->closed);
1333 connection->closed = TRUE;
1335 data = g_new0 (EmitClosedData, 1);
1336 data->connection = g_object_ref (connection);
1337 data->remote_peer_vanished = remote_peer_vanished;
1338 data->error = error != NULL ? g_error_copy (error) : NULL;
1340 idle_source = g_idle_source_new ();
1341 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1342 g_source_set_callback (idle_source,
1343 emit_closed_in_idle,
1345 (GDestroyNotify) emit_closed_data_free);
1346 g_source_attach (idle_source, connection->main_context_at_construction);
1347 g_source_unref (idle_source);
1350 /* ---------------------------------------------------------------------------------------------------- */
1353 * g_dbus_connection_close:
1354 * @connection: A #GDBusConnection.
1355 * @cancellable: A #GCancellable or %NULL.
1356 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1357 * satisfied or %NULL if you don't care about the result.
1358 * @user_data: The data to pass to @callback.
1360 * Closes @connection. Note that this never causes the process to
1361 * exit (this might only happen if the other end of a shared message
1362 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1364 * Once the connection is closed, operations such as sending a message
1365 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1366 * will not automatically flush the connection so queued messages may
1367 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1369 * If @connection is already closed, this method fails with
1370 * %G_IO_ERROR_CLOSED.
1372 * When @connection has been closed, the #GDBusConnection::closed
1373 * signal is emitted in the <link
1374 * linkend="g-main-context-push-thread-default">thread-default main
1375 * loop</link> of the thread that @connection was constructed in.
1377 * This is an asynchronous method. When the operation is finished,
1378 * @callback will be invoked in the <link
1379 * linkend="g-main-context-push-thread-default">thread-default main
1380 * loop</link> of the thread you are calling this method from. You can
1381 * then call g_dbus_connection_close_finish() to get the result of the
1382 * operation. See g_dbus_connection_close_sync() for the synchronous
1388 g_dbus_connection_close (GDBusConnection *connection,
1389 GCancellable *cancellable,
1390 GAsyncReadyCallback callback,
1393 GSimpleAsyncResult *simple;
1395 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1397 /* do not use g_return_val_if_fail(), we want the memory barrier */
1398 if (!check_initialized (connection))
1401 g_assert (connection->worker != NULL);
1403 simple = g_simple_async_result_new (G_OBJECT (connection),
1406 g_dbus_connection_close);
1407 _g_dbus_worker_close (connection->worker, cancellable, simple);
1408 g_object_unref (simple);
1412 * g_dbus_connection_close_finish:
1413 * @connection: A #GDBusConnection.
1414 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1415 * @error: Return location for error or %NULL.
1417 * Finishes an operation started with g_dbus_connection_close().
1419 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1424 g_dbus_connection_close_finish (GDBusConnection *connection,
1428 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1433 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1434 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1435 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1437 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1439 if (g_simple_async_result_propagate_error (simple, error))
1450 GAsyncResult *result;
1454 sync_close_cb (GObject *source_object,
1458 SyncCloseData *data = user_data;
1460 data->result = g_object_ref (res);
1461 g_main_loop_quit (data->loop);
1465 * g_dbus_connection_close_sync:
1466 * @connection: A #GDBusConnection.
1467 * @cancellable: A #GCancellable or %NULL.
1468 * @error: Return location for error or %NULL.
1470 * Synchronously closees @connection. The calling thread is blocked
1471 * until this is done. See g_dbus_connection_close() for the
1472 * asynchronous version of this method and more details about what it
1475 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1480 g_dbus_connection_close_sync (GDBusConnection *connection,
1481 GCancellable *cancellable,
1486 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1487 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1491 CONNECTION_LOCK (connection);
1492 if (!connection->closed)
1494 GMainContext *context;
1497 context = g_main_context_new ();
1498 g_main_context_push_thread_default (context);
1499 data.loop = g_main_loop_new (context, TRUE);
1502 CONNECTION_UNLOCK (connection);
1503 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1504 g_main_loop_run (data.loop);
1505 ret = g_dbus_connection_close_finish (connection, data.result, error);
1506 CONNECTION_LOCK (connection);
1508 g_object_unref (data.result);
1509 g_main_loop_unref (data.loop);
1510 g_main_context_pop_thread_default (context);
1511 g_main_context_unref (context);
1515 g_set_error_literal (error,
1518 _("The connection is closed"));
1520 CONNECTION_UNLOCK (connection);
1525 /* ---------------------------------------------------------------------------------------------------- */
1528 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1529 GDBusMessage *message,
1530 GDBusSendMessageFlags flags,
1531 volatile guint32 *out_serial,
1536 guint32 serial_to_use;
1539 CONNECTION_ENSURE_LOCK (connection);
1541 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1542 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1544 /* TODO: check all necessary headers are present */
1549 if (out_serial != NULL)
1552 /* If we're in initable_init(), don't check for being initialized, to avoid
1553 * chicken-and-egg problems. initable_init() is responsible for setting up
1554 * our prerequisites (mainly connection->worker), and only calling us
1555 * from its own thread (so no memory barrier is needed).
1557 * In the case where we're not initializing, do not use
1558 * g_return_val_if_fail() - we want the memory barrier.
1560 if ((flags & SEND_MESSAGE_FLAGS_INITIALIZING) == 0 &&
1561 !check_initialized (connection))
1564 if (connection->closed)
1566 g_set_error_literal (error,
1569 _("The connection is closed"));
1573 blob = g_dbus_message_to_blob (message,
1575 connection->capabilities,
1580 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1581 serial_to_use = g_dbus_message_get_serial (message);
1583 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1588 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1591 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1594 g_assert_not_reached ();
1599 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1600 blob_size, serial_to_use, connection);
1601 g_printerr ("----\n");
1602 hexdump (blob, blob_size);
1603 g_printerr ("----\n");
1606 /* TODO: use connection->auth to encode the blob */
1608 if (out_serial != NULL)
1609 *out_serial = serial_to_use;
1611 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1612 g_dbus_message_set_serial (message, serial_to_use);
1614 g_dbus_message_lock (message);
1615 _g_dbus_worker_send_message (connection->worker,
1619 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1630 * g_dbus_connection_send_message:
1631 * @connection: A #GDBusConnection.
1632 * @message: A #GDBusMessage
1633 * @flags: Flags affecting how the message is sent.
1634 * @out_serial: (out) (allow-none): Return location for serial number assigned
1635 * to @message when sending it or %NULL.
1636 * @error: Return location for error or %NULL.
1638 * Asynchronously sends @message to the peer represented by @connection.
1640 * Unless @flags contain the
1641 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1642 * will be assigned by @connection and set on @message via
1643 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1644 * serial number used will be written to this location prior to
1645 * submitting the message to the underlying transport.
1647 * If @connection is closed then the operation will fail with
1648 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1649 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1651 * See <xref linkend="gdbus-server"/> and <xref
1652 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1653 * low-level API to send and receive UNIX file descriptors.
1655 * Note that @message must be unlocked, unless @flags contain the
1656 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1658 * Returns: %TRUE if the message was well-formed and queued for
1659 * transmission, %FALSE if @error is set.
1664 g_dbus_connection_send_message (GDBusConnection *connection,
1665 GDBusMessage *message,
1666 GDBusSendMessageFlags flags,
1667 volatile guint32 *out_serial,
1672 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1673 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1674 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1675 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1677 CONNECTION_LOCK (connection);
1678 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1679 CONNECTION_UNLOCK (connection);
1683 /* ---------------------------------------------------------------------------------------------------- */
1687 volatile gint ref_count;
1688 GDBusConnection *connection;
1690 GSimpleAsyncResult *simple;
1692 GMainContext *main_context;
1694 GCancellable *cancellable;
1696 gulong cancellable_handler_id;
1698 GSource *timeout_source;
1703 static SendMessageData *
1704 send_message_data_ref (SendMessageData *data)
1706 g_atomic_int_inc (&data->ref_count);
1711 send_message_data_unref (SendMessageData *data)
1713 if (g_atomic_int_dec_and_test (&data->ref_count))
1715 g_assert (data->timeout_source == NULL);
1716 g_assert (data->simple == NULL);
1717 g_assert (data->cancellable_handler_id == 0);
1718 g_object_unref (data->connection);
1719 if (data->cancellable != NULL)
1720 g_object_unref (data->cancellable);
1721 g_main_context_unref (data->main_context);
1726 /* ---------------------------------------------------------------------------------------------------- */
1728 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1730 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1732 CONNECTION_ENSURE_LOCK (data->connection);
1734 g_assert (!data->delivered);
1736 data->delivered = TRUE;
1738 g_simple_async_result_complete_in_idle (data->simple);
1739 g_object_unref (data->simple);
1740 data->simple = NULL;
1742 if (data->timeout_source != NULL)
1744 g_source_destroy (data->timeout_source);
1745 data->timeout_source = NULL;
1747 if (data->cancellable_handler_id > 0)
1749 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1750 data->cancellable_handler_id = 0;
1755 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1756 GUINT_TO_POINTER (data->serial)));
1759 send_message_data_unref (data);
1762 /* ---------------------------------------------------------------------------------------------------- */
1764 /* must hold lock */
1766 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1767 GDBusMessage *reply)
1769 if (data->delivered)
1772 g_simple_async_result_set_op_res_gpointer (data->simple,
1773 g_object_ref (reply),
1776 send_message_with_reply_deliver (data, TRUE);
1782 /* ---------------------------------------------------------------------------------------------------- */
1785 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1787 SendMessageData *data = user_data;
1789 CONNECTION_LOCK (data->connection);
1790 if (data->delivered)
1793 g_simple_async_result_set_error (data->simple,
1795 G_IO_ERROR_CANCELLED,
1796 _("Operation was cancelled"));
1798 send_message_with_reply_deliver (data, TRUE);
1801 CONNECTION_UNLOCK (data->connection);
1805 /* Can be called from any thread with or without lock held */
1807 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1810 SendMessageData *data = user_data;
1811 GSource *idle_source;
1813 /* postpone cancellation to idle handler since we may be called directly
1814 * via g_cancellable_connect() (e.g. holding lock)
1816 idle_source = g_idle_source_new ();
1817 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1818 g_source_set_callback (idle_source,
1819 send_message_with_reply_cancelled_idle_cb,
1820 send_message_data_ref (data),
1821 (GDestroyNotify) send_message_data_unref);
1822 g_source_attach (idle_source, data->main_context);
1823 g_source_unref (idle_source);
1826 /* ---------------------------------------------------------------------------------------------------- */
1829 send_message_with_reply_timeout_cb (gpointer user_data)
1831 SendMessageData *data = user_data;
1833 CONNECTION_LOCK (data->connection);
1834 if (data->delivered)
1837 g_simple_async_result_set_error (data->simple,
1839 G_IO_ERROR_TIMED_OUT,
1840 _("Timeout was reached"));
1842 send_message_with_reply_deliver (data, TRUE);
1845 CONNECTION_UNLOCK (data->connection);
1850 /* ---------------------------------------------------------------------------------------------------- */
1853 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1854 GDBusMessage *message,
1855 GDBusSendMessageFlags flags,
1857 volatile guint32 *out_serial,
1858 GCancellable *cancellable,
1859 GAsyncReadyCallback callback,
1862 GSimpleAsyncResult *simple;
1863 SendMessageData *data;
1865 volatile guint32 serial;
1869 if (out_serial == NULL)
1870 out_serial = &serial;
1872 if (timeout_msec == -1)
1873 timeout_msec = 25 * 1000;
1875 simple = g_simple_async_result_new (G_OBJECT (connection),
1878 g_dbus_connection_send_message_with_reply);
1880 if (g_cancellable_is_cancelled (cancellable))
1882 g_simple_async_result_set_error (simple,
1884 G_IO_ERROR_CANCELLED,
1885 _("Operation was cancelled"));
1886 g_simple_async_result_complete_in_idle (simple);
1887 g_object_unref (simple);
1891 if (connection->closed)
1893 g_simple_async_result_set_error (simple,
1896 _("The connection is closed"));
1897 g_simple_async_result_complete_in_idle (simple);
1898 g_object_unref (simple);
1903 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1905 g_simple_async_result_take_error (simple, error);
1906 g_simple_async_result_complete_in_idle (simple);
1907 g_object_unref (simple);
1911 data = g_new0 (SendMessageData, 1);
1912 data->ref_count = 1;
1913 data->connection = g_object_ref (connection);
1914 data->simple = simple;
1915 data->serial = *out_serial;
1916 data->main_context = g_main_context_ref_thread_default ();
1918 if (cancellable != NULL)
1920 data->cancellable = g_object_ref (cancellable);
1921 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1922 G_CALLBACK (send_message_with_reply_cancelled_cb),
1923 send_message_data_ref (data),
1924 (GDestroyNotify) send_message_data_unref);
1925 g_object_set_data_full (G_OBJECT (simple),
1927 g_object_ref (cancellable),
1928 (GDestroyNotify) g_object_unref);
1931 if (timeout_msec != G_MAXINT)
1933 data->timeout_source = g_timeout_source_new (timeout_msec);
1934 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1935 g_source_set_callback (data->timeout_source,
1936 send_message_with_reply_timeout_cb,
1937 send_message_data_ref (data),
1938 (GDestroyNotify) send_message_data_unref);
1939 g_source_attach (data->timeout_source, data->main_context);
1940 g_source_unref (data->timeout_source);
1943 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1944 GUINT_TO_POINTER (*out_serial),
1952 * g_dbus_connection_send_message_with_reply:
1953 * @connection: A #GDBusConnection.
1954 * @message: A #GDBusMessage.
1955 * @flags: Flags affecting how the message is sent.
1956 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1957 * timeout or %G_MAXINT for no timeout.
1958 * @out_serial: (out) (allow-none): Return location for serial number assigned
1959 * to @message when sending it or %NULL.
1960 * @cancellable: A #GCancellable or %NULL.
1961 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1962 * satisfied or %NULL if you don't care about the result.
1963 * @user_data: The data to pass to @callback.
1965 * Asynchronously sends @message to the peer represented by @connection.
1967 * Unless @flags contain the
1968 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1969 * will be assigned by @connection and set on @message via
1970 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1971 * serial number used will be written to this location prior to
1972 * submitting the message to the underlying transport.
1974 * If @connection is closed then the operation will fail with
1975 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1976 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1977 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1979 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1980 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1981 * of the thread you are calling this method from. You can then call
1982 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1983 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1985 * Note that @message must be unlocked, unless @flags contain the
1986 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1988 * See <xref linkend="gdbus-server"/> and <xref
1989 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1990 * low-level API to send and receive UNIX file descriptors.
1995 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1996 GDBusMessage *message,
1997 GDBusSendMessageFlags flags,
1999 volatile guint32 *out_serial,
2000 GCancellable *cancellable,
2001 GAsyncReadyCallback callback,
2004 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2005 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2006 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2007 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2009 CONNECTION_LOCK (connection);
2010 g_dbus_connection_send_message_with_reply_unlocked (connection,
2018 CONNECTION_UNLOCK (connection);
2022 * g_dbus_connection_send_message_with_reply_finish:
2023 * @connection: a #GDBusConnection
2024 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2025 * @error: Return location for error or %NULL.
2027 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2029 * Note that @error is only set if a local in-process error
2030 * occurred. That is to say that the returned #GDBusMessage object may
2031 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2032 * g_dbus_message_to_gerror() to transcode this to a #GError.
2034 * See <xref linkend="gdbus-server"/> and <xref
2035 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2036 * low-level API to send and receive UNIX file descriptors.
2038 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2043 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2047 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2048 GDBusMessage *reply;
2049 GCancellable *cancellable;
2051 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2052 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2056 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2058 if (g_simple_async_result_propagate_error (simple, error))
2061 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2062 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2063 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2065 g_object_unref (reply);
2067 g_set_error_literal (error,
2069 G_IO_ERROR_CANCELLED,
2070 _("Operation was cancelled"));
2076 /* ---------------------------------------------------------------------------------------------------- */
2081 GMainContext *context;
2083 } SendMessageSyncData;
2086 send_message_with_reply_sync_cb (GDBusConnection *connection,
2090 SendMessageSyncData *data = user_data;
2091 data->res = g_object_ref (res);
2092 g_main_loop_quit (data->loop);
2096 * g_dbus_connection_send_message_with_reply_sync:
2097 * @connection: A #GDBusConnection.
2098 * @message: A #GDBusMessage.
2099 * @flags: Flags affecting how the message is sent.
2100 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2101 * timeout or %G_MAXINT for no timeout.
2102 * @out_serial: (out) (allow-none): Return location for serial number assigned
2103 * to @message when sending it or %NULL.
2104 * @cancellable: A #GCancellable or %NULL.
2105 * @error: Return location for error or %NULL.
2107 * Synchronously sends @message to the peer represented by @connection
2108 * and blocks the calling thread until a reply is received or the
2109 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2110 * for the asynchronous version of this method.
2112 * Unless @flags contain the
2113 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2114 * will be assigned by @connection and set on @message via
2115 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2116 * serial number used will be written to this location prior to
2117 * submitting the message to the underlying transport.
2119 * If @connection is closed then the operation will fail with
2120 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2121 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2122 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2124 * Note that @error is only set if a local in-process error
2125 * occurred. That is to say that the returned #GDBusMessage object may
2126 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2127 * g_dbus_message_to_gerror() to transcode this to a #GError.
2129 * See <xref linkend="gdbus-server"/> and <xref
2130 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2131 * low-level API to send and receive UNIX file descriptors.
2133 * Note that @message must be unlocked, unless @flags contain the
2134 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2136 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2141 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2142 GDBusMessage *message,
2143 GDBusSendMessageFlags flags,
2145 volatile guint32 *out_serial,
2146 GCancellable *cancellable,
2149 SendMessageSyncData *data;
2150 GDBusMessage *reply;
2152 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2153 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2154 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2155 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2156 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2158 data = g_new0 (SendMessageSyncData, 1);
2159 data->context = g_main_context_new ();
2160 data->loop = g_main_loop_new (data->context, FALSE);
2162 g_main_context_push_thread_default (data->context);
2164 g_dbus_connection_send_message_with_reply (connection,
2170 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2172 g_main_loop_run (data->loop);
2173 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2177 g_main_context_pop_thread_default (data->context);
2179 g_main_context_unref (data->context);
2180 g_main_loop_unref (data->loop);
2181 g_object_unref (data->res);
2187 /* ---------------------------------------------------------------------------------------------------- */
2191 GDBusMessageFilterFunction func;
2198 GDBusMessageFilterFunction filter_function;
2200 GDestroyNotify user_data_free_func;
2203 /* Called in worker's thread - we must not block */
2205 on_worker_message_received (GDBusWorker *worker,
2206 GDBusMessage *message,
2209 GDBusConnection *connection;
2210 FilterCallback *filters;
2215 G_LOCK (message_bus_lock);
2216 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2219 G_UNLOCK (message_bus_lock);
2222 connection = G_DBUS_CONNECTION (user_data);
2223 g_object_ref (connection);
2224 G_UNLOCK (message_bus_lock);
2226 //g_debug ("in on_worker_message_received");
2228 g_object_ref (message);
2229 g_dbus_message_lock (message);
2231 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2233 /* First collect the set of callback functions */
2234 CONNECTION_LOCK (connection);
2235 num_filters = connection->filters->len;
2236 filters = g_new0 (FilterCallback, num_filters);
2237 for (n = 0; n < num_filters; n++)
2239 FilterData *data = connection->filters->pdata[n];
2240 filters[n].func = data->filter_function;
2241 filters[n].user_data = data->user_data;
2243 CONNECTION_UNLOCK (connection);
2245 /* then call the filters in order (without holding the lock) */
2246 for (n = 0; n < num_filters; n++)
2248 message = filters[n].func (connection,
2251 filters[n].user_data);
2252 if (message == NULL)
2254 g_dbus_message_lock (message);
2257 /* Standard dispatch unless the filter ate the message - no need to
2258 * do anything if the message was altered
2260 if (message != NULL)
2262 GDBusMessageType message_type;
2264 message_type = g_dbus_message_get_message_type (message);
2265 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2267 guint32 reply_serial;
2268 SendMessageData *send_message_data;
2270 reply_serial = g_dbus_message_get_reply_serial (message);
2271 CONNECTION_LOCK (connection);
2272 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2273 GUINT_TO_POINTER (reply_serial));
2274 if (send_message_data != NULL)
2276 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2277 send_message_data_deliver_reply_unlocked (send_message_data, message);
2281 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2283 CONNECTION_UNLOCK (connection);
2285 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2287 CONNECTION_LOCK (connection);
2288 distribute_signals (connection, message);
2289 CONNECTION_UNLOCK (connection);
2291 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2293 CONNECTION_LOCK (connection);
2294 distribute_method_call (connection, message);
2295 CONNECTION_UNLOCK (connection);
2299 if (message != NULL)
2300 g_object_unref (message);
2301 g_object_unref (connection);
2305 /* Called in worker's thread */
2306 static GDBusMessage *
2307 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2308 GDBusMessage *message,
2311 GDBusConnection *connection;
2312 FilterCallback *filters;
2317 G_LOCK (message_bus_lock);
2318 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2321 G_UNLOCK (message_bus_lock);
2324 connection = G_DBUS_CONNECTION (user_data);
2325 g_object_ref (connection);
2326 G_UNLOCK (message_bus_lock);
2328 //g_debug ("in on_worker_message_about_to_be_sent");
2330 /* First collect the set of callback functions */
2331 CONNECTION_LOCK (connection);
2332 num_filters = connection->filters->len;
2333 filters = g_new0 (FilterCallback, num_filters);
2334 for (n = 0; n < num_filters; n++)
2336 FilterData *data = connection->filters->pdata[n];
2337 filters[n].func = data->filter_function;
2338 filters[n].user_data = data->user_data;
2340 CONNECTION_UNLOCK (connection);
2342 /* then call the filters in order (without holding the lock) */
2343 for (n = 0; n < num_filters; n++)
2345 g_dbus_message_lock (message);
2346 message = filters[n].func (connection,
2349 filters[n].user_data);
2350 if (message == NULL)
2354 g_object_unref (connection);
2360 /* called with connection lock held */
2362 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2364 SendMessageData *data = value;
2366 if (data->delivered)
2369 g_simple_async_result_set_error (data->simple,
2372 _("The connection is closed"));
2374 /* Ask send_message_with_reply_deliver not to remove the element from the
2375 * hash table - we're in the middle of a foreach; that would be unsafe.
2376 * Instead, return TRUE from this function so that it gets removed safely.
2378 send_message_with_reply_deliver (data, FALSE);
2382 /* Called in worker's thread - we must not block */
2384 on_worker_closed (GDBusWorker *worker,
2385 gboolean remote_peer_vanished,
2389 GDBusConnection *connection;
2392 G_LOCK (message_bus_lock);
2393 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2396 G_UNLOCK (message_bus_lock);
2399 connection = G_DBUS_CONNECTION (user_data);
2400 g_object_ref (connection);
2401 G_UNLOCK (message_bus_lock);
2403 //g_debug ("in on_worker_closed: %s", error->message);
2405 CONNECTION_LOCK (connection);
2406 if (!connection->closed)
2408 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2409 set_closed_unlocked (connection, remote_peer_vanished, error);
2411 CONNECTION_UNLOCK (connection);
2413 g_object_unref (connection);
2416 /* ---------------------------------------------------------------------------------------------------- */
2418 /* Determines the biggest set of capabilities we can support on this connection */
2419 static GDBusCapabilityFlags
2420 get_offered_capabilities_max (GDBusConnection *connection)
2422 GDBusCapabilityFlags ret;
2423 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2425 if (G_IS_UNIX_CONNECTION (connection->stream))
2426 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2432 initable_init (GInitable *initable,
2433 GCancellable *cancellable,
2436 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2439 /* This method needs to be idempotent to work with the singleton
2440 * pattern. See the docs for g_initable_init(). We implement this by
2443 * Unfortunately we can't use the main lock since the on_worker_*()
2444 * callbacks above needs the lock during initialization (for message
2445 * bus connections we do a synchronous Hello() call on the bus).
2447 g_mutex_lock (&connection->init_lock);
2451 /* Make this a no-op if we're already initialized (successfully or
2454 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2456 ret = (connection->initialization_error == NULL);
2460 /* Because of init_lock, we can't get here twice in different threads */
2461 g_assert (connection->initialization_error == NULL);
2463 /* The user can pass multiple (but mutally exclusive) construct
2466 * - stream (of type GIOStream)
2467 * - address (of type gchar*)
2469 * At the end of the day we end up with a non-NULL GIOStream
2470 * object in connection->stream.
2472 if (connection->address != NULL)
2474 g_assert (connection->stream == NULL);
2476 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2477 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2479 g_set_error_literal (error,
2481 G_IO_ERROR_INVALID_ARGUMENT,
2482 _("Unsupported flags encountered when constructing a client-side connection"));
2486 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2487 NULL, /* TODO: out_guid */
2489 &connection->initialization_error);
2490 if (connection->stream == NULL)
2493 else if (connection->stream != NULL)
2499 g_assert_not_reached ();
2502 /* Authenticate the connection */
2503 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2505 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2506 g_assert (connection->guid != NULL);
2507 connection->auth = _g_dbus_auth_new (connection->stream);
2508 if (!_g_dbus_auth_run_server (connection->auth,
2509 connection->authentication_observer,
2511 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2512 get_offered_capabilities_max (connection),
2513 &connection->capabilities,
2514 &connection->credentials,
2516 &connection->initialization_error))
2519 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2521 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2522 g_assert (connection->guid == NULL);
2523 connection->auth = _g_dbus_auth_new (connection->stream);
2524 connection->guid = _g_dbus_auth_run_client (connection->auth,
2525 get_offered_capabilities_max (connection),
2526 &connection->capabilities,
2528 &connection->initialization_error);
2529 if (connection->guid == NULL)
2533 if (connection->authentication_observer != NULL)
2535 g_object_unref (connection->authentication_observer);
2536 connection->authentication_observer = NULL;
2539 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2541 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2544 /* We want all IO operations to be non-blocking since they happen in
2545 * the worker thread which is shared by _all_ connections.
2547 if (G_IS_SOCKET_CONNECTION (connection->stream))
2549 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2553 G_LOCK (message_bus_lock);
2554 if (alive_connections == NULL)
2555 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2556 g_hash_table_insert (alive_connections, connection, connection);
2557 G_UNLOCK (message_bus_lock);
2559 connection->worker = _g_dbus_worker_new (connection->stream,
2560 connection->capabilities,
2561 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2562 on_worker_message_received,
2563 on_worker_message_about_to_be_sent,
2567 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2568 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2570 GVariant *hello_result;
2572 /* we could lift this restriction by adding code in gdbusprivate.c */
2573 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2575 g_set_error_literal (&connection->initialization_error,
2578 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2582 hello_result = g_dbus_connection_call_sync (connection,
2583 "org.freedesktop.DBus", /* name */
2584 "/org/freedesktop/DBus", /* path */
2585 "org.freedesktop.DBus", /* interface */
2587 NULL, /* parameters */
2588 G_VARIANT_TYPE ("(s)"),
2589 CALL_FLAGS_INITIALIZING,
2591 NULL, /* TODO: cancellable */
2592 &connection->initialization_error);
2593 if (hello_result == NULL)
2596 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2597 g_variant_unref (hello_result);
2598 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2605 g_assert (connection->initialization_error != NULL);
2606 g_propagate_error (error, g_error_copy (connection->initialization_error));
2609 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2610 g_mutex_unlock (&connection->init_lock);
2616 initable_iface_init (GInitableIface *initable_iface)
2618 initable_iface->init = initable_init;
2621 /* ---------------------------------------------------------------------------------------------------- */
2624 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2629 /* ---------------------------------------------------------------------------------------------------- */
2632 * g_dbus_connection_new:
2633 * @stream: A #GIOStream.
2634 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2635 * @flags: Flags describing how to make the connection.
2636 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2637 * @cancellable: A #GCancellable or %NULL.
2638 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2639 * @user_data: The data to pass to @callback.
2641 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2642 * with the end represented by @stream.
2644 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2645 * will be put into non-blocking mode.
2647 * The D-Bus connection will interact with @stream from a worker thread.
2648 * As a result, the caller should not interact with @stream after this
2649 * method has been called, except by calling g_object_unref() on it.
2651 * If @observer is not %NULL it may be used to control the
2652 * authentication process.
2654 * When the operation is finished, @callback will be invoked. You can
2655 * then call g_dbus_connection_new_finish() to get the result of the
2658 * This is a asynchronous failable constructor. See
2659 * g_dbus_connection_new_sync() for the synchronous
2665 g_dbus_connection_new (GIOStream *stream,
2667 GDBusConnectionFlags flags,
2668 GDBusAuthObserver *observer,
2669 GCancellable *cancellable,
2670 GAsyncReadyCallback callback,
2673 g_return_if_fail (G_IS_IO_STREAM (stream));
2674 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2682 "authentication-observer", observer,
2687 * g_dbus_connection_new_finish:
2688 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2689 * @error: Return location for error or %NULL.
2691 * Finishes an operation started with g_dbus_connection_new().
2693 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2698 g_dbus_connection_new_finish (GAsyncResult *res,
2702 GObject *source_object;
2704 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2705 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2707 source_object = g_async_result_get_source_object (res);
2708 g_assert (source_object != NULL);
2709 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2712 g_object_unref (source_object);
2714 return G_DBUS_CONNECTION (object);
2720 * g_dbus_connection_new_sync:
2721 * @stream: A #GIOStream.
2722 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2723 * @flags: Flags describing how to make the connection.
2724 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2725 * @cancellable: A #GCancellable or %NULL.
2726 * @error: Return location for error or %NULL.
2728 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2729 * with the end represented by @stream.
2731 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2732 * will be put into non-blocking mode.
2734 * The D-Bus connection will interact with @stream from a worker thread.
2735 * As a result, the caller should not interact with @stream after this
2736 * method has been called, except by calling g_object_unref() on it.
2738 * If @observer is not %NULL it may be used to control the
2739 * authentication process.
2741 * This is a synchronous failable constructor. See
2742 * g_dbus_connection_new() for the asynchronous version.
2744 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2749 g_dbus_connection_new_sync (GIOStream *stream,
2751 GDBusConnectionFlags flags,
2752 GDBusAuthObserver *observer,
2753 GCancellable *cancellable,
2756 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2757 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2758 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2764 "authentication-observer", observer,
2768 /* ---------------------------------------------------------------------------------------------------- */
2771 * g_dbus_connection_new_for_address:
2772 * @address: A D-Bus address.
2773 * @flags: Flags describing how to make the connection.
2774 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2775 * @cancellable: A #GCancellable or %NULL.
2776 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2777 * @user_data: The data to pass to @callback.
2779 * Asynchronously connects and sets up a D-Bus client connection for
2780 * exchanging D-Bus messages with an endpoint specified by @address
2781 * which must be in the D-Bus address format.
2783 * This constructor can only be used to initiate client-side
2784 * connections - use g_dbus_connection_new() if you need to act as the
2785 * server. In particular, @flags cannot contain the
2786 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2787 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2789 * When the operation is finished, @callback will be invoked. You can
2790 * then call g_dbus_connection_new_finish() to get the result of the
2793 * If @observer is not %NULL it may be used to control the
2794 * authentication process.
2796 * This is a asynchronous failable constructor. See
2797 * g_dbus_connection_new_for_address_sync() for the synchronous
2803 g_dbus_connection_new_for_address (const gchar *address,
2804 GDBusConnectionFlags flags,
2805 GDBusAuthObserver *observer,
2806 GCancellable *cancellable,
2807 GAsyncReadyCallback callback,
2810 g_return_if_fail (address != NULL);
2811 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2818 "authentication-observer", observer,
2823 * g_dbus_connection_new_for_address_finish:
2824 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2825 * @error: Return location for error or %NULL.
2827 * Finishes an operation started with g_dbus_connection_new_for_address().
2829 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2834 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2838 GObject *source_object;
2840 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2841 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2843 source_object = g_async_result_get_source_object (res);
2844 g_assert (source_object != NULL);
2845 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2848 g_object_unref (source_object);
2850 return G_DBUS_CONNECTION (object);
2856 * g_dbus_connection_new_for_address_sync:
2857 * @address: A D-Bus address.
2858 * @flags: Flags describing how to make the connection.
2859 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2860 * @cancellable: A #GCancellable or %NULL.
2861 * @error: Return location for error or %NULL.
2863 * Synchronously connects and sets up a D-Bus client connection for
2864 * exchanging D-Bus messages with an endpoint specified by @address
2865 * which must be in the D-Bus address format.
2867 * This constructor can only be used to initiate client-side
2868 * connections - use g_dbus_connection_new_sync() if you need to act
2869 * as the server. In particular, @flags cannot contain the
2870 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2871 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2873 * This is a synchronous failable constructor. See
2874 * g_dbus_connection_new_for_address() for the asynchronous version.
2876 * If @observer is not %NULL it may be used to control the
2877 * authentication process.
2879 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2884 g_dbus_connection_new_for_address_sync (const gchar *address,
2885 GDBusConnectionFlags flags,
2886 GDBusAuthObserver *observer,
2887 GCancellable *cancellable,
2890 g_return_val_if_fail (address != NULL, NULL);
2891 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2892 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2897 "authentication-observer", observer,
2901 /* ---------------------------------------------------------------------------------------------------- */
2904 * g_dbus_connection_set_exit_on_close:
2905 * @connection: A #GDBusConnection.
2906 * @exit_on_close: Whether the process should be terminated
2907 * when @connection is closed by the remote peer.
2909 * Sets whether the process should be terminated when @connection is
2910 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2913 * Note that this function should be used with care. Most modern UNIX
2914 * desktops tie the notion of a user session the session bus, and expect
2915 * all of a users applications to quit when their bus connection goes away.
2916 * If you are setting @exit_on_close to %FALSE for the shared session
2917 * bus connection, you should make sure that your application exits
2918 * when the user session ends.
2923 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2924 gboolean exit_on_close)
2926 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2927 connection->exit_on_close = exit_on_close;
2931 * g_dbus_connection_get_exit_on_close:
2932 * @connection: A #GDBusConnection.
2934 * Gets whether the process is terminated when @connection is
2935 * closed by the remote peer. See
2936 * #GDBusConnection:exit-on-close for more details.
2938 * Returns: Whether the process is terminated when @connection is
2939 * closed by the remote peer.
2944 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2946 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2947 return connection->exit_on_close;
2951 * g_dbus_connection_get_guid:
2952 * @connection: A #GDBusConnection.
2954 * The GUID of the peer performing the role of server when
2955 * authenticating. See #GDBusConnection:guid for more details.
2957 * Returns: The GUID. Do not free this string, it is owned by
2963 g_dbus_connection_get_guid (GDBusConnection *connection)
2965 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2966 return connection->guid;
2970 * g_dbus_connection_get_unique_name:
2971 * @connection: A #GDBusConnection.
2973 * Gets the unique name of @connection as assigned by the message
2974 * bus. This can also be used to figure out if @connection is a
2975 * message bus connection.
2977 * Returns: The unique name or %NULL if @connection is not a message
2978 * bus connection. Do not free this string, it is owned by
2984 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2986 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2988 /* do not use g_return_val_if_fail(), we want the memory barrier */
2989 if (!check_initialized (connection))
2992 return connection->bus_unique_name;
2996 * g_dbus_connection_get_peer_credentials:
2997 * @connection: A #GDBusConnection.
2999 * Gets the credentials of the authenticated peer. This will always
3000 * return %NULL unless @connection acted as a server
3001 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3002 * when set up and the client passed credentials as part of the
3003 * authentication process.
3005 * In a message bus setup, the message bus is always the server and
3006 * each application is a client. So this method will always return
3007 * %NULL for message bus clients.
3009 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3010 * this object, it is owned by @connection.
3015 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3017 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3019 /* do not use g_return_val_if_fail(), we want the memory barrier */
3020 if (!check_initialized (connection))
3023 return connection->credentials;
3026 /* ---------------------------------------------------------------------------------------------------- */
3028 static guint _global_filter_id = 1;
3031 * g_dbus_connection_add_filter:
3032 * @connection: A #GDBusConnection.
3033 * @filter_function: A filter function.
3034 * @user_data: User data to pass to @filter_function.
3035 * @user_data_free_func: Function to free @user_data with when filter
3036 * is removed or %NULL.
3038 * Adds a message filter. Filters are handlers that are run on all
3039 * incoming and outgoing messages, prior to standard dispatch. Filters
3040 * are run in the order that they were added. The same handler can be
3041 * added as a filter more than once, in which case it will be run more
3042 * than once. Filters added during a filter callback won't be run on
3043 * the message being processed. Filter functions are allowed to modify
3044 * and even drop messages.
3046 * Note that filters are run in a dedicated message handling thread so
3047 * they can't block and, generally, can't do anything but signal a
3048 * worker thread. Also note that filters are rarely needed - use API
3049 * such as g_dbus_connection_send_message_with_reply(),
3050 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3052 * If a filter consumes an incoming message the message is not
3053 * dispatched anywhere else - not even the standard dispatch machinery
3054 * (that API such as g_dbus_connection_signal_subscribe() and
3055 * g_dbus_connection_send_message_with_reply() relies on) will see the
3056 * message. Similary, if a filter consumes an outgoing message, the
3057 * message will not be sent to the other peer.
3059 * Returns: A filter identifier that can be used with
3060 * g_dbus_connection_remove_filter().
3065 g_dbus_connection_add_filter (GDBusConnection *connection,
3066 GDBusMessageFilterFunction filter_function,
3068 GDestroyNotify user_data_free_func)
3072 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3073 g_return_val_if_fail (filter_function != NULL, 0);
3074 g_return_val_if_fail (check_initialized (connection), 0);
3076 CONNECTION_LOCK (connection);
3077 data = g_new0 (FilterData, 1);
3078 data->id = _global_filter_id++; /* TODO: overflow etc. */
3079 data->filter_function = filter_function;
3080 data->user_data = user_data;
3081 data->user_data_free_func = user_data_free_func;
3082 g_ptr_array_add (connection->filters, data);
3083 CONNECTION_UNLOCK (connection);
3088 /* only called from finalize(), removes all filters */
3090 purge_all_filters (GDBusConnection *connection)
3093 for (n = 0; n < connection->filters->len; n++)
3095 FilterData *data = connection->filters->pdata[n];
3096 if (data->user_data_free_func != NULL)
3097 data->user_data_free_func (data->user_data);
3103 * g_dbus_connection_remove_filter:
3104 * @connection: a #GDBusConnection
3105 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3112 g_dbus_connection_remove_filter (GDBusConnection *connection,
3116 FilterData *to_destroy;
3118 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3119 g_return_if_fail (check_initialized (connection));
3121 CONNECTION_LOCK (connection);
3123 for (n = 0; n < connection->filters->len; n++)
3125 FilterData *data = connection->filters->pdata[n];
3126 if (data->id == filter_id)
3128 g_ptr_array_remove_index (connection->filters, n);
3133 CONNECTION_UNLOCK (connection);
3135 /* do free without holding lock */
3136 if (to_destroy != NULL)
3138 if (to_destroy->user_data_free_func != NULL)
3139 to_destroy->user_data_free_func (to_destroy->user_data);
3140 g_free (to_destroy);
3144 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3148 /* ---------------------------------------------------------------------------------------------------- */
3154 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3155 gchar *interface_name;
3159 GArray *subscribers;
3164 GDBusSignalCallback callback;
3166 GDestroyNotify user_data_free_func;
3168 GMainContext *context;
3172 signal_data_free (SignalData *signal_data)
3174 g_free (signal_data->rule);
3175 g_free (signal_data->sender);
3176 g_free (signal_data->sender_unique_name);
3177 g_free (signal_data->interface_name);
3178 g_free (signal_data->member);
3179 g_free (signal_data->object_path);
3180 g_free (signal_data->arg0);
3181 g_array_free (signal_data->subscribers, TRUE);
3182 g_free (signal_data);
3186 args_to_rule (const gchar *sender,
3187 const gchar *interface_name,
3188 const gchar *member,
3189 const gchar *object_path,
3195 rule = g_string_new ("type='signal'");
3197 g_string_prepend_c (rule, '-');
3199 g_string_append_printf (rule, ",sender='%s'", sender);
3200 if (interface_name != NULL)
3201 g_string_append_printf (rule, ",interface='%s'", interface_name);
3203 g_string_append_printf (rule, ",member='%s'", member);
3204 if (object_path != NULL)
3205 g_string_append_printf (rule, ",path='%s'", object_path);
3207 g_string_append_printf (rule, ",arg0='%s'", arg0);
3209 return g_string_free (rule, FALSE);
3212 static guint _global_subscriber_id = 1;
3213 static guint _global_registration_id = 1;
3214 static guint _global_subtree_registration_id = 1;
3216 /* ---------------------------------------------------------------------------------------------------- */
3218 /* must hold lock when calling */
3220 add_match_rule (GDBusConnection *connection,
3221 const gchar *match_rule)
3224 GDBusMessage *message;
3226 if (match_rule[0] == '-')
3229 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3230 "/org/freedesktop/DBus", /* path */
3231 "org.freedesktop.DBus", /* interface */
3233 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3235 if (!g_dbus_connection_send_message_unlocked (connection,
3237 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3241 g_critical ("Error while sending AddMatch() message: %s", error->message);
3242 g_error_free (error);
3244 g_object_unref (message);
3247 /* ---------------------------------------------------------------------------------------------------- */
3249 /* must hold lock when calling */
3251 remove_match_rule (GDBusConnection *connection,
3252 const gchar *match_rule)
3255 GDBusMessage *message;
3257 if (match_rule[0] == '-')
3260 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3261 "/org/freedesktop/DBus", /* path */
3262 "org.freedesktop.DBus", /* interface */
3264 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3267 if (!g_dbus_connection_send_message_unlocked (connection,
3269 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3273 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3274 g_error_free (error);
3276 g_object_unref (message);
3279 /* ---------------------------------------------------------------------------------------------------- */
3282 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3284 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3285 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3286 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3287 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3288 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3291 /* ---------------------------------------------------------------------------------------------------- */
3294 * g_dbus_connection_signal_subscribe:
3295 * @connection: A #GDBusConnection.
3296 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3297 * or %NULL to listen from all senders.
3298 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3299 * match on all interfaces.
3300 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3301 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3302 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3303 * to match on all kinds of arguments.
3304 * @flags: Flags describing how to subscribe to the signal (currently unused).
3305 * @callback: Callback to invoke when there is a signal matching the requested data.
3306 * @user_data: User data to pass to @callback.
3307 * @user_data_free_func: (allow-none): Function to free @user_data with when
3308 * subscription is removed or %NULL.
3310 * Subscribes to signals on @connection and invokes @callback with a
3311 * whenever the signal is received. Note that @callback
3312 * will be invoked in the <link
3313 * linkend="g-main-context-push-thread-default">thread-default main
3314 * loop</link> of the thread you are calling this method from.
3316 * If @connection is not a message bus connection, @sender must be
3319 * If @sender is a well-known name note that @callback is invoked with
3320 * the unique name for the owner of @sender, not the well-known name
3321 * as one would expect. This is because the message bus rewrites the
3322 * name. As such, to avoid certain race conditions, users should be
3323 * tracking the name owner of the well-known name and use that when
3324 * processing the received signal.
3326 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3331 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3332 const gchar *sender,
3333 const gchar *interface_name,
3334 const gchar *member,
3335 const gchar *object_path,
3337 GDBusSignalFlags flags,
3338 GDBusSignalCallback callback,
3340 GDestroyNotify user_data_free_func)
3343 SignalData *signal_data;
3344 SignalSubscriber subscriber;
3345 GPtrArray *signal_data_array;
3346 const gchar *sender_unique_name;
3348 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3349 * an OOM condition. We might want to change that but that would involve making
3350 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3351 * handle that. And there's really no sensible way of handling this short of retrying
3352 * to add the match rule... and then there's the little thing that, hey, maybe there's
3353 * a reason the bus in an OOM condition.
3355 * Doable, but not really sure it's worth it...
3358 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3359 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3360 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3361 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3362 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3363 g_return_val_if_fail (callback != NULL, 0);
3364 g_return_val_if_fail (check_initialized (connection), 0);
3366 CONNECTION_LOCK (connection);
3368 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3369 * with a '-' character to prefix the rule (which will otherwise be
3372 * This allows us to hash the rule and do our lifecycle tracking in
3373 * the usual way, but the '-' prevents the match rule from ever
3374 * actually being send to the bus (either for add or remove).
3376 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3377 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3379 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3380 sender_unique_name = sender;
3382 sender_unique_name = "";
3384 subscriber.callback = callback;
3385 subscriber.user_data = user_data;
3386 subscriber.user_data_free_func = user_data_free_func;
3387 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3388 subscriber.context = g_main_context_ref_thread_default ();
3390 /* see if we've already have this rule */
3391 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3392 if (signal_data != NULL)
3394 g_array_append_val (signal_data->subscribers, subscriber);
3399 signal_data = g_new0 (SignalData, 1);
3400 signal_data->rule = rule;
3401 signal_data->sender = g_strdup (sender);
3402 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3403 signal_data->interface_name = g_strdup (interface_name);
3404 signal_data->member = g_strdup (member);
3405 signal_data->object_path = g_strdup (object_path);
3406 signal_data->arg0 = g_strdup (arg0);
3407 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3408 g_array_append_val (signal_data->subscribers, subscriber);
3410 g_hash_table_insert (connection->map_rule_to_signal_data,
3414 /* Add the match rule to the bus...
3416 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3417 * always send such messages to us.
3419 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3421 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3422 add_match_rule (connection, signal_data->rule);
3425 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3426 signal_data->sender_unique_name);
3427 if (signal_data_array == NULL)
3429 signal_data_array = g_ptr_array_new ();
3430 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3431 g_strdup (signal_data->sender_unique_name),
3434 g_ptr_array_add (signal_data_array, signal_data);
3437 g_hash_table_insert (connection->map_id_to_signal_data,
3438 GUINT_TO_POINTER (subscriber.id),
3441 CONNECTION_UNLOCK (connection);
3443 return subscriber.id;
3446 /* ---------------------------------------------------------------------------------------------------- */
3448 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3450 unsubscribe_id_internal (GDBusConnection *connection,
3451 guint subscription_id,
3452 GArray *out_removed_subscribers)
3454 SignalData *signal_data;
3455 GPtrArray *signal_data_array;
3458 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3459 GUINT_TO_POINTER (subscription_id));
3460 if (signal_data == NULL)
3462 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3466 for (n = 0; n < signal_data->subscribers->len; n++)
3468 SignalSubscriber *subscriber;
3470 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3471 if (subscriber->id != subscription_id)
3474 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3475 GUINT_TO_POINTER (subscription_id)));
3476 g_array_append_val (out_removed_subscribers, *subscriber);
3477 g_array_remove_index (signal_data->subscribers, n);
3479 if (signal_data->subscribers->len == 0)
3481 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3483 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3484 signal_data->sender_unique_name);
3485 g_warn_if_fail (signal_data_array != NULL);
3486 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3488 if (signal_data_array->len == 0)
3490 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3491 signal_data->sender_unique_name));
3494 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3495 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3497 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3498 if (!connection->closed && !connection->finalizing)
3499 remove_match_rule (connection, signal_data->rule);
3501 signal_data_free (signal_data);
3507 g_assert_not_reached ();
3514 * g_dbus_connection_signal_unsubscribe:
3515 * @connection: A #GDBusConnection.
3516 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3518 * Unsubscribes from signals.
3523 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3524 guint subscription_id)
3526 GArray *subscribers;
3529 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3530 g_return_if_fail (check_initialized (connection));
3532 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3534 CONNECTION_LOCK (connection);
3535 unsubscribe_id_internal (connection,
3538 CONNECTION_UNLOCK (connection);
3541 g_assert (subscribers->len == 0 || subscribers->len == 1);
3543 /* call GDestroyNotify without lock held */
3544 for (n = 0; n < subscribers->len; n++)
3546 SignalSubscriber *subscriber;
3547 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3548 call_destroy_notify (subscriber->context,
3549 subscriber->user_data_free_func,
3550 subscriber->user_data);
3551 g_main_context_unref (subscriber->context);
3554 g_array_free (subscribers, TRUE);
3557 /* ---------------------------------------------------------------------------------------------------- */
3561 guint subscription_id;
3562 GDBusSignalCallback callback;
3564 GDBusMessage *message;
3565 GDBusConnection *connection;
3566 const gchar *sender;
3568 const gchar *interface;
3569 const gchar *member;
3572 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3576 emit_signal_instance_in_idle_cb (gpointer data)
3578 SignalInstance *signal_instance = data;
3579 GVariant *parameters;
3580 gboolean has_subscription;
3582 parameters = g_dbus_message_get_body (signal_instance->message);
3583 if (parameters == NULL)
3585 parameters = g_variant_new ("()");
3586 g_variant_ref_sink (parameters);
3590 g_variant_ref_sink (parameters);
3594 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3595 signal_instance->subscription_id,
3596 signal_instance->sender,
3597 signal_instance->path,
3598 signal_instance->interface,
3599 signal_instance->member,
3600 g_variant_print (parameters, TRUE));
3603 /* Careful here, don't do the callback if we no longer has the subscription */
3604 CONNECTION_LOCK (signal_instance->connection);
3605 has_subscription = FALSE;
3606 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3607 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3608 has_subscription = TRUE;
3609 CONNECTION_UNLOCK (signal_instance->connection);
3611 if (has_subscription)
3612 signal_instance->callback (signal_instance->connection,
3613 signal_instance->sender,
3614 signal_instance->path,
3615 signal_instance->interface,
3616 signal_instance->member,
3618 signal_instance->user_data);
3620 g_variant_unref (parameters);
3626 signal_instance_free (SignalInstance *signal_instance)
3628 g_object_unref (signal_instance->message);
3629 g_object_unref (signal_instance->connection);
3630 g_free (signal_instance);
3633 /* called in message handler thread WITH lock held */
3635 schedule_callbacks (GDBusConnection *connection,
3636 GPtrArray *signal_data_array,
3637 GDBusMessage *message,
3638 const gchar *sender)
3641 const gchar *interface;
3642 const gchar *member;
3651 interface = g_dbus_message_get_interface (message);
3652 member = g_dbus_message_get_member (message);
3653 path = g_dbus_message_get_path (message);
3654 arg0 = g_dbus_message_get_arg0 (message);
3657 g_print ("In schedule_callbacks:\n"
3659 " interface = `%s'\n"
3670 /* TODO: if this is slow, then we can change signal_data_array into
3671 * map_object_path_to_signal_data_array or something.
3673 for (n = 0; n < signal_data_array->len; n++)
3675 SignalData *signal_data = signal_data_array->pdata[n];
3677 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3680 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3683 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3686 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3689 for (m = 0; m < signal_data->subscribers->len; m++)
3691 SignalSubscriber *subscriber;
3692 GSource *idle_source;
3693 SignalInstance *signal_instance;
3695 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3697 signal_instance = g_new0 (SignalInstance, 1);
3698 signal_instance->subscription_id = subscriber->id;
3699 signal_instance->callback = subscriber->callback;
3700 signal_instance->user_data = subscriber->user_data;
3701 signal_instance->message = g_object_ref (message);
3702 signal_instance->connection = g_object_ref (connection);
3703 signal_instance->sender = sender;
3704 signal_instance->path = path;
3705 signal_instance->interface = interface;
3706 signal_instance->member = member;
3708 idle_source = g_idle_source_new ();
3709 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3710 g_source_set_callback (idle_source,
3711 emit_signal_instance_in_idle_cb,
3713 (GDestroyNotify) signal_instance_free);
3714 g_source_attach (idle_source, subscriber->context);
3715 g_source_unref (idle_source);
3720 /* called in message handler thread with lock held */
3722 distribute_signals (GDBusConnection *connection,
3723 GDBusMessage *message)
3725 GPtrArray *signal_data_array;
3726 const gchar *sender;
3728 sender = g_dbus_message_get_sender (message);
3730 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3732 _g_dbus_debug_print_lock ();
3733 g_print ("========================================================================\n"
3734 "GDBus-debug:Signal:\n"
3735 " <<<< RECEIVED SIGNAL %s.%s\n"
3737 " sent by name %s\n",
3738 g_dbus_message_get_interface (message),
3739 g_dbus_message_get_member (message),
3740 g_dbus_message_get_path (message),
3741 sender != NULL ? sender : "(none)");
3742 _g_dbus_debug_print_unlock ();
3745 /* collect subscribers that match on sender */
3748 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3749 if (signal_data_array != NULL)
3750 schedule_callbacks (connection, signal_data_array, message, sender);
3753 /* collect subscribers not matching on sender */
3754 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3755 if (signal_data_array != NULL)
3756 schedule_callbacks (connection, signal_data_array, message, sender);
3759 /* ---------------------------------------------------------------------------------------------------- */
3761 /* only called from finalize(), removes all subscriptions */
3763 purge_all_signal_subscriptions (GDBusConnection *connection)
3765 GHashTableIter iter;
3768 GArray *subscribers;
3771 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3772 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3773 while (g_hash_table_iter_next (&iter, &key, NULL))
3775 guint subscription_id = GPOINTER_TO_UINT (key);
3776 g_array_append_val (ids, subscription_id);
3779 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3780 for (n = 0; n < ids->len; n++)
3782 guint subscription_id = g_array_index (ids, guint, n);
3783 unsubscribe_id_internal (connection,
3787 g_array_free (ids, TRUE);
3789 /* call GDestroyNotify without lock held */
3790 for (n = 0; n < subscribers->len; n++)
3792 SignalSubscriber *subscriber;
3793 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3794 call_destroy_notify (subscriber->context,
3795 subscriber->user_data_free_func,
3796 subscriber->user_data);
3797 g_main_context_unref (subscriber->context);
3800 g_array_free (subscribers, TRUE);
3803 /* ---------------------------------------------------------------------------------------------------- */
3805 static GDBusInterfaceVTable *
3806 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3808 /* Don't waste memory by copying padding - remember to update this
3809 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3811 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3815 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3820 /* ---------------------------------------------------------------------------------------------------- */
3822 static GDBusSubtreeVTable *
3823 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3825 /* Don't waste memory by copying padding - remember to update this
3826 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3828 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3832 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3837 /* ---------------------------------------------------------------------------------------------------- */
3839 struct ExportedObject
3842 GDBusConnection *connection;
3844 /* maps gchar* -> ExportedInterface* */
3845 GHashTable *map_if_name_to_ei;
3848 /* only called with lock held */
3850 exported_object_free (ExportedObject *eo)
3852 g_free (eo->object_path);
3853 g_hash_table_unref (eo->map_if_name_to_ei);
3862 gchar *interface_name;
3863 GDBusInterfaceVTable *vtable;
3864 GDBusInterfaceInfo *interface_info;
3866 GMainContext *context;
3868 GDestroyNotify user_data_free_func;
3869 } ExportedInterface;
3871 /* called with lock held */
3873 exported_interface_free (ExportedInterface *ei)
3875 g_dbus_interface_info_cache_release (ei->interface_info);
3876 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3878 call_destroy_notify (ei->context,
3879 ei->user_data_free_func,
3882 g_main_context_unref (ei->context);
3884 g_free (ei->interface_name);
3885 _g_dbus_interface_vtable_free (ei->vtable);
3889 /* ---------------------------------------------------------------------------------------------------- */
3891 /* Convenience function to check if @registration_id (if not zero) or
3892 * @subtree_registration_id (if not zero) has been unregistered. If
3893 * so, returns %TRUE.
3895 * Caller must *not* hold lock.
3898 has_object_been_unregistered (GDBusConnection *connection,
3899 guint registration_id,
3900 guint subtree_registration_id)
3904 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3908 CONNECTION_LOCK (connection);
3909 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3910 GUINT_TO_POINTER (registration_id)) == NULL)
3914 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3915 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3919 CONNECTION_UNLOCK (connection);
3924 /* ---------------------------------------------------------------------------------------------------- */
3928 GDBusConnection *connection;
3929 GDBusMessage *message;
3931 const gchar *property_name;
3932 const GDBusInterfaceVTable *vtable;
3933 GDBusInterfaceInfo *interface_info;
3934 const GDBusPropertyInfo *property_info;
3935 guint registration_id;
3936 guint subtree_registration_id;
3940 property_data_free (PropertyData *data)
3942 g_object_unref (data->connection);
3943 g_object_unref (data->message);
3947 /* called in thread where object was registered - no locks held */
3949 invoke_get_property_in_idle_cb (gpointer _data)
3951 PropertyData *data = _data;
3954 GDBusMessage *reply;
3956 if (has_object_been_unregistered (data->connection,
3957 data->registration_id,
3958 data->subtree_registration_id))
3960 reply = g_dbus_message_new_method_error (data->message,
3961 "org.freedesktop.DBus.Error.UnknownMethod",
3962 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3963 g_dbus_message_get_path (data->message));
3964 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3965 g_object_unref (reply);
3970 value = data->vtable->get_property (data->connection,
3971 g_dbus_message_get_sender (data->message),
3972 g_dbus_message_get_path (data->message),
3973 data->interface_info->name,
3974 data->property_name,
3981 g_assert_no_error (error);
3983 g_variant_take_ref (value);
3984 reply = g_dbus_message_new_method_reply (data->message);
3985 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3986 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3987 g_variant_unref (value);
3988 g_object_unref (reply);
3992 gchar *dbus_error_name;
3993 g_assert (error != NULL);
3994 dbus_error_name = g_dbus_error_encode_gerror (error);
3995 reply = g_dbus_message_new_method_error_literal (data->message,
3998 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3999 g_free (dbus_error_name);
4000 g_error_free (error);
4001 g_object_unref (reply);
4008 /* called in thread where object was registered - no locks held */
4010 invoke_set_property_in_idle_cb (gpointer _data)
4012 PropertyData *data = _data;
4014 GDBusMessage *reply;
4020 g_variant_get (g_dbus_message_get_body (data->message),
4026 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4027 * of the given value is wrong
4029 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4031 reply = g_dbus_message_new_method_error (data->message,
4032 "org.freedesktop.DBus.Error.InvalidArgs",
4033 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4034 data->property_info->name,
4035 data->property_info->signature,
4036 g_variant_get_type_string (value));
4040 if (!data->vtable->set_property (data->connection,
4041 g_dbus_message_get_sender (data->message),
4042 g_dbus_message_get_path (data->message),
4043 data->interface_info->name,
4044 data->property_name,
4049 gchar *dbus_error_name;
4050 g_assert (error != NULL);
4051 dbus_error_name = g_dbus_error_encode_gerror (error);
4052 reply = g_dbus_message_new_method_error_literal (data->message,
4055 g_free (dbus_error_name);
4056 g_error_free (error);
4060 reply = g_dbus_message_new_method_reply (data->message);
4064 g_assert (reply != NULL);
4065 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4066 g_object_unref (reply);
4067 g_variant_unref (value);
4072 /* called with lock held */
4074 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4075 GDBusMessage *message,
4076 guint registration_id,
4077 guint subtree_registration_id,
4079 GDBusInterfaceInfo *interface_info,
4080 const GDBusInterfaceVTable *vtable,
4081 GMainContext *main_context,
4085 const char *interface_name;
4086 const char *property_name;
4087 const GDBusPropertyInfo *property_info;
4088 GSource *idle_source;
4089 PropertyData *property_data;
4090 GDBusMessage *reply;
4095 g_variant_get (g_dbus_message_get_body (message),
4100 g_variant_get (g_dbus_message_get_body (message),
4109 if (vtable == NULL || vtable->get_property == NULL)
4114 if (vtable == NULL || vtable->set_property == NULL)
4118 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4120 property_info = NULL;
4122 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4123 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4124 if (property_info == NULL)
4126 reply = g_dbus_message_new_method_error (message,
4127 "org.freedesktop.DBus.Error.InvalidArgs",
4128 _("No such property `%s'"),
4130 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4131 g_object_unref (reply);
4136 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4138 reply = g_dbus_message_new_method_error (message,
4139 "org.freedesktop.DBus.Error.InvalidArgs",
4140 _("Property `%s' is not readable"),
4142 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4143 g_object_unref (reply);
4147 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4149 reply = g_dbus_message_new_method_error (message,
4150 "org.freedesktop.DBus.Error.InvalidArgs",
4151 _("Property `%s' is not writable"),
4153 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4154 g_object_unref (reply);
4159 /* ok, got the property info - call user code in an idle handler */
4160 property_data = g_new0 (PropertyData, 1);
4161 property_data->connection = g_object_ref (connection);
4162 property_data->message = g_object_ref (message);
4163 property_data->user_data = user_data;
4164 property_data->property_name = property_name;
4165 property_data->vtable = vtable;
4166 property_data->interface_info = interface_info;
4167 property_data->property_info = property_info;
4168 property_data->registration_id = registration_id;
4169 property_data->subtree_registration_id = subtree_registration_id;
4171 idle_source = g_idle_source_new ();
4172 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4173 g_source_set_callback (idle_source,
4174 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4176 (GDestroyNotify) property_data_free);
4177 g_source_attach (idle_source, main_context);
4178 g_source_unref (idle_source);
4186 /* called with lock held */
4188 handle_getset_property (GDBusConnection *connection,
4190 GDBusMessage *message,
4193 ExportedInterface *ei;
4195 const char *interface_name;
4196 const char *property_name;
4201 g_variant_get (g_dbus_message_get_body (message),
4206 g_variant_get (g_dbus_message_get_body (message),
4212 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4213 * no such interface registered
4215 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4218 GDBusMessage *reply;
4219 reply = g_dbus_message_new_method_error (message,
4220 "org.freedesktop.DBus.Error.InvalidArgs",
4221 _("No such interface `%s'"),
4223 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4224 g_object_unref (reply);
4229 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4242 /* ---------------------------------------------------------------------------------------------------- */
4246 GDBusConnection *connection;
4247 GDBusMessage *message;
4249 const GDBusInterfaceVTable *vtable;
4250 GDBusInterfaceInfo *interface_info;
4251 guint registration_id;
4252 guint subtree_registration_id;
4253 } PropertyGetAllData;
4256 property_get_all_data_free (PropertyData *data)
4258 g_object_unref (data->connection);
4259 g_object_unref (data->message);
4263 /* called in thread where object was registered - no locks held */
4265 invoke_get_all_properties_in_idle_cb (gpointer _data)
4267 PropertyGetAllData *data = _data;
4268 GVariantBuilder builder;
4269 GDBusMessage *reply;
4272 if (has_object_been_unregistered (data->connection,
4273 data->registration_id,
4274 data->subtree_registration_id))
4276 reply = g_dbus_message_new_method_error (data->message,
4277 "org.freedesktop.DBus.Error.UnknownMethod",
4278 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4279 g_dbus_message_get_path (data->message));
4280 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4281 g_object_unref (reply);
4285 /* TODO: Right now we never fail this call - we just omit values if
4286 * a get_property() call is failing.
4288 * We could fail the whole call if just a single get_property() call
4289 * returns an error. We need clarification in the D-Bus spec about this.
4291 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4292 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4293 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4295 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4298 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4301 value = data->vtable->get_property (data->connection,
4302 g_dbus_message_get_sender (data->message),
4303 g_dbus_message_get_path (data->message),
4304 data->interface_info->name,
4305 property_info->name,
4312 g_variant_take_ref (value);
4313 g_variant_builder_add (&builder,
4315 property_info->name,
4317 g_variant_unref (value);
4319 g_variant_builder_close (&builder);
4321 reply = g_dbus_message_new_method_reply (data->message);
4322 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4323 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4324 g_object_unref (reply);
4330 /* called with lock held */
4332 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4333 GDBusMessage *message,
4334 guint registration_id,
4335 guint subtree_registration_id,
4336 GDBusInterfaceInfo *interface_info,
4337 const GDBusInterfaceVTable *vtable,
4338 GMainContext *main_context,
4342 const char *interface_name;
4343 GSource *idle_source;
4344 PropertyGetAllData *property_get_all_data;
4348 g_variant_get (g_dbus_message_get_body (message),
4352 if (vtable == NULL || vtable->get_property == NULL)
4355 /* ok, got the property info - call user in an idle handler */
4356 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4357 property_get_all_data->connection = g_object_ref (connection);
4358 property_get_all_data->message = g_object_ref (message);
4359 property_get_all_data->user_data = user_data;
4360 property_get_all_data->vtable = vtable;
4361 property_get_all_data->interface_info = interface_info;
4362 property_get_all_data->registration_id = registration_id;
4363 property_get_all_data->subtree_registration_id = subtree_registration_id;
4365 idle_source = g_idle_source_new ();
4366 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4367 g_source_set_callback (idle_source,
4368 invoke_get_all_properties_in_idle_cb,
4369 property_get_all_data,
4370 (GDestroyNotify) property_get_all_data_free);
4371 g_source_attach (idle_source, main_context);
4372 g_source_unref (idle_source);
4380 /* called with lock held */
4382 handle_get_all_properties (GDBusConnection *connection,
4384 GDBusMessage *message)
4386 ExportedInterface *ei;
4388 const char *interface_name;
4392 g_variant_get (g_dbus_message_get_body (message),
4396 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4397 * no such interface registered
4399 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4402 GDBusMessage *reply;
4403 reply = g_dbus_message_new_method_error (message,
4404 "org.freedesktop.DBus.Error.InvalidArgs",
4405 _("No such interface"),
4407 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4408 g_object_unref (reply);
4413 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4425 /* ---------------------------------------------------------------------------------------------------- */
4427 static const gchar introspect_header[] =
4428 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4429 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4430 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4433 static const gchar introspect_tail[] =
4436 static const gchar introspect_properties_interface[] =
4437 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4438 " <method name=\"Get\">\n"
4439 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4440 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4441 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4443 " <method name=\"GetAll\">\n"
4444 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4445 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4447 " <method name=\"Set\">\n"
4448 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4449 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4450 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4452 " <signal name=\"PropertiesChanged\">\n"
4453 " <arg type=\"s\" name=\"interface_name\"/>\n"
4454 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4455 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4459 static const gchar introspect_introspectable_interface[] =
4460 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4461 " <method name=\"Introspect\">\n"
4462 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4465 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4466 " <method name=\"Ping\"/>\n"
4467 " <method name=\"GetMachineId\">\n"
4468 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4473 introspect_append_header (GString *s)
4475 g_string_append (s, introspect_header);
4479 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4481 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4487 begin = object_path + path_len;
4488 end = strchr (begin, '/');
4490 s = g_strndup (begin, end - begin);
4492 s = g_strdup (begin);
4494 if (g_hash_table_lookup (set, s) == NULL)
4495 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4501 /* TODO: we want a nicer public interface for this */
4503 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4508 GHashTableIter hash_iter;
4509 const gchar *object_path;
4515 CONNECTION_ENSURE_LOCK (connection);
4517 path_len = strlen (path);
4521 set = g_hash_table_new (g_str_hash, g_str_equal);
4523 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4524 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4525 maybe_add_path (path, path_len, object_path, set);
4527 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4528 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4529 maybe_add_path (path, path_len, object_path, set);
4531 p = g_ptr_array_new ();
4532 keys = g_hash_table_get_keys (set);
4533 for (l = keys; l != NULL; l = l->next)
4534 g_ptr_array_add (p, l->data);
4535 g_hash_table_unref (set);
4538 g_ptr_array_add (p, NULL);
4539 ret = (gchar **) g_ptr_array_free (p, FALSE);
4544 g_dbus_connection_list_registered (GDBusConnection *connection,
4548 CONNECTION_LOCK (connection);
4549 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4550 CONNECTION_UNLOCK (connection);
4554 /* called in message handler thread with lock held */
4556 handle_introspect (GDBusConnection *connection,
4558 GDBusMessage *message)
4562 GDBusMessage *reply;
4563 GHashTableIter hash_iter;
4564 ExportedInterface *ei;
4567 /* first the header with the standard interfaces */
4568 s = g_string_sized_new (sizeof (introspect_header) +
4569 sizeof (introspect_properties_interface) +
4570 sizeof (introspect_introspectable_interface) +
4571 sizeof (introspect_tail));
4572 introspect_append_header (s);
4573 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4574 "org.freedesktop.DBus.Properties"))
4575 g_string_append (s, introspect_properties_interface);
4577 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4578 "org.freedesktop.DBus.Introspectable"))
4579 g_string_append (s, introspect_introspectable_interface);
4581 /* then include the registered interfaces */
4582 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4583 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4584 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4586 /* finally include nodes registered below us */
4587 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4588 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4589 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4590 g_strfreev (registered);
4591 g_string_append (s, introspect_tail);
4593 reply = g_dbus_message_new_method_reply (message);
4594 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4595 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4596 g_object_unref (reply);
4597 g_string_free (s, TRUE);
4602 /* called in thread where object was registered - no locks held */
4604 call_in_idle_cb (gpointer user_data)
4606 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4607 GDBusInterfaceVTable *vtable;
4608 guint registration_id;
4609 guint subtree_registration_id;
4611 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4612 g_assert (vtable != NULL && vtable->method_call != NULL);
4614 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4615 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4617 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4619 subtree_registration_id))
4621 GDBusMessage *reply;
4622 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4623 "org.freedesktop.DBus.Error.UnknownMethod",
4624 _("No such interface `%s' on object at path %s"),
4625 g_dbus_method_invocation_get_interface_name (invocation),
4626 g_dbus_method_invocation_get_object_path (invocation));
4627 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4628 g_object_unref (reply);
4632 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4633 g_dbus_method_invocation_get_sender (invocation),
4634 g_dbus_method_invocation_get_object_path (invocation),
4635 g_dbus_method_invocation_get_interface_name (invocation),
4636 g_dbus_method_invocation_get_method_name (invocation),
4637 g_dbus_method_invocation_get_parameters (invocation),
4638 g_object_ref (invocation),
4639 g_dbus_method_invocation_get_user_data (invocation));
4645 /* called in message handler thread with lock held */
4647 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4648 GDBusMessage *message,
4649 guint registration_id,
4650 guint subtree_registration_id,
4651 GDBusInterfaceInfo *interface_info,
4652 const GDBusInterfaceVTable *vtable,
4653 GMainContext *main_context,
4656 GDBusMethodInvocation *invocation;
4657 const GDBusMethodInfo *method_info;
4658 GDBusMessage *reply;
4659 GVariant *parameters;
4660 GSource *idle_source;
4662 GVariantType *in_type;
4666 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4667 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4669 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4670 * error to the caller
4672 if (method_info == NULL)
4674 reply = g_dbus_message_new_method_error (message,
4675 "org.freedesktop.DBus.Error.UnknownMethod",
4676 _("No such method `%s'"),
4677 g_dbus_message_get_member (message));
4678 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4679 g_object_unref (reply);
4684 parameters = g_dbus_message_get_body (message);
4685 if (parameters == NULL)
4687 parameters = g_variant_new ("()");
4688 g_variant_ref_sink (parameters);
4692 g_variant_ref (parameters);
4695 /* Check that the incoming args are of the right type - if they are not, return
4696 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4698 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4699 if (!g_variant_is_of_type (parameters, in_type))
4703 type_string = g_variant_type_dup_string (in_type);
4705 reply = g_dbus_message_new_method_error (message,
4706 "org.freedesktop.DBus.Error.InvalidArgs",
4707 _("Type of message, `%s', does not match expected type `%s'"),
4708 g_variant_get_type_string (parameters),
4710 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4711 g_variant_type_free (in_type);
4712 g_variant_unref (parameters);
4713 g_object_unref (reply);
4714 g_free (type_string);
4718 g_variant_type_free (in_type);
4720 /* schedule the call in idle */
4721 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4722 g_dbus_message_get_path (message),
4723 g_dbus_message_get_interface (message),
4724 g_dbus_message_get_member (message),
4730 g_variant_unref (parameters);
4732 /* TODO: would be nicer with a real MethodData like we already
4733 * have PropertyData and PropertyGetAllData... */
4734 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4735 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4736 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4738 idle_source = g_idle_source_new ();
4739 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4740 g_source_set_callback (idle_source,
4744 g_source_attach (idle_source, main_context);
4745 g_source_unref (idle_source);
4753 /* ---------------------------------------------------------------------------------------------------- */
4755 /* called in message handler thread with lock held */
4757 obj_message_func (GDBusConnection *connection,
4759 GDBusMessage *message)
4761 const gchar *interface_name;
4762 const gchar *member;
4763 const gchar *signature;
4768 interface_name = g_dbus_message_get_interface (message);
4769 member = g_dbus_message_get_member (message);
4770 signature = g_dbus_message_get_signature (message);
4772 /* see if we have an interface for handling this call */
4773 if (interface_name != NULL)
4775 ExportedInterface *ei;
4776 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4779 /* we do - invoke the handler in idle in the right thread */
4781 /* handle no vtable or handler being present */
4782 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4785 handled = validate_and_maybe_schedule_method_call (connection,
4797 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4798 g_strcmp0 (member, "Introspect") == 0 &&
4799 g_strcmp0 (signature, "") == 0)
4801 handled = handle_introspect (connection, eo, message);
4804 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4805 g_strcmp0 (member, "Get") == 0 &&
4806 g_strcmp0 (signature, "ss") == 0)
4808 handled = handle_getset_property (connection, eo, message, TRUE);
4811 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4812 g_strcmp0 (member, "Set") == 0 &&
4813 g_strcmp0 (signature, "ssv") == 0)
4815 handled = handle_getset_property (connection, eo, message, FALSE);
4818 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4819 g_strcmp0 (member, "GetAll") == 0 &&
4820 g_strcmp0 (signature, "s") == 0)
4822 handled = handle_get_all_properties (connection, eo, message);
4831 * g_dbus_connection_register_object:
4832 * @connection: A #GDBusConnection.
4833 * @object_path: The object path to register at.
4834 * @interface_info: Introspection data for the interface.
4835 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4836 * @user_data: (allow-none): Data to pass to functions in @vtable.
4837 * @user_data_free_func: Function to call when the object path is unregistered.
4838 * @error: Return location for error or %NULL.
4840 * Registers callbacks for exported objects at @object_path with the
4841 * D-Bus interface that is described in @interface_info.
4843 * Calls to functions in @vtable (and @user_data_free_func) will
4844 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4845 * loop</link> of the thread you are calling this method from.
4847 * Note that all #GVariant values passed to functions in @vtable will match
4848 * the signature given in @interface_info - if a remote caller passes
4849 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4850 * is returned to the remote caller.
4852 * Additionally, if the remote caller attempts to invoke methods or
4853 * access properties not mentioned in @interface_info the
4854 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4855 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4856 * are returned to the caller.
4858 * It is considered a programming error if the
4859 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4860 * #GVariant of incorrect type.
4862 * If an existing callback is already registered at @object_path and
4863 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4865 * GDBus automatically implements the standard D-Bus interfaces
4866 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4867 * and org.freedesktop.Peer, so you don't have to implement those for
4868 * the objects you export. You <emphasis>can</emphasis> implement
4869 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4870 * and setting of properties asynchronously.
4872 * Note that the reference count on @interface_info will be
4873 * incremented by 1 (unless allocated statically, e.g. if the
4874 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4875 * as the object is exported. Also note that @vtable will be copied.
4877 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4879 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4880 * that can be used with g_dbus_connection_unregister_object() .
4885 g_dbus_connection_register_object (GDBusConnection *connection,
4886 const gchar *object_path,
4887 GDBusInterfaceInfo *interface_info,
4888 const GDBusInterfaceVTable *vtable,
4890 GDestroyNotify user_data_free_func,
4894 ExportedInterface *ei;
4897 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4898 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4899 g_return_val_if_fail (interface_info != NULL, 0);
4900 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4901 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4902 g_return_val_if_fail (check_initialized (connection), 0);
4906 CONNECTION_LOCK (connection);
4908 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4911 eo = g_new0 (ExportedObject, 1);
4912 eo->object_path = g_strdup (object_path);
4913 eo->connection = connection;
4914 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4917 (GDestroyNotify) exported_interface_free);
4918 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4921 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4927 _("An object is already exported for the interface %s at %s"),
4928 interface_info->name,
4933 ei = g_new0 (ExportedInterface, 1);
4934 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4936 ei->user_data = user_data;
4937 ei->user_data_free_func = user_data_free_func;
4938 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4939 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4940 g_dbus_interface_info_cache_build (ei->interface_info);
4941 ei->interface_name = g_strdup (interface_info->name);
4942 ei->context = g_main_context_ref_thread_default ();
4944 g_hash_table_insert (eo->map_if_name_to_ei,
4945 (gpointer) ei->interface_name,
4947 g_hash_table_insert (connection->map_id_to_ei,
4948 GUINT_TO_POINTER (ei->id),
4954 CONNECTION_UNLOCK (connection);
4960 * g_dbus_connection_unregister_object:
4961 * @connection: A #GDBusConnection.
4962 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4964 * Unregisters an object.
4966 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4971 g_dbus_connection_unregister_object (GDBusConnection *connection,
4972 guint registration_id)
4974 ExportedInterface *ei;
4978 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4979 g_return_val_if_fail (check_initialized (connection), FALSE);
4983 CONNECTION_LOCK (connection);
4985 ei = g_hash_table_lookup (connection->map_id_to_ei,
4986 GUINT_TO_POINTER (registration_id));
4992 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4993 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4994 /* unregister object path if we have no more exported interfaces */
4995 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4996 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5002 CONNECTION_UNLOCK (connection);
5007 /* ---------------------------------------------------------------------------------------------------- */
5010 * g_dbus_connection_emit_signal:
5011 * @connection: A #GDBusConnection.
5012 * @destination_bus_name: (allow-none): The unique bus name for the destination
5013 * for the signal or %NULL to emit to all listeners.
5014 * @object_path: Path of remote object.
5015 * @interface_name: D-Bus interface to emit a signal on.
5016 * @signal_name: The name of the signal to emit.
5017 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5018 * or %NULL if not passing parameters.
5019 * @error: Return location for error or %NULL.
5023 * If the parameters GVariant is floating, it is consumed.
5025 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5027 * Returns: %TRUE unless @error is set.
5032 g_dbus_connection_emit_signal (GDBusConnection *connection,
5033 const gchar *destination_bus_name,
5034 const gchar *object_path,
5035 const gchar *interface_name,
5036 const gchar *signal_name,
5037 GVariant *parameters,
5040 GDBusMessage *message;
5046 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5047 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5048 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5049 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5050 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5051 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5052 g_return_val_if_fail (check_initialized (connection), FALSE);
5054 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5056 _g_dbus_debug_print_lock ();
5057 g_print ("========================================================================\n"
5058 "GDBus-debug:Emission:\n"
5059 " >>>> SIGNAL EMISSION %s.%s()\n"
5061 " destination %s\n",
5062 interface_name, signal_name,
5064 destination_bus_name != NULL ? destination_bus_name : "(none)");
5065 _g_dbus_debug_print_unlock ();
5068 message = g_dbus_message_new_signal (object_path,
5072 if (destination_bus_name != NULL)
5073 g_dbus_message_set_header (message,
5074 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5075 g_variant_new_string (destination_bus_name));
5077 if (parameters != NULL)
5078 g_dbus_message_set_body (message, parameters);
5080 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5081 g_object_unref (message);
5087 add_call_flags (GDBusMessage *message,
5088 GDBusCallFlags flags)
5090 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5091 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5095 decode_method_reply (GDBusMessage *reply,
5096 const gchar *method_name,
5097 const GVariantType *reply_type,
5098 GUnixFDList **out_fd_list,
5104 switch (g_dbus_message_get_message_type (reply))
5106 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5107 result = g_dbus_message_get_body (reply);
5110 result = g_variant_new ("()");
5111 g_variant_ref_sink (result);
5115 g_variant_ref (result);
5118 if (!g_variant_is_of_type (result, reply_type))
5120 gchar *type_string = g_variant_type_dup_string (reply_type);
5124 G_IO_ERROR_INVALID_ARGUMENT,
5125 _("Method `%s' returned type `%s', but expected `%s'"),
5126 method_name, g_variant_get_type_string (result), type_string);
5128 g_variant_unref (result);
5129 g_free (type_string);
5136 if (out_fd_list != NULL)
5138 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5139 if (*out_fd_list != NULL)
5140 g_object_ref (*out_fd_list);
5146 case G_DBUS_MESSAGE_TYPE_ERROR:
5147 g_dbus_message_to_gerror (reply, error);
5151 g_assert_not_reached ();
5161 GSimpleAsyncResult *simple;
5162 GVariantType *reply_type;
5163 gchar *method_name; /* for error message */
5167 GUnixFDList *fd_list;
5171 call_state_free (CallState *state)
5173 g_variant_type_free (state->reply_type);
5174 g_free (state->method_name);
5176 if (state->value != NULL)
5177 g_variant_unref (state->value);
5178 if (state->fd_list != NULL)
5179 g_object_unref (state->fd_list);
5180 g_slice_free (CallState, state);
5184 g_dbus_connection_call_done (GObject *source,
5185 GAsyncResult *result,
5188 GSimpleAsyncResult *simple;
5189 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5190 CallState *state = user_data;
5192 GDBusMessage *reply;
5195 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5199 if (G_UNLIKELY (_g_dbus_debug_call ()))
5201 _g_dbus_debug_print_lock ();
5202 g_print ("========================================================================\n"
5203 "GDBus-debug:Call:\n"
5204 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5210 g_print ("SUCCESS\n");
5214 g_print ("FAILED: %s\n",
5217 _g_dbus_debug_print_unlock ();
5221 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5223 simple = state->simple; /* why? because state is freed before we unref simple.. */
5226 g_simple_async_result_take_error (state->simple, error);
5227 g_simple_async_result_complete (state->simple);
5228 call_state_free (state);
5232 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5233 g_simple_async_result_complete (state->simple);
5234 g_object_unref (reply);
5236 g_object_unref (simple);
5240 g_dbus_connection_call_internal (GDBusConnection *connection,
5241 const gchar *bus_name,
5242 const gchar *object_path,
5243 const gchar *interface_name,
5244 const gchar *method_name,
5245 GVariant *parameters,
5246 const GVariantType *reply_type,
5247 GDBusCallFlags flags,
5249 GUnixFDList *fd_list,
5250 GCancellable *cancellable,
5251 GAsyncReadyCallback callback,
5254 GDBusMessage *message;
5257 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5258 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5259 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5260 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5261 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5262 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5263 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5264 g_return_if_fail (check_initialized (connection));
5266 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5268 g_return_if_fail (fd_list == NULL);
5271 state = g_slice_new0 (CallState);
5272 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5273 callback, user_data,
5274 g_dbus_connection_call_internal);
5275 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5277 if (reply_type == NULL)
5278 reply_type = G_VARIANT_TYPE_ANY;
5280 state->reply_type = g_variant_type_copy (reply_type);
5282 message = g_dbus_message_new_method_call (bus_name,
5286 add_call_flags (message, flags);
5287 if (parameters != NULL)
5288 g_dbus_message_set_body (message, parameters);
5291 if (fd_list != NULL)
5292 g_dbus_message_set_unix_fd_list (message, fd_list);
5295 g_dbus_connection_send_message_with_reply (connection,
5297 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5301 g_dbus_connection_call_done,
5304 if (G_UNLIKELY (_g_dbus_debug_call ()))
5306 _g_dbus_debug_print_lock ();
5307 g_print ("========================================================================\n"
5308 "GDBus-debug:Call:\n"
5309 " >>>> ASYNC %s.%s()\n"
5311 " owned by name %s (serial %d)\n",
5315 bus_name != NULL ? bus_name : "(none)",
5317 _g_dbus_debug_print_unlock ();
5320 if (message != NULL)
5321 g_object_unref (message);
5325 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5326 GUnixFDList **out_fd_list,
5330 GSimpleAsyncResult *simple;
5333 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5334 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5335 g_dbus_connection_call_internal), NULL);
5336 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5338 simple = G_SIMPLE_ASYNC_RESULT (res);
5340 if (g_simple_async_result_propagate_error (simple, error))
5343 state = g_simple_async_result_get_op_res_gpointer (simple);
5344 if (out_fd_list != NULL)
5345 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5346 return g_variant_ref (state->value);
5350 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5351 const gchar *bus_name,
5352 const gchar *object_path,
5353 const gchar *interface_name,
5354 const gchar *method_name,
5355 GVariant *parameters,
5356 const GVariantType *reply_type,
5357 GDBusCallFlags flags,
5359 GUnixFDList *fd_list,
5360 GUnixFDList **out_fd_list,
5361 GCancellable *cancellable,
5364 GDBusMessage *message;
5365 GDBusMessage *reply;
5367 GError *local_error;
5368 GDBusSendMessageFlags send_flags;
5374 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5375 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5376 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5377 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5378 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5379 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5380 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5382 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5384 g_return_val_if_fail (fd_list == NULL, NULL);
5386 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5388 if (!(flags & CALL_FLAGS_INITIALIZING))
5389 g_return_val_if_fail (check_initialized (connection), FALSE);
5391 if (reply_type == NULL)
5392 reply_type = G_VARIANT_TYPE_ANY;
5394 message = g_dbus_message_new_method_call (bus_name,
5398 add_call_flags (message, flags);
5399 if (parameters != NULL)
5400 g_dbus_message_set_body (message, parameters);
5403 if (fd_list != NULL)
5404 g_dbus_message_set_unix_fd_list (message, fd_list);
5407 if (G_UNLIKELY (_g_dbus_debug_call ()))
5409 _g_dbus_debug_print_lock ();
5410 g_print ("========================================================================\n"
5411 "GDBus-debug:Call:\n"
5412 " >>>> SYNC %s.%s()\n"
5414 " owned by name %s\n",
5418 bus_name != NULL ? bus_name : "(none)");
5419 _g_dbus_debug_print_unlock ();
5424 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5426 /* translate from one flavour of flags to another... */
5427 if (flags & CALL_FLAGS_INITIALIZING)
5428 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5430 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5434 NULL, /* volatile guint32 *out_serial */
5438 if (G_UNLIKELY (_g_dbus_debug_call ()))
5440 _g_dbus_debug_print_lock ();
5441 g_print ("========================================================================\n"
5442 "GDBus-debug:Call:\n"
5443 " <<<< SYNC COMPLETE %s.%s()\n"
5449 g_print ("SUCCESS\n");
5453 g_print ("FAILED: %s\n",
5454 local_error->message);
5456 _g_dbus_debug_print_unlock ();
5462 *error = local_error;
5464 g_error_free (local_error);
5468 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5471 if (message != NULL)
5472 g_object_unref (message);
5474 g_object_unref (reply);
5479 /* ---------------------------------------------------------------------------------------------------- */
5482 * g_dbus_connection_call:
5483 * @connection: A #GDBusConnection.
5484 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5485 * @connection is not a message bus connection.
5486 * @object_path: Path of remote object.
5487 * @interface_name: D-Bus interface to invoke method on.
5488 * @method_name: The name of the method to invoke.
5489 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5490 * or %NULL if not passing parameters.
5491 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5492 * @flags: Flags from the #GDBusCallFlags enumeration.
5493 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5494 * timeout or %G_MAXINT for no timeout.
5495 * @cancellable: A #GCancellable or %NULL.
5496 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5497 * satisfied or %NULL if you don't * care about the result of the
5498 * method invocation.
5499 * @user_data: The data to pass to @callback.
5501 * Asynchronously invokes the @method_name method on the
5502 * @interface_name D-Bus interface on the remote object at
5503 * @object_path owned by @bus_name.
5505 * If @connection is closed then the operation will fail with
5506 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5507 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5508 * not compatible with the D-Bus protocol, the operation fails with
5509 * %G_IO_ERROR_INVALID_ARGUMENT.
5511 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5512 * error will be raised if it does not match. Said another way, if you give a @reply_type
5513 * then any non-%NULL return value will be of this type.
5515 * If the @parameters #GVariant is floating, it is consumed. This allows
5516 * convenient 'inline' use of g_variant_new(), e.g.:
5518 * g_dbus_connection_call (connection,
5519 * "org.freedesktop.StringThings",
5520 * "/org/freedesktop/StringThings",
5521 * "org.freedesktop.StringThings",
5523 * g_variant_new ("(ss)",
5527 * G_DBUS_CALL_FLAGS_NONE,
5530 * (GAsyncReadyCallback) two_strings_done,
5534 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5535 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5536 * of the thread you are calling this method from. You can then call
5537 * g_dbus_connection_call_finish() to get the result of the operation.
5538 * See g_dbus_connection_call_sync() for the synchronous version of this
5544 g_dbus_connection_call (GDBusConnection *connection,
5545 const gchar *bus_name,
5546 const gchar *object_path,
5547 const gchar *interface_name,
5548 const gchar *method_name,
5549 GVariant *parameters,
5550 const GVariantType *reply_type,
5551 GDBusCallFlags flags,
5553 GCancellable *cancellable,
5554 GAsyncReadyCallback callback,
5557 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);
5561 * g_dbus_connection_call_finish:
5562 * @connection: A #GDBusConnection.
5563 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5564 * @error: Return location for error or %NULL.
5566 * Finishes an operation started with g_dbus_connection_call().
5568 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5569 * return values. Free with g_variant_unref().
5574 g_dbus_connection_call_finish (GDBusConnection *connection,
5578 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5582 * g_dbus_connection_call_sync:
5583 * @connection: A #GDBusConnection.
5584 * @bus_name: A unique or well-known bus name.
5585 * @object_path: Path of remote object.
5586 * @interface_name: D-Bus interface to invoke method on.
5587 * @method_name: The name of the method to invoke.
5588 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5589 * or %NULL if not passing parameters.
5590 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5591 * @flags: Flags from the #GDBusCallFlags enumeration.
5592 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5593 * timeout or %G_MAXINT for no timeout.
5594 * @cancellable: A #GCancellable or %NULL.
5595 * @error: Return location for error or %NULL.
5597 * Synchronously invokes the @method_name method on the
5598 * @interface_name D-Bus interface on the remote object at
5599 * @object_path owned by @bus_name.
5601 * If @connection is closed then the operation will fail with
5602 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5603 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5604 * contains a value not compatible with the D-Bus protocol, the operation
5605 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5607 * If @reply_type is non-%NULL then the reply will be checked for having
5608 * this type and an error will be raised if it does not match. Said
5609 * another way, if you give a @reply_type then any non-%NULL return
5610 * value will be of this type.
5612 * If the @parameters #GVariant is floating, it is consumed.
5613 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5615 * g_dbus_connection_call_sync (connection,
5616 * "org.freedesktop.StringThings",
5617 * "/org/freedesktop/StringThings",
5618 * "org.freedesktop.StringThings",
5620 * g_variant_new ("(ss)",
5624 * G_DBUS_CALL_FLAGS_NONE,
5630 * The calling thread is blocked until a reply is received. See
5631 * g_dbus_connection_call() for the asynchronous version of
5634 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5635 * return values. Free with g_variant_unref().
5640 g_dbus_connection_call_sync (GDBusConnection *connection,
5641 const gchar *bus_name,
5642 const gchar *object_path,
5643 const gchar *interface_name,
5644 const gchar *method_name,
5645 GVariant *parameters,
5646 const GVariantType *reply_type,
5647 GDBusCallFlags flags,
5649 GCancellable *cancellable,
5652 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);
5655 /* ---------------------------------------------------------------------------------------------------- */
5660 * g_dbus_connection_call_with_unix_fd_list:
5661 * @connection: A #GDBusConnection.
5662 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5663 * @connection is not a message bus connection.
5664 * @object_path: Path of remote object.
5665 * @interface_name: D-Bus interface to invoke method on.
5666 * @method_name: The name of the method to invoke.
5667 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5668 * or %NULL if not passing parameters.
5669 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5670 * @flags: Flags from the #GDBusCallFlags enumeration.
5671 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5672 * timeout or %G_MAXINT for no timeout.
5673 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5674 * @cancellable: A #GCancellable or %NULL.
5675 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5676 * satisfied or %NULL if you don't * care about the result of the
5677 * method invocation.
5678 * @user_data: The data to pass to @callback.
5680 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5682 * This method is only available on UNIX.
5687 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5688 const gchar *bus_name,
5689 const gchar *object_path,
5690 const gchar *interface_name,
5691 const gchar *method_name,
5692 GVariant *parameters,
5693 const GVariantType *reply_type,
5694 GDBusCallFlags flags,
5696 GUnixFDList *fd_list,
5697 GCancellable *cancellable,
5698 GAsyncReadyCallback callback,
5701 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);
5705 * g_dbus_connection_call_with_unix_fd_list_finish:
5706 * @connection: A #GDBusConnection.
5707 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5708 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5709 * @error: Return location for error or %NULL.
5711 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5713 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5714 * return values. Free with g_variant_unref().
5719 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5720 GUnixFDList **out_fd_list,
5724 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5728 * g_dbus_connection_call_with_unix_fd_list_sync:
5729 * @connection: A #GDBusConnection.
5730 * @bus_name: A unique or well-known bus name.
5731 * @object_path: Path of remote object.
5732 * @interface_name: D-Bus interface to invoke method on.
5733 * @method_name: The name of the method to invoke.
5734 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5735 * or %NULL if not passing parameters.
5736 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5737 * @flags: Flags from the #GDBusCallFlags enumeration.
5738 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5739 * timeout or %G_MAXINT for no timeout.
5740 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5741 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5742 * @cancellable: A #GCancellable or %NULL.
5743 * @error: Return location for error or %NULL.
5745 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5747 * This method is only available on UNIX.
5749 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5750 * return values. Free with g_variant_unref().
5755 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5756 const gchar *bus_name,
5757 const gchar *object_path,
5758 const gchar *interface_name,
5759 const gchar *method_name,
5760 GVariant *parameters,
5761 const GVariantType *reply_type,
5762 GDBusCallFlags flags,
5764 GUnixFDList *fd_list,
5765 GUnixFDList **out_fd_list,
5766 GCancellable *cancellable,
5769 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);
5772 #endif /* G_OS_UNIX */
5774 /* ---------------------------------------------------------------------------------------------------- */
5776 struct ExportedSubtree
5780 GDBusConnection *connection;
5781 GDBusSubtreeVTable *vtable;
5782 GDBusSubtreeFlags flags;
5784 GMainContext *context;
5786 GDestroyNotify user_data_free_func;
5790 exported_subtree_free (ExportedSubtree *es)
5792 call_destroy_notify (es->context,
5793 es->user_data_free_func,
5796 g_main_context_unref (es->context);
5798 _g_dbus_subtree_vtable_free (es->vtable);
5799 g_free (es->object_path);
5803 /* called without lock held */
5805 handle_subtree_introspect (GDBusConnection *connection,
5806 ExportedSubtree *es,
5807 GDBusMessage *message)
5811 GDBusMessage *reply;
5814 const gchar *sender;
5815 const gchar *requested_object_path;
5816 const gchar *requested_node;
5817 GDBusInterfaceInfo **interfaces;
5819 gchar **subnode_paths;
5820 gboolean has_properties_interface;
5821 gboolean has_introspectable_interface;
5825 requested_object_path = g_dbus_message_get_path (message);
5826 sender = g_dbus_message_get_sender (message);
5827 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5829 s = g_string_new (NULL);
5830 introspect_append_header (s);
5832 /* Strictly we don't need the children in dynamic mode, but we avoid the
5833 * conditionals to preserve code clarity
5835 children = es->vtable->enumerate (es->connection,
5842 requested_node = strrchr (requested_object_path, '/') + 1;
5844 /* Assert existence of object if we are not dynamic */
5845 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5846 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5851 requested_node = NULL;
5854 interfaces = es->vtable->introspect (es->connection,
5859 if (interfaces != NULL)
5861 has_properties_interface = FALSE;
5862 has_introspectable_interface = FALSE;
5864 for (n = 0; interfaces[n] != NULL; n++)
5866 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5867 has_properties_interface = TRUE;
5868 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5869 has_introspectable_interface = TRUE;
5871 if (!has_properties_interface)
5872 g_string_append (s, introspect_properties_interface);
5873 if (!has_introspectable_interface)
5874 g_string_append (s, introspect_introspectable_interface);
5876 for (n = 0; interfaces[n] != NULL; n++)
5878 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5879 g_dbus_interface_info_unref (interfaces[n]);
5881 g_free (interfaces);
5884 /* then include <node> entries from the Subtree for the root */
5887 for (n = 0; children != NULL && children[n] != NULL; n++)
5888 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5891 /* finally include nodes registered below us */
5892 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5893 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5894 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5895 g_strfreev (subnode_paths);
5897 g_string_append (s, "</node>\n");
5899 reply = g_dbus_message_new_method_reply (message);
5900 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5901 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5902 g_object_unref (reply);
5907 g_string_free (s, TRUE);
5908 g_strfreev (children);
5912 /* called without lock held */
5914 handle_subtree_method_invocation (GDBusConnection *connection,
5915 ExportedSubtree *es,
5916 GDBusMessage *message)
5919 const gchar *sender;
5920 const gchar *interface_name;
5921 const gchar *member;
5922 const gchar *signature;
5923 const gchar *requested_object_path;
5924 const gchar *requested_node;
5926 GDBusInterfaceInfo *interface_info;
5927 const GDBusInterfaceVTable *interface_vtable;
5928 gpointer interface_user_data;
5930 GDBusInterfaceInfo **interfaces;
5931 gboolean is_property_get;
5932 gboolean is_property_set;
5933 gboolean is_property_get_all;
5938 requested_object_path = g_dbus_message_get_path (message);
5939 sender = g_dbus_message_get_sender (message);
5940 interface_name = g_dbus_message_get_interface (message);
5941 member = g_dbus_message_get_member (message);
5942 signature = g_dbus_message_get_signature (message);
5943 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5945 is_property_get = FALSE;
5946 is_property_set = FALSE;
5947 is_property_get_all = FALSE;
5948 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5950 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5951 is_property_get = TRUE;
5952 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5953 is_property_set = TRUE;
5954 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5955 is_property_get_all = TRUE;
5960 requested_node = strrchr (requested_object_path, '/') + 1;
5962 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5964 /* We don't want to dispatch to unenumerated
5965 * nodes, so ensure that the child exists.
5970 children = es->vtable->enumerate (es->connection,
5975 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5976 g_strfreev (children);
5984 requested_node = NULL;
5987 /* get introspection data for the node */
5988 interfaces = es->vtable->introspect (es->connection,
5990 requested_object_path,
5994 if (interfaces == NULL)
5997 interface_info = NULL;
5998 for (n = 0; interfaces[n] != NULL; n++)
6000 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6001 interface_info = interfaces[n];
6004 /* dispatch the call if the user wants to handle it */
6005 if (interface_info != NULL)
6007 /* figure out where to dispatch the method call */
6008 interface_user_data = NULL;
6009 interface_vtable = es->vtable->dispatch (es->connection,
6014 &interface_user_data,
6016 if (interface_vtable == NULL)
6019 CONNECTION_LOCK (connection);
6020 handled = validate_and_maybe_schedule_method_call (es->connection,
6027 interface_user_data);
6028 CONNECTION_UNLOCK (connection);
6030 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6031 else if (is_property_get || is_property_set || is_property_get_all)
6033 if (is_property_get)
6034 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6035 else if (is_property_set)
6036 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6037 else if (is_property_get_all)
6038 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6040 g_assert_not_reached ();
6042 /* see if the object supports this interface at all */
6043 for (n = 0; interfaces[n] != NULL; n++)
6045 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6046 interface_info = interfaces[n];
6049 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6050 * claims it won't support the interface
6052 if (interface_info == NULL)
6054 GDBusMessage *reply;
6055 reply = g_dbus_message_new_method_error (message,
6056 "org.freedesktop.DBus.Error.InvalidArgs",
6057 _("No such interface `%s'"),
6059 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6060 g_object_unref (reply);
6065 /* figure out where to dispatch the property get/set/getall calls */
6066 interface_user_data = NULL;
6067 interface_vtable = es->vtable->dispatch (es->connection,
6072 &interface_user_data,
6074 if (interface_vtable == NULL)
6076 g_warning ("The subtree introspection function indicates that '%s' "
6077 "is a valid interface name, but calling the dispatch "
6078 "function on that interface gave us NULL", interface_name);
6082 if (is_property_get || is_property_set)
6084 CONNECTION_LOCK (connection);
6085 handled = validate_and_maybe_schedule_property_getset (es->connection,
6093 interface_user_data);
6094 CONNECTION_UNLOCK (connection);
6096 else if (is_property_get_all)
6098 CONNECTION_LOCK (connection);
6099 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6106 interface_user_data);
6107 CONNECTION_UNLOCK (connection);
6112 if (interfaces != NULL)
6114 for (n = 0; interfaces[n] != NULL; n++)
6115 g_dbus_interface_info_unref (interfaces[n]);
6116 g_free (interfaces);
6124 GDBusMessage *message;
6125 ExportedSubtree *es;
6126 } SubtreeDeferredData;
6129 subtree_deferred_data_free (SubtreeDeferredData *data)
6131 g_object_unref (data->message);
6135 /* called without lock held in the thread where the caller registered the subtree */
6137 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6139 SubtreeDeferredData *data = _data;
6144 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6145 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6146 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6147 handled = handle_subtree_introspect (data->es->connection,
6151 handled = handle_subtree_method_invocation (data->es->connection,
6157 CONNECTION_LOCK (data->es->connection);
6158 handled = handle_generic_unlocked (data->es->connection, data->message);
6159 CONNECTION_UNLOCK (data->es->connection);
6162 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6165 GDBusMessage *reply;
6166 reply = g_dbus_message_new_method_error (data->message,
6167 "org.freedesktop.DBus.Error.UnknownMethod",
6168 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6169 g_dbus_message_get_member (data->message),
6170 g_dbus_message_get_interface (data->message),
6171 g_dbus_message_get_signature (data->message));
6172 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6173 g_object_unref (reply);
6179 /* called in message handler thread with lock held */
6181 subtree_message_func (GDBusConnection *connection,
6182 ExportedSubtree *es,
6183 GDBusMessage *message)
6185 GSource *idle_source;
6186 SubtreeDeferredData *data;
6188 data = g_new0 (SubtreeDeferredData, 1);
6189 data->message = g_object_ref (message);
6192 /* defer this call to an idle handler in the right thread */
6193 idle_source = g_idle_source_new ();
6194 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6195 g_source_set_callback (idle_source,
6196 process_subtree_vtable_message_in_idle_cb,
6198 (GDestroyNotify) subtree_deferred_data_free);
6199 g_source_attach (idle_source, es->context);
6200 g_source_unref (idle_source);
6202 /* since we own the entire subtree, handlers for objects not in the subtree have been
6203 * tried already by libdbus-1 - so we just need to ensure that we're always going
6204 * to reply to the message
6210 * g_dbus_connection_register_subtree:
6211 * @connection: A #GDBusConnection.
6212 * @object_path: The object path to register the subtree at.
6213 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6214 * @flags: Flags used to fine tune the behavior of the subtree.
6215 * @user_data: Data to pass to functions in @vtable.
6216 * @user_data_free_func: Function to call when the subtree is unregistered.
6217 * @error: Return location for error or %NULL.
6219 * Registers a whole subtree of <quote>dynamic</quote> objects.
6221 * The @enumerate and @introspection functions in @vtable are used to
6222 * convey, to remote callers, what nodes exist in the subtree rooted
6225 * When handling remote calls into any node in the subtree, first the
6226 * @enumerate function is used to check if the node exists. If the node exists
6227 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6228 * the @introspection function is used to check if the node supports the
6229 * requested method. If so, the @dispatch function is used to determine
6230 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6231 * #gpointer will be used to call into the interface vtable for processing
6234 * All calls into user-provided code will be invoked in the <link
6235 * linkend="g-main-context-push-thread-default">thread-default main
6236 * loop</link> of the thread you are calling this method from.
6238 * If an existing subtree is already registered at @object_path or
6239 * then @error is set to #G_IO_ERROR_EXISTS.
6241 * Note that it is valid to register regular objects (using
6242 * g_dbus_connection_register_object()) in a subtree registered with
6243 * g_dbus_connection_register_subtree() - if so, the subtree handler
6244 * is tried as the last resort. One way to think about a subtree
6245 * handler is to consider it a <quote>fallback handler</quote>
6246 * for object paths not registered via g_dbus_connection_register_object()
6247 * or other bindings.
6249 * Note that @vtable will be copied so you cannot change it after
6252 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6254 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6255 * that can be used with g_dbus_connection_unregister_subtree() .
6260 g_dbus_connection_register_subtree (GDBusConnection *connection,
6261 const gchar *object_path,
6262 const GDBusSubtreeVTable *vtable,
6263 GDBusSubtreeFlags flags,
6265 GDestroyNotify user_data_free_func,
6269 ExportedSubtree *es;
6271 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6272 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6273 g_return_val_if_fail (vtable != NULL, 0);
6274 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6275 g_return_val_if_fail (check_initialized (connection), 0);
6279 CONNECTION_LOCK (connection);
6281 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6287 _("A subtree is already exported for %s"),
6292 es = g_new0 (ExportedSubtree, 1);
6293 es->object_path = g_strdup (object_path);
6294 es->connection = connection;
6296 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6298 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6299 es->user_data = user_data;
6300 es->user_data_free_func = user_data_free_func;
6301 es->context = g_main_context_ref_thread_default ();
6303 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6304 g_hash_table_insert (connection->map_id_to_es,
6305 GUINT_TO_POINTER (es->id),
6311 CONNECTION_UNLOCK (connection);
6316 /* ---------------------------------------------------------------------------------------------------- */
6319 * g_dbus_connection_unregister_subtree:
6320 * @connection: A #GDBusConnection.
6321 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6323 * Unregisters a subtree.
6325 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6330 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6331 guint registration_id)
6333 ExportedSubtree *es;
6336 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6337 g_return_val_if_fail (check_initialized (connection), FALSE);
6341 CONNECTION_LOCK (connection);
6343 es = g_hash_table_lookup (connection->map_id_to_es,
6344 GUINT_TO_POINTER (registration_id));
6348 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6349 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6354 CONNECTION_UNLOCK (connection);
6359 /* ---------------------------------------------------------------------------------------------------- */
6361 /* must be called with lock held */
6363 handle_generic_ping_unlocked (GDBusConnection *connection,
6364 const gchar *object_path,
6365 GDBusMessage *message)
6367 GDBusMessage *reply;
6368 reply = g_dbus_message_new_method_reply (message);
6369 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6370 g_object_unref (reply);
6373 /* must be called with lock held */
6375 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6376 const gchar *object_path,
6377 GDBusMessage *message)
6379 GDBusMessage *reply;
6382 if (connection->machine_id == NULL)
6387 connection->machine_id = _g_dbus_get_machine_id (&error);
6388 if (connection->machine_id == NULL)
6390 reply = g_dbus_message_new_method_error_literal (message,
6391 "org.freedesktop.DBus.Error.Failed",
6393 g_error_free (error);
6399 reply = g_dbus_message_new_method_reply (message);
6400 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6402 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6403 g_object_unref (reply);
6406 /* must be called with lock held */
6408 handle_generic_introspect_unlocked (GDBusConnection *connection,
6409 const gchar *object_path,
6410 GDBusMessage *message)
6415 GDBusMessage *reply;
6417 /* first the header */
6418 s = g_string_new (NULL);
6419 introspect_append_header (s);
6421 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6422 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6423 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6424 g_strfreev (registered);
6425 g_string_append (s, "</node>\n");
6427 reply = g_dbus_message_new_method_reply (message);
6428 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6429 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6430 g_object_unref (reply);
6431 g_string_free (s, TRUE);
6434 /* must be called with lock held */
6436 handle_generic_unlocked (GDBusConnection *connection,
6437 GDBusMessage *message)
6440 const gchar *interface_name;
6441 const gchar *member;
6442 const gchar *signature;
6445 CONNECTION_ENSURE_LOCK (connection);
6449 interface_name = g_dbus_message_get_interface (message);
6450 member = g_dbus_message_get_member (message);
6451 signature = g_dbus_message_get_signature (message);
6452 path = g_dbus_message_get_path (message);
6454 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6455 g_strcmp0 (member, "Introspect") == 0 &&
6456 g_strcmp0 (signature, "") == 0)
6458 handle_generic_introspect_unlocked (connection, path, message);
6461 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6462 g_strcmp0 (member, "Ping") == 0 &&
6463 g_strcmp0 (signature, "") == 0)
6465 handle_generic_ping_unlocked (connection, path, message);
6468 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6469 g_strcmp0 (member, "GetMachineId") == 0 &&
6470 g_strcmp0 (signature, "") == 0)
6472 handle_generic_get_machine_id_unlocked (connection, path, message);
6479 /* ---------------------------------------------------------------------------------------------------- */
6481 /* called in message handler thread with lock held */
6483 distribute_method_call (GDBusConnection *connection,
6484 GDBusMessage *message)
6486 GDBusMessage *reply;
6488 ExportedSubtree *es;
6489 const gchar *object_path;
6490 const gchar *interface_name;
6491 const gchar *member;
6493 gchar *subtree_path;
6496 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6498 interface_name = g_dbus_message_get_interface (message);
6499 member = g_dbus_message_get_member (message);
6500 path = g_dbus_message_get_path (message);
6501 subtree_path = g_strdup (path);
6502 needle = strrchr (subtree_path, '/');
6503 if (needle != NULL && needle != subtree_path)
6509 g_free (subtree_path);
6510 subtree_path = NULL;
6514 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6516 _g_dbus_debug_print_lock ();
6517 g_print ("========================================================================\n"
6518 "GDBus-debug:Incoming:\n"
6519 " <<<< METHOD INVOCATION %s.%s()\n"
6521 " invoked by name %s\n"
6523 interface_name, member,
6525 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6526 g_dbus_message_get_serial (message));
6527 _g_dbus_debug_print_unlock ();
6530 object_path = g_dbus_message_get_path (message);
6531 g_assert (object_path != NULL);
6533 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6536 if (obj_message_func (connection, eo, message))
6540 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6543 if (subtree_message_func (connection, es, message))
6547 if (subtree_path != NULL)
6549 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6552 if (subtree_message_func (connection, es, message))
6557 if (handle_generic_unlocked (connection, message))
6560 /* if we end up here, the message has not been not handled - so return an error saying this */
6561 reply = g_dbus_message_new_method_error (message,
6562 "org.freedesktop.DBus.Error.UnknownMethod",
6563 _("No such interface `%s' on object at path %s"),
6566 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6567 g_object_unref (reply);
6570 g_free (subtree_path);
6573 /* ---------------------------------------------------------------------------------------------------- */
6575 static GDBusConnection **
6576 message_bus_get_singleton (GBusType bus_type,
6579 GDBusConnection **ret;
6580 const gchar *starter_bus;
6586 case G_BUS_TYPE_SESSION:
6587 ret = &the_session_bus;
6590 case G_BUS_TYPE_SYSTEM:
6591 ret = &the_system_bus;
6594 case G_BUS_TYPE_STARTER:
6595 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6596 if (g_strcmp0 (starter_bus, "session") == 0)
6598 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6601 else if (g_strcmp0 (starter_bus, "system") == 0)
6603 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6608 if (starter_bus != NULL)
6612 G_IO_ERROR_INVALID_ARGUMENT,
6613 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6614 " - unknown value `%s'"),
6619 g_set_error_literal (error,
6621 G_IO_ERROR_INVALID_ARGUMENT,
6622 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6623 "variable is not set"));
6629 g_assert_not_reached ();
6637 static GDBusConnection *
6638 get_uninitialized_connection (GBusType bus_type,
6639 GCancellable *cancellable,
6642 GDBusConnection **singleton;
6643 GDBusConnection *ret;
6647 G_LOCK (message_bus_lock);
6648 singleton = message_bus_get_singleton (bus_type, error);
6649 if (singleton == NULL)
6652 if (*singleton == NULL)
6655 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6656 if (address == NULL)
6658 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6660 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6661 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6662 "exit-on-close", TRUE,
6668 ret = g_object_ref (*singleton);
6671 g_assert (ret != NULL);
6674 G_UNLOCK (message_bus_lock);
6680 * @bus_type: A #GBusType.
6681 * @cancellable: A #GCancellable or %NULL.
6682 * @error: Return location for error or %NULL.
6684 * Synchronously connects to the message bus specified by @bus_type.
6685 * Note that the returned object may shared with other callers,
6686 * e.g. if two separate parts of a process calls this function with
6687 * the same @bus_type, they will share the same object.
6689 * This is a synchronous failable function. See g_bus_get() and
6690 * g_bus_get_finish() for the asynchronous version.
6692 * The returned object is a singleton, that is, shared with other
6693 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6694 * event that you need a private message bus connection, use
6695 * g_dbus_address_get_for_bus_sync() and
6696 * g_dbus_connection_new_for_address().
6698 * Note that the returned #GDBusConnection object will (usually) have
6699 * the #GDBusConnection:exit-on-close property set to %TRUE.
6701 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6706 g_bus_get_sync (GBusType bus_type,
6707 GCancellable *cancellable,
6710 GDBusConnection *connection;
6712 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6714 connection = get_uninitialized_connection (bus_type, cancellable, error);
6715 if (connection == NULL)
6718 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6720 g_object_unref (connection);
6729 bus_get_async_initable_cb (GObject *source_object,
6733 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6737 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6741 g_assert (error != NULL);
6742 g_simple_async_result_take_error (simple, error);
6743 g_object_unref (source_object);
6747 g_simple_async_result_set_op_res_gpointer (simple,
6751 g_simple_async_result_complete_in_idle (simple);
6752 g_object_unref (simple);
6757 * @bus_type: A #GBusType.
6758 * @cancellable: A #GCancellable or %NULL.
6759 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6760 * @user_data: The data to pass to @callback.
6762 * Asynchronously connects to the message bus specified by @bus_type.
6764 * When the operation is finished, @callback will be invoked. You can
6765 * then call g_bus_get_finish() to get the result of the operation.
6767 * This is a asynchronous failable function. See g_bus_get_sync() for
6768 * the synchronous version.
6773 g_bus_get (GBusType bus_type,
6774 GCancellable *cancellable,
6775 GAsyncReadyCallback callback,
6778 GDBusConnection *connection;
6779 GSimpleAsyncResult *simple;
6782 simple = g_simple_async_result_new (NULL,
6788 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6789 if (connection == NULL)
6791 g_assert (error != NULL);
6792 g_simple_async_result_take_error (simple, error);
6793 g_simple_async_result_complete_in_idle (simple);
6794 g_object_unref (simple);
6798 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6801 bus_get_async_initable_cb,
6808 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6809 * @error: Return location for error or %NULL.
6811 * Finishes an operation started with g_bus_get().
6813 * The returned object is a singleton, that is, shared with other
6814 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6815 * event that you need a private message bus connection, use
6816 * g_dbus_address_get_for_bus_sync() and
6817 * g_dbus_connection_new_for_address().
6819 * Note that the returned #GDBusConnection object will (usually) have
6820 * the #GDBusConnection:exit-on-close property set to %TRUE.
6822 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6827 g_bus_get_finish (GAsyncResult *res,
6830 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6832 GDBusConnection *ret;
6834 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6836 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6840 if (g_simple_async_result_propagate_error (simple, error))
6843 object = g_simple_async_result_get_op_res_gpointer (simple);
6844 g_assert (object != NULL);
6845 ret = g_object_ref (G_DBUS_CONNECTION (object));
6851 /* ---------------------------------------------------------------------------------------------------- */