1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * Most of the ways to obtain a #GDBusConnection automatically initialize it
152 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
153 * g_bus_get(), and the synchronous versions of those methods, give you an
154 * initialized connection. Language bindings for GIO should use
155 * g_initable_new() or g_async_initable_new(), which also initialize the
158 * If you construct an uninitialized #GDBusConnection, such as via
159 * g_object_new(), you must initialize it via g_initable_init() or
160 * g_async_initable_init() before using its methods or properties. Calling
161 * methods or accessing properties on a #GDBusConnection that has not completed
162 * initialization successfully is considered to be invalid, and leads to
163 * undefined behaviour. In particular, if initialization fails with a #GError,
164 * the only valid thing you can do with that #GDBusConnection is to free it
165 * with g_object_unref().
167 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
169 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
171 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
173 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
176 /* ---------------------------------------------------------------------------------------------------- */
178 typedef struct _GDBusConnectionClass GDBusConnectionClass;
181 * GDBusConnectionClass:
182 * @closed: Signal class handler for the #GDBusConnection::closed signal.
184 * Class structure for #GDBusConnection.
188 struct _GDBusConnectionClass
191 GObjectClass parent_class;
195 void (*closed) (GDBusConnection *connection,
196 gboolean remote_peer_vanished,
200 G_LOCK_DEFINE_STATIC (message_bus_lock);
202 static GDBusConnection *the_session_bus = NULL;
203 static GDBusConnection *the_system_bus = NULL;
205 /* Extra pseudo-member of GDBusSendMessageFlags.
206 * Set by initable_init() to indicate that despite not being initialized yet,
207 * enough of the only-valid-after-init members are set that we can send a
208 * message, and we're being called from its thread, so no memory barrier is
209 * required before accessing them.
211 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
213 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
214 #define CALL_FLAGS_INITIALIZING (1<<31)
216 /* ---------------------------------------------------------------------------------------------------- */
220 GDestroyNotify callback;
222 GMainContext *context;
223 } CallDestroyNotifyData;
226 call_destroy_notify_data_in_idle (gpointer user_data)
228 CallDestroyNotifyData *data = user_data;
229 data->callback (data->user_data);
234 call_destroy_notify_data_free (CallDestroyNotifyData *data)
236 if (data->context != NULL)
237 g_main_context_unref (data->context);
242 * call_destroy_notify: <internal>
243 * @context: A #GMainContext or %NULL.
244 * @callback: A #GDestroyNotify or %NULL.
245 * @user_data: Data to pass to @callback.
247 * Schedules @callback to run in @context.
250 call_destroy_notify (GMainContext *context,
251 GDestroyNotify callback,
254 GMainContext *current_context;
256 if (callback == NULL)
259 current_context = g_main_context_get_thread_default ();
260 if ((context == current_context) ||
261 (current_context == NULL && context == g_main_context_default ()))
263 callback (user_data);
267 GSource *idle_source;
268 CallDestroyNotifyData *data;
270 data = g_new0 (CallDestroyNotifyData, 1);
271 data->callback = callback;
272 data->user_data = user_data;
273 data->context = context;
274 if (data->context != NULL)
275 g_main_context_ref (data->context);
277 idle_source = g_idle_source_new ();
278 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
279 g_source_set_callback (idle_source,
280 call_destroy_notify_data_in_idle,
282 (GDestroyNotify) call_destroy_notify_data_free);
283 g_source_attach (idle_source, data->context);
284 g_source_unref (idle_source);
291 /* ---------------------------------------------------------------------------------------------------- */
294 _g_strv_has_string (const gchar* const *haystack,
299 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
301 if (g_strcmp0 (haystack[n], needle) == 0)
307 /* ---------------------------------------------------------------------------------------------------- */
310 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
312 // TODO: for some reason this doesn't work on Windows
313 #define CONNECTION_ENSURE_LOCK(obj) do { \
314 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
316 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
317 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
322 #define CONNECTION_LOCK(obj) do { \
323 g_mutex_lock (&(obj)->lock); \
326 #define CONNECTION_UNLOCK(obj) do { \
327 g_mutex_unlock (&(obj)->lock); \
330 /* Flags in connection->atomic_flags */
332 FLAG_INITIALIZED = 1 << 0,
333 FLAG_EXIT_ON_CLOSE = 1 << 1
339 * The #GDBusConnection structure contains only private data and
340 * should only be accessed using the provided API.
344 struct _GDBusConnection
347 GObject parent_instance;
349 /* ------------------------------------------------------------------------ */
350 /* -- General object state ------------------------------------------------ */
351 /* ------------------------------------------------------------------------ */
353 /* object-wide lock */
356 /* A lock used in the init() method of the GInitable interface - see comments
357 * in initable_init() for why a separate lock is needed
361 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
362 * someone calls org.freedesktop.DBus.GetMachineId()
366 /* The underlying stream used for communication
367 * Read-only after initable_init(), so it may be read if you either
368 * hold @init_lock or check for initialization first.
372 /* The object used for authentication (if any).
373 * Read-only after initable_init(), so it may be read if you either
374 * hold @init_lock or check for initialization first.
378 /* Set to TRUE if the connection has been closed */
381 /* Last serial used */
384 /* The object used to send/receive messages.
385 * Read-only after initable_init(), so it may be read if you either
386 * hold @init_lock or check for initialization first.
390 /* If connected to a message bus, this contains the unique name assigned to
391 * us by the bus (e.g. ":1.42").
392 * Read-only after initable_init(), so it may be read if you either
393 * hold @init_lock or check for initialization first.
395 gchar *bus_unique_name;
397 /* The GUID returned by the other side if we authenticed as a client or
398 * the GUID to use if authenticating as a server.
399 * Read-only after initable_init(), so it may be read if you either
400 * hold @init_lock or check for initialization first.
404 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
405 * Inspect @initialization_error to see whether it succeeded or failed.
407 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
409 volatile gint atomic_flags;
411 /* If the connection could not be established during initable_init(),
412 * this GError will be set.
413 * Read-only after initable_init(), so it may be read if you either
414 * hold @init_lock or check for initialization first.
416 GError *initialization_error;
418 /* The result of g_main_context_ref_thread_default() when the object
419 * was created (the GObject _init() function) - this is used for delivery
420 * of the :closed GObject signal.
422 GMainContext *main_context_at_construction;
424 /* construct properties */
426 GDBusConnectionFlags flags;
428 /* Map used for managing method replies */
429 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
431 /* Maps used for managing signal subscription */
432 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
433 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
434 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
436 /* Maps used for managing exported objects and subtrees */
437 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
438 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
439 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
440 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
442 /* Structure used for message filters */
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);
645 /* called in any user thread, with the connection's lock not held */
647 g_dbus_connection_get_property (GObject *object,
652 GDBusConnection *connection = G_DBUS_CONNECTION (object);
657 g_value_set_object (value, g_dbus_connection_get_stream (connection));
661 g_value_set_string (value, g_dbus_connection_get_guid (connection));
664 case PROP_UNIQUE_NAME:
665 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
669 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
672 case PROP_EXIT_ON_CLOSE:
673 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
676 case PROP_CAPABILITY_FLAGS:
677 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
681 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
686 /* called in any user thread, with the connection's lock not held */
688 g_dbus_connection_set_property (GObject *object,
693 GDBusConnection *connection = G_DBUS_CONNECTION (object);
698 connection->stream = g_value_dup_object (value);
702 connection->guid = g_value_dup_string (value);
706 connection->address = g_value_dup_string (value);
710 connection->flags = g_value_get_flags (value);
713 case PROP_EXIT_ON_CLOSE:
714 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
717 case PROP_AUTHENTICATION_OBSERVER:
718 connection->authentication_observer = g_value_dup_object (value);
722 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
727 /* Base-class implementation of GDBusConnection::closed.
729 * Called in a user thread, by the main context that was thread-default when
730 * the object was constructed.
733 g_dbus_connection_real_closed (GDBusConnection *connection,
734 gboolean remote_peer_vanished,
737 gint flags = g_atomic_int_get (&connection->atomic_flags);
739 /* Because atomic int access is a memory barrier, we can safely read
740 * initialization_error without a lock, as long as we do it afterwards.
742 if (remote_peer_vanished &&
743 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
744 (flags & FLAG_INITIALIZED) != 0 &&
745 connection->initialization_error == NULL)
749 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
752 g_quark_to_string (error->domain), error->code);
756 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
763 g_dbus_connection_class_init (GDBusConnectionClass *klass)
765 GObjectClass *gobject_class;
767 gobject_class = G_OBJECT_CLASS (klass);
769 gobject_class->finalize = g_dbus_connection_finalize;
770 gobject_class->dispose = g_dbus_connection_dispose;
771 gobject_class->set_property = g_dbus_connection_set_property;
772 gobject_class->get_property = g_dbus_connection_get_property;
774 klass->closed = g_dbus_connection_real_closed;
777 * GDBusConnection:stream:
779 * The underlying #GIOStream used for I/O.
781 * If this is passed on construction and is a #GSocketConnection,
782 * then the corresponding #GSocket will be put into non-blocking mode.
784 * While the #GDBusConnection is active, it will interact with this
785 * stream from a worker thread, so it is not safe to interact with
786 * the stream directly.
790 g_object_class_install_property (gobject_class,
792 g_param_spec_object ("stream",
794 P_("The underlying streams used for I/O"),
798 G_PARAM_CONSTRUCT_ONLY |
799 G_PARAM_STATIC_NAME |
800 G_PARAM_STATIC_BLURB |
801 G_PARAM_STATIC_NICK));
804 * GDBusConnection:address:
806 * A D-Bus address specifying potential endpoints that can be used
807 * when establishing the connection.
811 g_object_class_install_property (gobject_class,
813 g_param_spec_string ("address",
815 P_("D-Bus address specifying potential socket endpoints"),
818 G_PARAM_CONSTRUCT_ONLY |
819 G_PARAM_STATIC_NAME |
820 G_PARAM_STATIC_BLURB |
821 G_PARAM_STATIC_NICK));
824 * GDBusConnection:flags:
826 * Flags from the #GDBusConnectionFlags enumeration.
830 g_object_class_install_property (gobject_class,
832 g_param_spec_flags ("flags",
835 G_TYPE_DBUS_CONNECTION_FLAGS,
836 G_DBUS_CONNECTION_FLAGS_NONE,
838 G_PARAM_CONSTRUCT_ONLY |
839 G_PARAM_STATIC_NAME |
840 G_PARAM_STATIC_BLURB |
841 G_PARAM_STATIC_NICK));
844 * GDBusConnection:guid:
846 * The GUID of the peer performing the role of server when
849 * If you are constructing a #GDBusConnection and pass
850 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
851 * #GDBusConnection:flags property then you MUST also set this
852 * property to a valid guid.
854 * If you are constructing a #GDBusConnection and pass
855 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
856 * #GDBusConnection:flags property you will be able to read the GUID
857 * of the other peer here after the connection has been successfully
862 g_object_class_install_property (gobject_class,
864 g_param_spec_string ("guid",
866 P_("GUID of the server peer"),
870 G_PARAM_CONSTRUCT_ONLY |
871 G_PARAM_STATIC_NAME |
872 G_PARAM_STATIC_BLURB |
873 G_PARAM_STATIC_NICK));
876 * GDBusConnection:unique-name:
878 * The unique name as assigned by the message bus or %NULL if the
879 * connection is not open or not a message bus connection.
883 g_object_class_install_property (gobject_class,
885 g_param_spec_string ("unique-name",
887 P_("Unique name of bus connection"),
890 G_PARAM_STATIC_NAME |
891 G_PARAM_STATIC_BLURB |
892 G_PARAM_STATIC_NICK));
895 * GDBusConnection:closed:
897 * A boolean specifying whether the connection has been closed.
901 g_object_class_install_property (gobject_class,
903 g_param_spec_boolean ("closed",
905 P_("Whether the connection is closed"),
908 G_PARAM_STATIC_NAME |
909 G_PARAM_STATIC_BLURB |
910 G_PARAM_STATIC_NICK));
913 * GDBusConnection:exit-on-close:
915 * A boolean specifying whether the process will be terminated (by
916 * calling <literal>raise(SIGTERM)</literal>) if the connection
917 * is closed by the remote peer.
921 g_object_class_install_property (gobject_class,
923 g_param_spec_boolean ("exit-on-close",
925 P_("Whether the process is terminated when the connection is closed"),
929 G_PARAM_STATIC_NAME |
930 G_PARAM_STATIC_BLURB |
931 G_PARAM_STATIC_NICK));
934 * GDBusConnection:capabilities:
936 * Flags from the #GDBusCapabilityFlags enumeration
937 * representing connection features negotiated with the other peer.
941 g_object_class_install_property (gobject_class,
942 PROP_CAPABILITY_FLAGS,
943 g_param_spec_flags ("capabilities",
946 G_TYPE_DBUS_CAPABILITY_FLAGS,
947 G_DBUS_CAPABILITY_FLAGS_NONE,
949 G_PARAM_STATIC_NAME |
950 G_PARAM_STATIC_BLURB |
951 G_PARAM_STATIC_NICK));
954 * GDBusConnection:authentication-observer:
956 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
960 g_object_class_install_property (gobject_class,
961 PROP_AUTHENTICATION_OBSERVER,
962 g_param_spec_object ("authentication-observer",
963 P_("Authentication Observer"),
964 P_("Object used to assist in the authentication process"),
965 G_TYPE_DBUS_AUTH_OBSERVER,
967 G_PARAM_CONSTRUCT_ONLY |
968 G_PARAM_STATIC_NAME |
969 G_PARAM_STATIC_BLURB |
970 G_PARAM_STATIC_NICK));
973 * GDBusConnection::closed:
974 * @connection: The #GDBusConnection emitting the signal.
975 * @remote_peer_vanished: %TRUE if @connection is closed because the
976 * remote peer closed its end of the connection.
977 * @error: A #GError with more details about the event or %NULL.
979 * Emitted when the connection is closed.
981 * The cause of this event can be
984 * If g_dbus_connection_close() is called. In this case
985 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
988 * If the remote peer closes the connection. In this case
989 * @remote_peer_vanished is set to %TRUE and @error is set.
992 * If the remote peer sends invalid or malformed data. In this
993 * case @remote_peer_vanished is set to %FALSE and @error
998 * Upon receiving this signal, you should give up your reference to
999 * @connection. You are guaranteed that this signal is emitted only
1004 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1005 G_TYPE_DBUS_CONNECTION,
1007 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1018 g_dbus_connection_init (GDBusConnection *connection)
1020 g_mutex_init (&connection->lock);
1021 g_mutex_init (&connection->init_lock);
1023 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1025 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1027 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1029 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1032 (GDestroyNotify) g_ptr_array_unref);
1034 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1037 (GDestroyNotify) exported_object_free);
1039 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1042 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1045 (GDestroyNotify) exported_subtree_free);
1047 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1050 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1052 connection->filters = g_ptr_array_new ();
1056 * g_dbus_connection_get_stream:
1057 * @connection: a #GDBusConnection
1059 * Gets the underlying stream used for IO.
1061 * While the #GDBusConnection is active, it will interact with this
1062 * stream from a worker thread, so it is not safe to interact with
1063 * the stream directly.
1065 * Returns: (transfer none): the stream used for IO
1070 g_dbus_connection_get_stream (GDBusConnection *connection)
1072 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1074 /* do not use g_return_val_if_fail(), we want the memory barrier */
1075 if (!check_initialized (connection))
1078 return connection->stream;
1082 * g_dbus_connection_start_message_processing:
1083 * @connection: A #GDBusConnection.
1085 * If @connection was created with
1086 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1087 * starts processing messages. Does nothing on if @connection wasn't
1088 * created with this flag or if the method has already been called.
1093 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1095 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1097 /* do not use g_return_val_if_fail(), we want the memory barrier */
1098 if (!check_initialized (connection))
1101 g_assert (connection->worker != NULL);
1102 _g_dbus_worker_unfreeze (connection->worker);
1106 * g_dbus_connection_is_closed:
1107 * @connection: A #GDBusConnection.
1109 * Gets whether @connection is closed.
1111 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1116 g_dbus_connection_is_closed (GDBusConnection *connection)
1118 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1119 return connection->closed;
1123 * g_dbus_connection_get_capabilities:
1124 * @connection: A #GDBusConnection.
1126 * Gets the capabilities negotiated with the remote peer
1128 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1132 GDBusCapabilityFlags
1133 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1135 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1137 /* do not use g_return_val_if_fail(), we want the memory barrier */
1138 if (!check_initialized (connection))
1139 return G_DBUS_CAPABILITY_FLAGS_NONE;
1141 return connection->capabilities;
1144 /* ---------------------------------------------------------------------------------------------------- */
1146 /* Called in a temporary thread without holding locks. */
1148 flush_in_thread_func (GSimpleAsyncResult *res,
1150 GCancellable *cancellable)
1155 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1158 g_simple_async_result_take_error (res, error);
1162 * g_dbus_connection_flush:
1163 * @connection: A #GDBusConnection.
1164 * @cancellable: A #GCancellable or %NULL.
1165 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1166 * satisfied or %NULL if you don't care about the result.
1167 * @user_data: The data to pass to @callback.
1169 * Asynchronously flushes @connection, that is, writes all queued
1170 * outgoing message to the transport and then flushes the transport
1171 * (using g_output_stream_flush_async()). This is useful in programs
1172 * that wants to emit a D-Bus signal and then exit
1173 * immediately. Without flushing the connection, there is no guarantee
1174 * that the message has been sent to the networking buffers in the OS
1177 * This is an asynchronous method. When the operation is finished,
1178 * @callback will be invoked in the <link
1179 * linkend="g-main-context-push-thread-default">thread-default main
1180 * loop</link> of the thread you are calling this method from. You can
1181 * then call g_dbus_connection_flush_finish() to get the result of the
1182 * operation. See g_dbus_connection_flush_sync() for the synchronous
1188 g_dbus_connection_flush (GDBusConnection *connection,
1189 GCancellable *cancellable,
1190 GAsyncReadyCallback callback,
1193 GSimpleAsyncResult *simple;
1195 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1197 simple = g_simple_async_result_new (G_OBJECT (connection),
1200 g_dbus_connection_flush);
1201 g_simple_async_result_run_in_thread (simple,
1202 flush_in_thread_func,
1205 g_object_unref (simple);
1209 * g_dbus_connection_flush_finish:
1210 * @connection: A #GDBusConnection.
1211 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1212 * @error: Return location for error or %NULL.
1214 * Finishes an operation started with g_dbus_connection_flush().
1216 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1221 g_dbus_connection_flush_finish (GDBusConnection *connection,
1225 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1230 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1231 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1232 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1234 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1236 if (g_simple_async_result_propagate_error (simple, error))
1246 * g_dbus_connection_flush_sync:
1247 * @connection: A #GDBusConnection.
1248 * @cancellable: A #GCancellable or %NULL.
1249 * @error: Return location for error or %NULL.
1251 * Synchronously flushes @connection. The calling thread is blocked
1252 * until this is done. See g_dbus_connection_flush() for the
1253 * asynchronous version of this method and more details about what it
1256 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1261 g_dbus_connection_flush_sync (GDBusConnection *connection,
1262 GCancellable *cancellable,
1267 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1268 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1272 /* do not use g_return_val_if_fail(), we want the memory barrier */
1273 if (!check_initialized (connection))
1276 g_assert (connection->worker != NULL);
1278 if (connection->closed)
1280 g_set_error_literal (error,
1283 _("The connection is closed"));
1287 ret = _g_dbus_worker_flush_sync (connection->worker,
1295 /* ---------------------------------------------------------------------------------------------------- */
1299 GDBusConnection *connection;
1301 gboolean remote_peer_vanished;
1305 emit_closed_data_free (EmitClosedData *data)
1307 g_object_unref (data->connection);
1308 if (data->error != NULL)
1309 g_error_free (data->error);
1313 /* Called in a user thread that has acquired the main context that was
1314 * thread-default when the object was constructed
1317 emit_closed_in_idle (gpointer user_data)
1319 EmitClosedData *data = user_data;
1322 g_object_notify (G_OBJECT (data->connection), "closed");
1323 g_signal_emit (data->connection,
1324 signals[CLOSED_SIGNAL],
1326 data->remote_peer_vanished,
1332 /* Can be called from any thread, must hold lock */
1334 set_closed_unlocked (GDBusConnection *connection,
1335 gboolean remote_peer_vanished,
1338 GSource *idle_source;
1339 EmitClosedData *data;
1341 CONNECTION_ENSURE_LOCK (connection);
1343 g_assert (!connection->closed);
1345 connection->closed = TRUE;
1347 data = g_new0 (EmitClosedData, 1);
1348 data->connection = g_object_ref (connection);
1349 data->remote_peer_vanished = remote_peer_vanished;
1350 data->error = error != NULL ? g_error_copy (error) : NULL;
1352 idle_source = g_idle_source_new ();
1353 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1354 g_source_set_callback (idle_source,
1355 emit_closed_in_idle,
1357 (GDestroyNotify) emit_closed_data_free);
1358 g_source_attach (idle_source, connection->main_context_at_construction);
1359 g_source_unref (idle_source);
1362 /* ---------------------------------------------------------------------------------------------------- */
1365 * g_dbus_connection_close:
1366 * @connection: A #GDBusConnection.
1367 * @cancellable: A #GCancellable or %NULL.
1368 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1369 * satisfied or %NULL if you don't care about the result.
1370 * @user_data: The data to pass to @callback.
1372 * Closes @connection. Note that this never causes the process to
1373 * exit (this might only happen if the other end of a shared message
1374 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1376 * Once the connection is closed, operations such as sending a message
1377 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1378 * will not automatically flush the connection so queued messages may
1379 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1381 * If @connection is already closed, this method fails with
1382 * %G_IO_ERROR_CLOSED.
1384 * When @connection has been closed, the #GDBusConnection::closed
1385 * signal is emitted in the <link
1386 * linkend="g-main-context-push-thread-default">thread-default main
1387 * loop</link> of the thread that @connection was constructed in.
1389 * This is an asynchronous method. When the operation is finished,
1390 * @callback will be invoked in the <link
1391 * linkend="g-main-context-push-thread-default">thread-default main
1392 * loop</link> of the thread you are calling this method from. You can
1393 * then call g_dbus_connection_close_finish() to get the result of the
1394 * operation. See g_dbus_connection_close_sync() for the synchronous
1400 g_dbus_connection_close (GDBusConnection *connection,
1401 GCancellable *cancellable,
1402 GAsyncReadyCallback callback,
1405 GSimpleAsyncResult *simple;
1407 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1409 /* do not use g_return_val_if_fail(), we want the memory barrier */
1410 if (!check_initialized (connection))
1413 g_assert (connection->worker != NULL);
1415 simple = g_simple_async_result_new (G_OBJECT (connection),
1418 g_dbus_connection_close);
1419 _g_dbus_worker_close (connection->worker, cancellable, simple);
1420 g_object_unref (simple);
1424 * g_dbus_connection_close_finish:
1425 * @connection: A #GDBusConnection.
1426 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1427 * @error: Return location for error or %NULL.
1429 * Finishes an operation started with g_dbus_connection_close().
1431 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1436 g_dbus_connection_close_finish (GDBusConnection *connection,
1440 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1445 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1446 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1447 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1449 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1451 if (g_simple_async_result_propagate_error (simple, error))
1462 GAsyncResult *result;
1465 /* Can be called by any thread, without the connection lock */
1467 sync_close_cb (GObject *source_object,
1471 SyncCloseData *data = user_data;
1473 data->result = g_object_ref (res);
1474 g_main_loop_quit (data->loop);
1478 * g_dbus_connection_close_sync:
1479 * @connection: A #GDBusConnection.
1480 * @cancellable: A #GCancellable or %NULL.
1481 * @error: Return location for error or %NULL.
1483 * Synchronously closees @connection. The calling thread is blocked
1484 * until this is done. See g_dbus_connection_close() for the
1485 * asynchronous version of this method and more details about what it
1488 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1493 g_dbus_connection_close_sync (GDBusConnection *connection,
1494 GCancellable *cancellable,
1499 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1500 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1504 CONNECTION_LOCK (connection);
1505 if (!connection->closed)
1507 GMainContext *context;
1510 context = g_main_context_new ();
1511 g_main_context_push_thread_default (context);
1512 data.loop = g_main_loop_new (context, TRUE);
1515 CONNECTION_UNLOCK (connection);
1516 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1517 g_main_loop_run (data.loop);
1518 ret = g_dbus_connection_close_finish (connection, data.result, error);
1519 CONNECTION_LOCK (connection);
1521 g_object_unref (data.result);
1522 g_main_loop_unref (data.loop);
1523 g_main_context_pop_thread_default (context);
1524 g_main_context_unref (context);
1528 g_set_error_literal (error,
1531 _("The connection is closed"));
1533 CONNECTION_UNLOCK (connection);
1538 /* ---------------------------------------------------------------------------------------------------- */
1540 /* Can be called by any thread, with the connection lock held */
1542 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1543 GDBusMessage *message,
1544 GDBusSendMessageFlags flags,
1545 volatile guint32 *out_serial,
1550 guint32 serial_to_use;
1553 CONNECTION_ENSURE_LOCK (connection);
1555 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1556 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1558 /* TODO: check all necessary headers are present */
1563 if (out_serial != NULL)
1566 /* If we're in initable_init(), don't check for being initialized, to avoid
1567 * chicken-and-egg problems. initable_init() is responsible for setting up
1568 * our prerequisites (mainly connection->worker), and only calling us
1569 * from its own thread (so no memory barrier is needed).
1571 * In the case where we're not initializing, do not use
1572 * g_return_val_if_fail() - we want the memory barrier.
1574 if ((flags & SEND_MESSAGE_FLAGS_INITIALIZING) == 0 &&
1575 !check_initialized (connection))
1578 if (connection->closed)
1580 g_set_error_literal (error,
1583 _("The connection is closed"));
1587 blob = g_dbus_message_to_blob (message,
1589 connection->capabilities,
1594 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1595 serial_to_use = g_dbus_message_get_serial (message);
1597 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1602 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1605 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1608 g_assert_not_reached ();
1613 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1614 blob_size, serial_to_use, connection);
1615 g_printerr ("----\n");
1616 hexdump (blob, blob_size);
1617 g_printerr ("----\n");
1620 /* TODO: use connection->auth to encode the blob */
1622 if (out_serial != NULL)
1623 *out_serial = serial_to_use;
1625 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1626 g_dbus_message_set_serial (message, serial_to_use);
1628 g_dbus_message_lock (message);
1629 _g_dbus_worker_send_message (connection->worker,
1633 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1644 * g_dbus_connection_send_message:
1645 * @connection: A #GDBusConnection.
1646 * @message: A #GDBusMessage
1647 * @flags: Flags affecting how the message is sent.
1648 * @out_serial: (out) (allow-none): Return location for serial number assigned
1649 * to @message when sending it or %NULL.
1650 * @error: Return location for error or %NULL.
1652 * Asynchronously sends @message to the peer represented by @connection.
1654 * Unless @flags contain the
1655 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1656 * will be assigned by @connection and set on @message via
1657 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1658 * serial number used will be written to this location prior to
1659 * submitting the message to the underlying transport.
1661 * If @connection is closed then the operation will fail with
1662 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1663 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1665 * See <xref linkend="gdbus-server"/> and <xref
1666 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1667 * low-level API to send and receive UNIX file descriptors.
1669 * Note that @message must be unlocked, unless @flags contain the
1670 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1672 * Returns: %TRUE if the message was well-formed and queued for
1673 * transmission, %FALSE if @error is set.
1678 g_dbus_connection_send_message (GDBusConnection *connection,
1679 GDBusMessage *message,
1680 GDBusSendMessageFlags flags,
1681 volatile guint32 *out_serial,
1686 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1687 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1688 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1689 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1691 CONNECTION_LOCK (connection);
1692 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1693 CONNECTION_UNLOCK (connection);
1697 /* ---------------------------------------------------------------------------------------------------- */
1701 volatile gint ref_count;
1702 GDBusConnection *connection;
1704 GSimpleAsyncResult *simple;
1706 GMainContext *main_context;
1708 GCancellable *cancellable;
1710 gulong cancellable_handler_id;
1712 GSource *timeout_source;
1717 /* Can be called from any thread with or without lock held */
1718 static SendMessageData *
1719 send_message_data_ref (SendMessageData *data)
1721 g_atomic_int_inc (&data->ref_count);
1725 /* Can be called from any thread with or without lock held */
1727 send_message_data_unref (SendMessageData *data)
1729 if (g_atomic_int_dec_and_test (&data->ref_count))
1731 g_assert (data->timeout_source == NULL);
1732 g_assert (data->simple == NULL);
1733 g_assert (data->cancellable_handler_id == 0);
1734 g_object_unref (data->connection);
1735 if (data->cancellable != NULL)
1736 g_object_unref (data->cancellable);
1737 g_main_context_unref (data->main_context);
1742 /* ---------------------------------------------------------------------------------------------------- */
1744 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1746 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1748 CONNECTION_ENSURE_LOCK (data->connection);
1750 g_assert (!data->delivered);
1752 data->delivered = TRUE;
1754 g_simple_async_result_complete_in_idle (data->simple);
1755 g_object_unref (data->simple);
1756 data->simple = NULL;
1758 if (data->timeout_source != NULL)
1760 g_source_destroy (data->timeout_source);
1761 data->timeout_source = NULL;
1763 if (data->cancellable_handler_id > 0)
1765 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1766 data->cancellable_handler_id = 0;
1771 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1772 GUINT_TO_POINTER (data->serial)));
1775 send_message_data_unref (data);
1778 /* ---------------------------------------------------------------------------------------------------- */
1780 /* Can be called from any thread with lock held */
1782 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1783 GDBusMessage *reply)
1785 if (data->delivered)
1788 g_simple_async_result_set_op_res_gpointer (data->simple,
1789 g_object_ref (reply),
1792 send_message_with_reply_deliver (data, TRUE);
1798 /* ---------------------------------------------------------------------------------------------------- */
1800 /* Called from a user thread, lock is not held */
1802 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1804 SendMessageData *data = user_data;
1806 CONNECTION_LOCK (data->connection);
1807 if (data->delivered)
1810 g_simple_async_result_set_error (data->simple,
1812 G_IO_ERROR_CANCELLED,
1813 _("Operation was cancelled"));
1815 send_message_with_reply_deliver (data, TRUE);
1818 CONNECTION_UNLOCK (data->connection);
1822 /* Can be called from any thread with or without lock held */
1824 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1827 SendMessageData *data = user_data;
1828 GSource *idle_source;
1830 /* postpone cancellation to idle handler since we may be called directly
1831 * via g_cancellable_connect() (e.g. holding lock)
1833 idle_source = g_idle_source_new ();
1834 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1835 g_source_set_callback (idle_source,
1836 send_message_with_reply_cancelled_idle_cb,
1837 send_message_data_ref (data),
1838 (GDestroyNotify) send_message_data_unref);
1839 g_source_attach (idle_source, data->main_context);
1840 g_source_unref (idle_source);
1843 /* ---------------------------------------------------------------------------------------------------- */
1845 /* Called from a user thread, lock is not held */
1847 send_message_with_reply_timeout_cb (gpointer user_data)
1849 SendMessageData *data = user_data;
1851 CONNECTION_LOCK (data->connection);
1852 if (data->delivered)
1855 g_simple_async_result_set_error (data->simple,
1857 G_IO_ERROR_TIMED_OUT,
1858 _("Timeout was reached"));
1860 send_message_with_reply_deliver (data, TRUE);
1863 CONNECTION_UNLOCK (data->connection);
1868 /* ---------------------------------------------------------------------------------------------------- */
1870 /* Called from a user thread, connection's lock is held */
1872 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1873 GDBusMessage *message,
1874 GDBusSendMessageFlags flags,
1876 volatile guint32 *out_serial,
1877 GCancellable *cancellable,
1878 GAsyncReadyCallback callback,
1881 GSimpleAsyncResult *simple;
1882 SendMessageData *data;
1884 volatile guint32 serial;
1888 if (out_serial == NULL)
1889 out_serial = &serial;
1891 if (timeout_msec == -1)
1892 timeout_msec = 25 * 1000;
1894 simple = g_simple_async_result_new (G_OBJECT (connection),
1897 g_dbus_connection_send_message_with_reply);
1899 if (g_cancellable_is_cancelled (cancellable))
1901 g_simple_async_result_set_error (simple,
1903 G_IO_ERROR_CANCELLED,
1904 _("Operation was cancelled"));
1905 g_simple_async_result_complete_in_idle (simple);
1906 g_object_unref (simple);
1910 if (connection->closed)
1912 g_simple_async_result_set_error (simple,
1915 _("The connection is closed"));
1916 g_simple_async_result_complete_in_idle (simple);
1917 g_object_unref (simple);
1922 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1924 g_simple_async_result_take_error (simple, error);
1925 g_simple_async_result_complete_in_idle (simple);
1926 g_object_unref (simple);
1930 data = g_new0 (SendMessageData, 1);
1931 data->ref_count = 1;
1932 data->connection = g_object_ref (connection);
1933 data->simple = simple;
1934 data->serial = *out_serial;
1935 data->main_context = g_main_context_ref_thread_default ();
1937 if (cancellable != NULL)
1939 data->cancellable = g_object_ref (cancellable);
1940 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1941 G_CALLBACK (send_message_with_reply_cancelled_cb),
1942 send_message_data_ref (data),
1943 (GDestroyNotify) send_message_data_unref);
1944 g_object_set_data_full (G_OBJECT (simple),
1946 g_object_ref (cancellable),
1947 (GDestroyNotify) g_object_unref);
1950 if (timeout_msec != G_MAXINT)
1952 data->timeout_source = g_timeout_source_new (timeout_msec);
1953 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1954 g_source_set_callback (data->timeout_source,
1955 send_message_with_reply_timeout_cb,
1956 send_message_data_ref (data),
1957 (GDestroyNotify) send_message_data_unref);
1958 g_source_attach (data->timeout_source, data->main_context);
1959 g_source_unref (data->timeout_source);
1962 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1963 GUINT_TO_POINTER (*out_serial),
1971 * g_dbus_connection_send_message_with_reply:
1972 * @connection: A #GDBusConnection.
1973 * @message: A #GDBusMessage.
1974 * @flags: Flags affecting how the message is sent.
1975 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1976 * timeout or %G_MAXINT for no timeout.
1977 * @out_serial: (out) (allow-none): Return location for serial number assigned
1978 * to @message when sending it or %NULL.
1979 * @cancellable: A #GCancellable or %NULL.
1980 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1981 * satisfied or %NULL if you don't care about the result.
1982 * @user_data: The data to pass to @callback.
1984 * Asynchronously sends @message to the peer represented by @connection.
1986 * Unless @flags contain the
1987 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1988 * will be assigned by @connection and set on @message via
1989 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1990 * serial number used will be written to this location prior to
1991 * submitting the message to the underlying transport.
1993 * If @connection is closed then the operation will fail with
1994 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1995 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1996 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1998 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1999 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2000 * of the thread you are calling this method from. You can then call
2001 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2002 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2004 * Note that @message must be unlocked, unless @flags contain the
2005 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2007 * See <xref linkend="gdbus-server"/> and <xref
2008 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2009 * low-level API to send and receive UNIX file descriptors.
2014 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2015 GDBusMessage *message,
2016 GDBusSendMessageFlags flags,
2018 volatile guint32 *out_serial,
2019 GCancellable *cancellable,
2020 GAsyncReadyCallback callback,
2023 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2024 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2025 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2026 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2028 CONNECTION_LOCK (connection);
2029 g_dbus_connection_send_message_with_reply_unlocked (connection,
2037 CONNECTION_UNLOCK (connection);
2041 * g_dbus_connection_send_message_with_reply_finish:
2042 * @connection: a #GDBusConnection
2043 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2044 * @error: Return location for error or %NULL.
2046 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2048 * Note that @error is only set if a local in-process error
2049 * occurred. That is to say that the returned #GDBusMessage object may
2050 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2051 * g_dbus_message_to_gerror() to transcode this to a #GError.
2053 * See <xref linkend="gdbus-server"/> and <xref
2054 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2055 * low-level API to send and receive UNIX file descriptors.
2057 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2062 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2066 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2067 GDBusMessage *reply;
2068 GCancellable *cancellable;
2070 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2071 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2075 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2077 if (g_simple_async_result_propagate_error (simple, error))
2080 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2081 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2082 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2084 g_object_unref (reply);
2086 g_set_error_literal (error,
2088 G_IO_ERROR_CANCELLED,
2089 _("Operation was cancelled"));
2095 /* ---------------------------------------------------------------------------------------------------- */
2100 GMainContext *context;
2102 } SendMessageSyncData;
2104 /* Called from a user thread, lock is not held */
2106 send_message_with_reply_sync_cb (GDBusConnection *connection,
2110 SendMessageSyncData *data = user_data;
2111 data->res = g_object_ref (res);
2112 g_main_loop_quit (data->loop);
2116 * g_dbus_connection_send_message_with_reply_sync:
2117 * @connection: A #GDBusConnection.
2118 * @message: A #GDBusMessage.
2119 * @flags: Flags affecting how the message is sent.
2120 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2121 * timeout or %G_MAXINT for no timeout.
2122 * @out_serial: (out) (allow-none): Return location for serial number assigned
2123 * to @message when sending it or %NULL.
2124 * @cancellable: A #GCancellable or %NULL.
2125 * @error: Return location for error or %NULL.
2127 * Synchronously sends @message to the peer represented by @connection
2128 * and blocks the calling thread until a reply is received or the
2129 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2130 * for the asynchronous version of this method.
2132 * Unless @flags contain the
2133 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2134 * will be assigned by @connection and set on @message via
2135 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2136 * serial number used will be written to this location prior to
2137 * submitting the message to the underlying transport.
2139 * If @connection is closed then the operation will fail with
2140 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2141 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2142 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2144 * Note that @error is only set if a local in-process error
2145 * occurred. That is to say that the returned #GDBusMessage object may
2146 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2147 * g_dbus_message_to_gerror() to transcode this to a #GError.
2149 * See <xref linkend="gdbus-server"/> and <xref
2150 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2151 * low-level API to send and receive UNIX file descriptors.
2153 * Note that @message must be unlocked, unless @flags contain the
2154 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2156 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2161 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2162 GDBusMessage *message,
2163 GDBusSendMessageFlags flags,
2165 volatile guint32 *out_serial,
2166 GCancellable *cancellable,
2169 SendMessageSyncData *data;
2170 GDBusMessage *reply;
2172 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2173 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2174 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2175 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2176 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2178 data = g_new0 (SendMessageSyncData, 1);
2179 data->context = g_main_context_new ();
2180 data->loop = g_main_loop_new (data->context, FALSE);
2182 g_main_context_push_thread_default (data->context);
2184 g_dbus_connection_send_message_with_reply (connection,
2190 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2192 g_main_loop_run (data->loop);
2193 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2197 g_main_context_pop_thread_default (data->context);
2199 g_main_context_unref (data->context);
2200 g_main_loop_unref (data->loop);
2201 g_object_unref (data->res);
2207 /* ---------------------------------------------------------------------------------------------------- */
2211 GDBusMessageFilterFunction func;
2218 GDBusMessageFilterFunction filter_function;
2220 GDestroyNotify user_data_free_func;
2223 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2225 on_worker_message_received (GDBusWorker *worker,
2226 GDBusMessage *message,
2229 GDBusConnection *connection;
2230 FilterCallback *filters;
2235 G_LOCK (message_bus_lock);
2236 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2239 G_UNLOCK (message_bus_lock);
2242 connection = G_DBUS_CONNECTION (user_data);
2243 g_object_ref (connection);
2244 G_UNLOCK (message_bus_lock);
2246 //g_debug ("in on_worker_message_received");
2248 g_object_ref (message);
2249 g_dbus_message_lock (message);
2251 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2253 /* First collect the set of callback functions */
2254 CONNECTION_LOCK (connection);
2255 num_filters = connection->filters->len;
2256 filters = g_new0 (FilterCallback, num_filters);
2257 for (n = 0; n < num_filters; n++)
2259 FilterData *data = connection->filters->pdata[n];
2260 filters[n].func = data->filter_function;
2261 filters[n].user_data = data->user_data;
2263 CONNECTION_UNLOCK (connection);
2265 /* then call the filters in order (without holding the lock) */
2266 for (n = 0; n < num_filters; n++)
2268 message = filters[n].func (connection,
2271 filters[n].user_data);
2272 if (message == NULL)
2274 g_dbus_message_lock (message);
2277 /* Standard dispatch unless the filter ate the message - no need to
2278 * do anything if the message was altered
2280 if (message != NULL)
2282 GDBusMessageType message_type;
2284 message_type = g_dbus_message_get_message_type (message);
2285 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2287 guint32 reply_serial;
2288 SendMessageData *send_message_data;
2290 reply_serial = g_dbus_message_get_reply_serial (message);
2291 CONNECTION_LOCK (connection);
2292 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2293 GUINT_TO_POINTER (reply_serial));
2294 if (send_message_data != NULL)
2296 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2297 send_message_data_deliver_reply_unlocked (send_message_data, message);
2301 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2303 CONNECTION_UNLOCK (connection);
2305 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2307 CONNECTION_LOCK (connection);
2308 distribute_signals (connection, message);
2309 CONNECTION_UNLOCK (connection);
2311 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2313 CONNECTION_LOCK (connection);
2314 distribute_method_call (connection, message);
2315 CONNECTION_UNLOCK (connection);
2319 if (message != NULL)
2320 g_object_unref (message);
2321 g_object_unref (connection);
2325 /* Called in GDBusWorker's thread, lock is not held */
2326 static GDBusMessage *
2327 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2328 GDBusMessage *message,
2331 GDBusConnection *connection;
2332 FilterCallback *filters;
2337 G_LOCK (message_bus_lock);
2338 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2341 G_UNLOCK (message_bus_lock);
2344 connection = G_DBUS_CONNECTION (user_data);
2345 g_object_ref (connection);
2346 G_UNLOCK (message_bus_lock);
2348 //g_debug ("in on_worker_message_about_to_be_sent");
2350 /* First collect the set of callback functions */
2351 CONNECTION_LOCK (connection);
2352 num_filters = connection->filters->len;
2353 filters = g_new0 (FilterCallback, num_filters);
2354 for (n = 0; n < num_filters; n++)
2356 FilterData *data = connection->filters->pdata[n];
2357 filters[n].func = data->filter_function;
2358 filters[n].user_data = data->user_data;
2360 CONNECTION_UNLOCK (connection);
2362 /* then call the filters in order (without holding the lock) */
2363 for (n = 0; n < num_filters; n++)
2365 g_dbus_message_lock (message);
2366 message = filters[n].func (connection,
2369 filters[n].user_data);
2370 if (message == NULL)
2374 g_object_unref (connection);
2380 /* called with connection lock held, in GDBusWorker thread */
2382 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2384 SendMessageData *data = value;
2386 if (data->delivered)
2389 g_simple_async_result_set_error (data->simple,
2392 _("The connection is closed"));
2394 /* Ask send_message_with_reply_deliver not to remove the element from the
2395 * hash table - we're in the middle of a foreach; that would be unsafe.
2396 * Instead, return TRUE from this function so that it gets removed safely.
2398 send_message_with_reply_deliver (data, FALSE);
2402 /* Called in GDBusWorker's thread - we must not block - without lock held */
2404 on_worker_closed (GDBusWorker *worker,
2405 gboolean remote_peer_vanished,
2409 GDBusConnection *connection;
2412 G_LOCK (message_bus_lock);
2413 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2416 G_UNLOCK (message_bus_lock);
2419 connection = G_DBUS_CONNECTION (user_data);
2420 g_object_ref (connection);
2421 G_UNLOCK (message_bus_lock);
2423 //g_debug ("in on_worker_closed: %s", error->message);
2425 CONNECTION_LOCK (connection);
2426 if (!connection->closed)
2428 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2429 set_closed_unlocked (connection, remote_peer_vanished, error);
2431 CONNECTION_UNLOCK (connection);
2433 g_object_unref (connection);
2436 /* ---------------------------------------------------------------------------------------------------- */
2438 /* Determines the biggest set of capabilities we can support on this
2441 * Called with the init_lock held.
2443 static GDBusCapabilityFlags
2444 get_offered_capabilities_max (GDBusConnection *connection)
2446 GDBusCapabilityFlags ret;
2447 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2449 if (G_IS_UNIX_CONNECTION (connection->stream))
2450 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2455 /* Called in a user thread, lock is not held */
2457 initable_init (GInitable *initable,
2458 GCancellable *cancellable,
2461 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2464 /* This method needs to be idempotent to work with the singleton
2465 * pattern. See the docs for g_initable_init(). We implement this by
2468 * Unfortunately we can't use the main lock since the on_worker_*()
2469 * callbacks above needs the lock during initialization (for message
2470 * bus connections we do a synchronous Hello() call on the bus).
2472 g_mutex_lock (&connection->init_lock);
2476 /* Make this a no-op if we're already initialized (successfully or
2479 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2481 ret = (connection->initialization_error == NULL);
2485 /* Because of init_lock, we can't get here twice in different threads */
2486 g_assert (connection->initialization_error == NULL);
2488 /* The user can pass multiple (but mutally exclusive) construct
2491 * - stream (of type GIOStream)
2492 * - address (of type gchar*)
2494 * At the end of the day we end up with a non-NULL GIOStream
2495 * object in connection->stream.
2497 if (connection->address != NULL)
2499 g_assert (connection->stream == NULL);
2501 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2502 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2504 g_set_error_literal (error,
2506 G_IO_ERROR_INVALID_ARGUMENT,
2507 _("Unsupported flags encountered when constructing a client-side connection"));
2511 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2512 NULL, /* TODO: out_guid */
2514 &connection->initialization_error);
2515 if (connection->stream == NULL)
2518 else if (connection->stream != NULL)
2524 g_assert_not_reached ();
2527 /* Authenticate the connection */
2528 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2530 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2531 g_assert (connection->guid != NULL);
2532 connection->auth = _g_dbus_auth_new (connection->stream);
2533 if (!_g_dbus_auth_run_server (connection->auth,
2534 connection->authentication_observer,
2536 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2537 get_offered_capabilities_max (connection),
2538 &connection->capabilities,
2539 &connection->credentials,
2541 &connection->initialization_error))
2544 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2546 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2547 g_assert (connection->guid == NULL);
2548 connection->auth = _g_dbus_auth_new (connection->stream);
2549 connection->guid = _g_dbus_auth_run_client (connection->auth,
2550 get_offered_capabilities_max (connection),
2551 &connection->capabilities,
2553 &connection->initialization_error);
2554 if (connection->guid == NULL)
2558 if (connection->authentication_observer != NULL)
2560 g_object_unref (connection->authentication_observer);
2561 connection->authentication_observer = NULL;
2564 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2566 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2569 /* We want all IO operations to be non-blocking since they happen in
2570 * the worker thread which is shared by _all_ connections.
2572 if (G_IS_SOCKET_CONNECTION (connection->stream))
2574 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2578 G_LOCK (message_bus_lock);
2579 if (alive_connections == NULL)
2580 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2581 g_hash_table_insert (alive_connections, connection, connection);
2582 G_UNLOCK (message_bus_lock);
2584 connection->worker = _g_dbus_worker_new (connection->stream,
2585 connection->capabilities,
2586 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2587 on_worker_message_received,
2588 on_worker_message_about_to_be_sent,
2592 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2593 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2595 GVariant *hello_result;
2597 /* we could lift this restriction by adding code in gdbusprivate.c */
2598 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2600 g_set_error_literal (&connection->initialization_error,
2603 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2607 hello_result = g_dbus_connection_call_sync (connection,
2608 "org.freedesktop.DBus", /* name */
2609 "/org/freedesktop/DBus", /* path */
2610 "org.freedesktop.DBus", /* interface */
2612 NULL, /* parameters */
2613 G_VARIANT_TYPE ("(s)"),
2614 CALL_FLAGS_INITIALIZING,
2616 NULL, /* TODO: cancellable */
2617 &connection->initialization_error);
2618 if (hello_result == NULL)
2621 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2622 g_variant_unref (hello_result);
2623 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2630 g_assert (connection->initialization_error != NULL);
2631 g_propagate_error (error, g_error_copy (connection->initialization_error));
2634 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2635 g_mutex_unlock (&connection->init_lock);
2641 initable_iface_init (GInitableIface *initable_iface)
2643 initable_iface->init = initable_init;
2646 /* ---------------------------------------------------------------------------------------------------- */
2649 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2654 /* ---------------------------------------------------------------------------------------------------- */
2657 * g_dbus_connection_new:
2658 * @stream: A #GIOStream.
2659 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2660 * @flags: Flags describing how to make the connection.
2661 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2662 * @cancellable: A #GCancellable or %NULL.
2663 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2664 * @user_data: The data to pass to @callback.
2666 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2667 * with the end represented by @stream.
2669 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2670 * will be put into non-blocking mode.
2672 * The D-Bus connection will interact with @stream from a worker thread.
2673 * As a result, the caller should not interact with @stream after this
2674 * method has been called, except by calling g_object_unref() on it.
2676 * If @observer is not %NULL it may be used to control the
2677 * authentication process.
2679 * When the operation is finished, @callback will be invoked. You can
2680 * then call g_dbus_connection_new_finish() to get the result of the
2683 * This is a asynchronous failable constructor. See
2684 * g_dbus_connection_new_sync() for the synchronous
2690 g_dbus_connection_new (GIOStream *stream,
2692 GDBusConnectionFlags flags,
2693 GDBusAuthObserver *observer,
2694 GCancellable *cancellable,
2695 GAsyncReadyCallback callback,
2698 g_return_if_fail (G_IS_IO_STREAM (stream));
2699 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2707 "authentication-observer", observer,
2712 * g_dbus_connection_new_finish:
2713 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2714 * @error: Return location for error or %NULL.
2716 * Finishes an operation started with g_dbus_connection_new().
2718 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2723 g_dbus_connection_new_finish (GAsyncResult *res,
2727 GObject *source_object;
2729 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2730 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2732 source_object = g_async_result_get_source_object (res);
2733 g_assert (source_object != NULL);
2734 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2737 g_object_unref (source_object);
2739 return G_DBUS_CONNECTION (object);
2745 * g_dbus_connection_new_sync:
2746 * @stream: A #GIOStream.
2747 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2748 * @flags: Flags describing how to make the connection.
2749 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2750 * @cancellable: A #GCancellable or %NULL.
2751 * @error: Return location for error or %NULL.
2753 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2754 * with the end represented by @stream.
2756 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2757 * will be put into non-blocking mode.
2759 * The D-Bus connection will interact with @stream from a worker thread.
2760 * As a result, the caller should not interact with @stream after this
2761 * method has been called, except by calling g_object_unref() on it.
2763 * If @observer is not %NULL it may be used to control the
2764 * authentication process.
2766 * This is a synchronous failable constructor. See
2767 * g_dbus_connection_new() for the asynchronous version.
2769 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2774 g_dbus_connection_new_sync (GIOStream *stream,
2776 GDBusConnectionFlags flags,
2777 GDBusAuthObserver *observer,
2778 GCancellable *cancellable,
2781 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2782 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2783 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2789 "authentication-observer", observer,
2793 /* ---------------------------------------------------------------------------------------------------- */
2796 * g_dbus_connection_new_for_address:
2797 * @address: A D-Bus address.
2798 * @flags: Flags describing how to make the connection.
2799 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2800 * @cancellable: A #GCancellable or %NULL.
2801 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2802 * @user_data: The data to pass to @callback.
2804 * Asynchronously connects and sets up a D-Bus client connection for
2805 * exchanging D-Bus messages with an endpoint specified by @address
2806 * which must be in the D-Bus address format.
2808 * This constructor can only be used to initiate client-side
2809 * connections - use g_dbus_connection_new() if you need to act as the
2810 * server. In particular, @flags cannot contain the
2811 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2812 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2814 * When the operation is finished, @callback will be invoked. You can
2815 * then call g_dbus_connection_new_finish() to get the result of the
2818 * If @observer is not %NULL it may be used to control the
2819 * authentication process.
2821 * This is a asynchronous failable constructor. See
2822 * g_dbus_connection_new_for_address_sync() for the synchronous
2828 g_dbus_connection_new_for_address (const gchar *address,
2829 GDBusConnectionFlags flags,
2830 GDBusAuthObserver *observer,
2831 GCancellable *cancellable,
2832 GAsyncReadyCallback callback,
2835 g_return_if_fail (address != NULL);
2836 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2843 "authentication-observer", observer,
2848 * g_dbus_connection_new_for_address_finish:
2849 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2850 * @error: Return location for error or %NULL.
2852 * Finishes an operation started with g_dbus_connection_new_for_address().
2854 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2859 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2863 GObject *source_object;
2865 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2866 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2868 source_object = g_async_result_get_source_object (res);
2869 g_assert (source_object != NULL);
2870 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2873 g_object_unref (source_object);
2875 return G_DBUS_CONNECTION (object);
2881 * g_dbus_connection_new_for_address_sync:
2882 * @address: A D-Bus address.
2883 * @flags: Flags describing how to make the connection.
2884 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2885 * @cancellable: A #GCancellable or %NULL.
2886 * @error: Return location for error or %NULL.
2888 * Synchronously connects and sets up a D-Bus client connection for
2889 * exchanging D-Bus messages with an endpoint specified by @address
2890 * which must be in the D-Bus address format.
2892 * This constructor can only be used to initiate client-side
2893 * connections - use g_dbus_connection_new_sync() if you need to act
2894 * as the server. In particular, @flags cannot contain the
2895 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2896 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2898 * This is a synchronous failable constructor. See
2899 * g_dbus_connection_new_for_address() for the asynchronous version.
2901 * If @observer is not %NULL it may be used to control the
2902 * authentication process.
2904 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2909 g_dbus_connection_new_for_address_sync (const gchar *address,
2910 GDBusConnectionFlags flags,
2911 GDBusAuthObserver *observer,
2912 GCancellable *cancellable,
2915 g_return_val_if_fail (address != NULL, NULL);
2916 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2917 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2922 "authentication-observer", observer,
2926 /* ---------------------------------------------------------------------------------------------------- */
2929 * g_dbus_connection_set_exit_on_close:
2930 * @connection: A #GDBusConnection.
2931 * @exit_on_close: Whether the process should be terminated
2932 * when @connection is closed by the remote peer.
2934 * Sets whether the process should be terminated when @connection is
2935 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2938 * Note that this function should be used with care. Most modern UNIX
2939 * desktops tie the notion of a user session the session bus, and expect
2940 * all of a users applications to quit when their bus connection goes away.
2941 * If you are setting @exit_on_close to %FALSE for the shared session
2942 * bus connection, you should make sure that your application exits
2943 * when the user session ends.
2948 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2949 gboolean exit_on_close)
2951 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2954 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2956 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2961 * g_dbus_connection_get_exit_on_close:
2962 * @connection: A #GDBusConnection.
2964 * Gets whether the process is terminated when @connection is
2965 * closed by the remote peer. See
2966 * #GDBusConnection:exit-on-close for more details.
2968 * Returns: Whether the process is terminated when @connection is
2969 * closed by the remote peer.
2974 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2976 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2978 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
2985 * g_dbus_connection_get_guid:
2986 * @connection: A #GDBusConnection.
2988 * The GUID of the peer performing the role of server when
2989 * authenticating. See #GDBusConnection:guid for more details.
2991 * Returns: The GUID. Do not free this string, it is owned by
2997 g_dbus_connection_get_guid (GDBusConnection *connection)
2999 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3000 return connection->guid;
3004 * g_dbus_connection_get_unique_name:
3005 * @connection: A #GDBusConnection.
3007 * Gets the unique name of @connection as assigned by the message
3008 * bus. This can also be used to figure out if @connection is a
3009 * message bus connection.
3011 * Returns: The unique name or %NULL if @connection is not a message
3012 * bus connection. Do not free this string, it is owned by
3018 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3020 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3022 /* do not use g_return_val_if_fail(), we want the memory barrier */
3023 if (!check_initialized (connection))
3026 return connection->bus_unique_name;
3030 * g_dbus_connection_get_peer_credentials:
3031 * @connection: A #GDBusConnection.
3033 * Gets the credentials of the authenticated peer. This will always
3034 * return %NULL unless @connection acted as a server
3035 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3036 * when set up and the client passed credentials as part of the
3037 * authentication process.
3039 * In a message bus setup, the message bus is always the server and
3040 * each application is a client. So this method will always return
3041 * %NULL for message bus clients.
3043 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3044 * this object, it is owned by @connection.
3049 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3051 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3053 /* do not use g_return_val_if_fail(), we want the memory barrier */
3054 if (!check_initialized (connection))
3057 return connection->credentials;
3060 /* ---------------------------------------------------------------------------------------------------- */
3062 static guint _global_filter_id = 1;
3065 * g_dbus_connection_add_filter:
3066 * @connection: A #GDBusConnection.
3067 * @filter_function: A filter function.
3068 * @user_data: User data to pass to @filter_function.
3069 * @user_data_free_func: Function to free @user_data with when filter
3070 * is removed or %NULL.
3072 * Adds a message filter. Filters are handlers that are run on all
3073 * incoming and outgoing messages, prior to standard dispatch. Filters
3074 * are run in the order that they were added. The same handler can be
3075 * added as a filter more than once, in which case it will be run more
3076 * than once. Filters added during a filter callback won't be run on
3077 * the message being processed. Filter functions are allowed to modify
3078 * and even drop messages.
3080 * Note that filters are run in a dedicated message handling thread so
3081 * they can't block and, generally, can't do anything but signal a
3082 * worker thread. Also note that filters are rarely needed - use API
3083 * such as g_dbus_connection_send_message_with_reply(),
3084 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3086 * If a filter consumes an incoming message the message is not
3087 * dispatched anywhere else - not even the standard dispatch machinery
3088 * (that API such as g_dbus_connection_signal_subscribe() and
3089 * g_dbus_connection_send_message_with_reply() relies on) will see the
3090 * message. Similary, if a filter consumes an outgoing message, the
3091 * message will not be sent to the other peer.
3093 * Returns: A filter identifier that can be used with
3094 * g_dbus_connection_remove_filter().
3099 g_dbus_connection_add_filter (GDBusConnection *connection,
3100 GDBusMessageFilterFunction filter_function,
3102 GDestroyNotify user_data_free_func)
3106 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3107 g_return_val_if_fail (filter_function != NULL, 0);
3108 g_return_val_if_fail (check_initialized (connection), 0);
3110 CONNECTION_LOCK (connection);
3111 data = g_new0 (FilterData, 1);
3112 data->id = _global_filter_id++; /* TODO: overflow etc. */
3113 data->filter_function = filter_function;
3114 data->user_data = user_data;
3115 data->user_data_free_func = user_data_free_func;
3116 g_ptr_array_add (connection->filters, data);
3117 CONNECTION_UNLOCK (connection);
3122 /* only called from finalize(), removes all filters */
3124 purge_all_filters (GDBusConnection *connection)
3127 for (n = 0; n < connection->filters->len; n++)
3129 FilterData *data = connection->filters->pdata[n];
3130 if (data->user_data_free_func != NULL)
3131 data->user_data_free_func (data->user_data);
3137 * g_dbus_connection_remove_filter:
3138 * @connection: a #GDBusConnection
3139 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3146 g_dbus_connection_remove_filter (GDBusConnection *connection,
3150 FilterData *to_destroy;
3152 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3153 g_return_if_fail (check_initialized (connection));
3155 CONNECTION_LOCK (connection);
3157 for (n = 0; n < connection->filters->len; n++)
3159 FilterData *data = connection->filters->pdata[n];
3160 if (data->id == filter_id)
3162 g_ptr_array_remove_index (connection->filters, n);
3167 CONNECTION_UNLOCK (connection);
3169 /* do free without holding lock */
3170 if (to_destroy != NULL)
3172 if (to_destroy->user_data_free_func != NULL)
3173 to_destroy->user_data_free_func (to_destroy->user_data);
3174 g_free (to_destroy);
3178 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3182 /* ---------------------------------------------------------------------------------------------------- */
3188 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3189 gchar *interface_name;
3193 GArray *subscribers;
3198 GDBusSignalCallback callback;
3200 GDestroyNotify user_data_free_func;
3202 GMainContext *context;
3206 signal_data_free (SignalData *signal_data)
3208 g_free (signal_data->rule);
3209 g_free (signal_data->sender);
3210 g_free (signal_data->sender_unique_name);
3211 g_free (signal_data->interface_name);
3212 g_free (signal_data->member);
3213 g_free (signal_data->object_path);
3214 g_free (signal_data->arg0);
3215 g_array_free (signal_data->subscribers, TRUE);
3216 g_free (signal_data);
3220 args_to_rule (const gchar *sender,
3221 const gchar *interface_name,
3222 const gchar *member,
3223 const gchar *object_path,
3229 rule = g_string_new ("type='signal'");
3231 g_string_prepend_c (rule, '-');
3233 g_string_append_printf (rule, ",sender='%s'", sender);
3234 if (interface_name != NULL)
3235 g_string_append_printf (rule, ",interface='%s'", interface_name);
3237 g_string_append_printf (rule, ",member='%s'", member);
3238 if (object_path != NULL)
3239 g_string_append_printf (rule, ",path='%s'", object_path);
3241 g_string_append_printf (rule, ",arg0='%s'", arg0);
3243 return g_string_free (rule, FALSE);
3246 static guint _global_subscriber_id = 1;
3247 static guint _global_registration_id = 1;
3248 static guint _global_subtree_registration_id = 1;
3250 /* ---------------------------------------------------------------------------------------------------- */
3252 /* Called in a user thread, lock is held */
3254 add_match_rule (GDBusConnection *connection,
3255 const gchar *match_rule)
3258 GDBusMessage *message;
3260 if (match_rule[0] == '-')
3263 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3264 "/org/freedesktop/DBus", /* path */
3265 "org.freedesktop.DBus", /* interface */
3267 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3269 if (!g_dbus_connection_send_message_unlocked (connection,
3271 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3275 g_critical ("Error while sending AddMatch() message: %s", error->message);
3276 g_error_free (error);
3278 g_object_unref (message);
3281 /* ---------------------------------------------------------------------------------------------------- */
3283 /* Called in a user thread, lock is held */
3285 remove_match_rule (GDBusConnection *connection,
3286 const gchar *match_rule)
3289 GDBusMessage *message;
3291 if (match_rule[0] == '-')
3294 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3295 "/org/freedesktop/DBus", /* path */
3296 "org.freedesktop.DBus", /* interface */
3298 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3301 if (!g_dbus_connection_send_message_unlocked (connection,
3303 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3307 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3308 g_error_free (error);
3310 g_object_unref (message);
3313 /* ---------------------------------------------------------------------------------------------------- */
3316 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3318 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3319 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3320 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3321 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3322 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3325 /* ---------------------------------------------------------------------------------------------------- */
3328 * g_dbus_connection_signal_subscribe:
3329 * @connection: A #GDBusConnection.
3330 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3331 * or %NULL to listen from all senders.
3332 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3333 * match on all interfaces.
3334 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3335 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3336 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3337 * to match on all kinds of arguments.
3338 * @flags: Flags describing how to subscribe to the signal (currently unused).
3339 * @callback: Callback to invoke when there is a signal matching the requested data.
3340 * @user_data: User data to pass to @callback.
3341 * @user_data_free_func: (allow-none): Function to free @user_data with when
3342 * subscription is removed or %NULL.
3344 * Subscribes to signals on @connection and invokes @callback with a
3345 * whenever the signal is received. Note that @callback
3346 * will be invoked in the <link
3347 * linkend="g-main-context-push-thread-default">thread-default main
3348 * loop</link> of the thread you are calling this method from.
3350 * If @connection is not a message bus connection, @sender must be
3353 * If @sender is a well-known name note that @callback is invoked with
3354 * the unique name for the owner of @sender, not the well-known name
3355 * as one would expect. This is because the message bus rewrites the
3356 * name. As such, to avoid certain race conditions, users should be
3357 * tracking the name owner of the well-known name and use that when
3358 * processing the received signal.
3360 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3365 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3366 const gchar *sender,
3367 const gchar *interface_name,
3368 const gchar *member,
3369 const gchar *object_path,
3371 GDBusSignalFlags flags,
3372 GDBusSignalCallback callback,
3374 GDestroyNotify user_data_free_func)
3377 SignalData *signal_data;
3378 SignalSubscriber subscriber;
3379 GPtrArray *signal_data_array;
3380 const gchar *sender_unique_name;
3382 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3383 * an OOM condition. We might want to change that but that would involve making
3384 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3385 * handle that. And there's really no sensible way of handling this short of retrying
3386 * to add the match rule... and then there's the little thing that, hey, maybe there's
3387 * a reason the bus in an OOM condition.
3389 * Doable, but not really sure it's worth it...
3392 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3393 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3394 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3395 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3396 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3397 g_return_val_if_fail (callback != NULL, 0);
3398 g_return_val_if_fail (check_initialized (connection), 0);
3400 CONNECTION_LOCK (connection);
3402 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3403 * with a '-' character to prefix the rule (which will otherwise be
3406 * This allows us to hash the rule and do our lifecycle tracking in
3407 * the usual way, but the '-' prevents the match rule from ever
3408 * actually being send to the bus (either for add or remove).
3410 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3411 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3413 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3414 sender_unique_name = sender;
3416 sender_unique_name = "";
3418 subscriber.callback = callback;
3419 subscriber.user_data = user_data;
3420 subscriber.user_data_free_func = user_data_free_func;
3421 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3422 subscriber.context = g_main_context_ref_thread_default ();
3424 /* see if we've already have this rule */
3425 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3426 if (signal_data != NULL)
3428 g_array_append_val (signal_data->subscribers, subscriber);
3433 signal_data = g_new0 (SignalData, 1);
3434 signal_data->rule = rule;
3435 signal_data->sender = g_strdup (sender);
3436 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3437 signal_data->interface_name = g_strdup (interface_name);
3438 signal_data->member = g_strdup (member);
3439 signal_data->object_path = g_strdup (object_path);
3440 signal_data->arg0 = g_strdup (arg0);
3441 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3442 g_array_append_val (signal_data->subscribers, subscriber);
3444 g_hash_table_insert (connection->map_rule_to_signal_data,
3448 /* Add the match rule to the bus...
3450 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3451 * always send such messages to us.
3453 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3455 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3456 add_match_rule (connection, signal_data->rule);
3459 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3460 signal_data->sender_unique_name);
3461 if (signal_data_array == NULL)
3463 signal_data_array = g_ptr_array_new ();
3464 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3465 g_strdup (signal_data->sender_unique_name),
3468 g_ptr_array_add (signal_data_array, signal_data);
3471 g_hash_table_insert (connection->map_id_to_signal_data,
3472 GUINT_TO_POINTER (subscriber.id),
3475 CONNECTION_UNLOCK (connection);
3477 return subscriber.id;
3480 /* ---------------------------------------------------------------------------------------------------- */
3482 /* called in any thread */
3483 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3485 unsubscribe_id_internal (GDBusConnection *connection,
3486 guint subscription_id,
3487 GArray *out_removed_subscribers)
3489 SignalData *signal_data;
3490 GPtrArray *signal_data_array;
3493 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3494 GUINT_TO_POINTER (subscription_id));
3495 if (signal_data == NULL)
3497 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3501 for (n = 0; n < signal_data->subscribers->len; n++)
3503 SignalSubscriber *subscriber;
3505 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3506 if (subscriber->id != subscription_id)
3509 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3510 GUINT_TO_POINTER (subscription_id)));
3511 g_array_append_val (out_removed_subscribers, *subscriber);
3512 g_array_remove_index (signal_data->subscribers, n);
3514 if (signal_data->subscribers->len == 0)
3516 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3518 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3519 signal_data->sender_unique_name);
3520 g_warn_if_fail (signal_data_array != NULL);
3521 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3523 if (signal_data_array->len == 0)
3525 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3526 signal_data->sender_unique_name));
3529 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3530 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3532 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3533 if (!connection->closed && !connection->finalizing)
3534 remove_match_rule (connection, signal_data->rule);
3536 signal_data_free (signal_data);
3542 g_assert_not_reached ();
3549 * g_dbus_connection_signal_unsubscribe:
3550 * @connection: A #GDBusConnection.
3551 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3553 * Unsubscribes from signals.
3558 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3559 guint subscription_id)
3561 GArray *subscribers;
3564 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3565 g_return_if_fail (check_initialized (connection));
3567 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3569 CONNECTION_LOCK (connection);
3570 unsubscribe_id_internal (connection,
3573 CONNECTION_UNLOCK (connection);
3576 g_assert (subscribers->len == 0 || subscribers->len == 1);
3578 /* call GDestroyNotify without lock held */
3579 for (n = 0; n < subscribers->len; n++)
3581 SignalSubscriber *subscriber;
3582 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3583 call_destroy_notify (subscriber->context,
3584 subscriber->user_data_free_func,
3585 subscriber->user_data);
3586 g_main_context_unref (subscriber->context);
3589 g_array_free (subscribers, TRUE);
3592 /* ---------------------------------------------------------------------------------------------------- */
3596 guint subscription_id;
3597 GDBusSignalCallback callback;
3599 GDBusMessage *message;
3600 GDBusConnection *connection;
3601 const gchar *sender;
3603 const gchar *interface;
3604 const gchar *member;
3607 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3611 emit_signal_instance_in_idle_cb (gpointer data)
3613 SignalInstance *signal_instance = data;
3614 GVariant *parameters;
3615 gboolean has_subscription;
3617 parameters = g_dbus_message_get_body (signal_instance->message);
3618 if (parameters == NULL)
3620 parameters = g_variant_new ("()");
3621 g_variant_ref_sink (parameters);
3625 g_variant_ref_sink (parameters);
3629 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3630 signal_instance->subscription_id,
3631 signal_instance->sender,
3632 signal_instance->path,
3633 signal_instance->interface,
3634 signal_instance->member,
3635 g_variant_print (parameters, TRUE));
3638 /* Careful here, don't do the callback if we no longer has the subscription */
3639 CONNECTION_LOCK (signal_instance->connection);
3640 has_subscription = FALSE;
3641 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3642 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3643 has_subscription = TRUE;
3644 CONNECTION_UNLOCK (signal_instance->connection);
3646 if (has_subscription)
3647 signal_instance->callback (signal_instance->connection,
3648 signal_instance->sender,
3649 signal_instance->path,
3650 signal_instance->interface,
3651 signal_instance->member,
3653 signal_instance->user_data);
3655 g_variant_unref (parameters);
3661 signal_instance_free (SignalInstance *signal_instance)
3663 g_object_unref (signal_instance->message);
3664 g_object_unref (signal_instance->connection);
3665 g_free (signal_instance);
3668 /* called in GDBusWorker thread WITH lock held */
3670 schedule_callbacks (GDBusConnection *connection,
3671 GPtrArray *signal_data_array,
3672 GDBusMessage *message,
3673 const gchar *sender)
3676 const gchar *interface;
3677 const gchar *member;
3686 interface = g_dbus_message_get_interface (message);
3687 member = g_dbus_message_get_member (message);
3688 path = g_dbus_message_get_path (message);
3689 arg0 = g_dbus_message_get_arg0 (message);
3692 g_print ("In schedule_callbacks:\n"
3694 " interface = `%s'\n"
3705 /* TODO: if this is slow, then we can change signal_data_array into
3706 * map_object_path_to_signal_data_array or something.
3708 for (n = 0; n < signal_data_array->len; n++)
3710 SignalData *signal_data = signal_data_array->pdata[n];
3712 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3715 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3718 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3721 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3724 for (m = 0; m < signal_data->subscribers->len; m++)
3726 SignalSubscriber *subscriber;
3727 GSource *idle_source;
3728 SignalInstance *signal_instance;
3730 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3732 signal_instance = g_new0 (SignalInstance, 1);
3733 signal_instance->subscription_id = subscriber->id;
3734 signal_instance->callback = subscriber->callback;
3735 signal_instance->user_data = subscriber->user_data;
3736 signal_instance->message = g_object_ref (message);
3737 signal_instance->connection = g_object_ref (connection);
3738 signal_instance->sender = sender;
3739 signal_instance->path = path;
3740 signal_instance->interface = interface;
3741 signal_instance->member = member;
3743 idle_source = g_idle_source_new ();
3744 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3745 g_source_set_callback (idle_source,
3746 emit_signal_instance_in_idle_cb,
3748 (GDestroyNotify) signal_instance_free);
3749 g_source_attach (idle_source, subscriber->context);
3750 g_source_unref (idle_source);
3755 /* called in GDBusWorker thread with lock held */
3757 distribute_signals (GDBusConnection *connection,
3758 GDBusMessage *message)
3760 GPtrArray *signal_data_array;
3761 const gchar *sender;
3763 sender = g_dbus_message_get_sender (message);
3765 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3767 _g_dbus_debug_print_lock ();
3768 g_print ("========================================================================\n"
3769 "GDBus-debug:Signal:\n"
3770 " <<<< RECEIVED SIGNAL %s.%s\n"
3772 " sent by name %s\n",
3773 g_dbus_message_get_interface (message),
3774 g_dbus_message_get_member (message),
3775 g_dbus_message_get_path (message),
3776 sender != NULL ? sender : "(none)");
3777 _g_dbus_debug_print_unlock ();
3780 /* collect subscribers that match on sender */
3783 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3784 if (signal_data_array != NULL)
3785 schedule_callbacks (connection, signal_data_array, message, sender);
3788 /* collect subscribers not matching on sender */
3789 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3790 if (signal_data_array != NULL)
3791 schedule_callbacks (connection, signal_data_array, message, sender);
3794 /* ---------------------------------------------------------------------------------------------------- */
3796 /* only called from finalize(), removes all subscriptions */
3798 purge_all_signal_subscriptions (GDBusConnection *connection)
3800 GHashTableIter iter;
3803 GArray *subscribers;
3806 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3807 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3808 while (g_hash_table_iter_next (&iter, &key, NULL))
3810 guint subscription_id = GPOINTER_TO_UINT (key);
3811 g_array_append_val (ids, subscription_id);
3814 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3815 for (n = 0; n < ids->len; n++)
3817 guint subscription_id = g_array_index (ids, guint, n);
3818 unsubscribe_id_internal (connection,
3822 g_array_free (ids, TRUE);
3824 /* call GDestroyNotify without lock held */
3825 for (n = 0; n < subscribers->len; n++)
3827 SignalSubscriber *subscriber;
3828 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3829 call_destroy_notify (subscriber->context,
3830 subscriber->user_data_free_func,
3831 subscriber->user_data);
3832 g_main_context_unref (subscriber->context);
3835 g_array_free (subscribers, TRUE);
3838 /* ---------------------------------------------------------------------------------------------------- */
3840 static GDBusInterfaceVTable *
3841 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3843 /* Don't waste memory by copying padding - remember to update this
3844 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3846 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3850 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3855 /* ---------------------------------------------------------------------------------------------------- */
3857 static GDBusSubtreeVTable *
3858 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3860 /* Don't waste memory by copying padding - remember to update this
3861 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3863 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3867 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3872 /* ---------------------------------------------------------------------------------------------------- */
3874 struct ExportedObject
3877 GDBusConnection *connection;
3879 /* maps gchar* -> ExportedInterface* */
3880 GHashTable *map_if_name_to_ei;
3883 /* only called with lock held */
3885 exported_object_free (ExportedObject *eo)
3887 g_free (eo->object_path);
3888 g_hash_table_unref (eo->map_if_name_to_ei);
3897 gchar *interface_name;
3898 GDBusInterfaceVTable *vtable;
3899 GDBusInterfaceInfo *interface_info;
3901 GMainContext *context;
3903 GDestroyNotify user_data_free_func;
3904 } ExportedInterface;
3906 /* called with lock held */
3908 exported_interface_free (ExportedInterface *ei)
3910 g_dbus_interface_info_cache_release (ei->interface_info);
3911 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3913 call_destroy_notify (ei->context,
3914 ei->user_data_free_func,
3917 g_main_context_unref (ei->context);
3919 g_free (ei->interface_name);
3920 _g_dbus_interface_vtable_free (ei->vtable);
3924 /* ---------------------------------------------------------------------------------------------------- */
3926 /* Convenience function to check if @registration_id (if not zero) or
3927 * @subtree_registration_id (if not zero) has been unregistered. If
3928 * so, returns %TRUE.
3930 * May be called by any thread. Caller must *not* hold lock.
3933 has_object_been_unregistered (GDBusConnection *connection,
3934 guint registration_id,
3935 guint subtree_registration_id)
3939 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3943 CONNECTION_LOCK (connection);
3944 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3945 GUINT_TO_POINTER (registration_id)) == NULL)
3949 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3950 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3954 CONNECTION_UNLOCK (connection);
3959 /* ---------------------------------------------------------------------------------------------------- */
3963 GDBusConnection *connection;
3964 GDBusMessage *message;
3966 const gchar *property_name;
3967 const GDBusInterfaceVTable *vtable;
3968 GDBusInterfaceInfo *interface_info;
3969 const GDBusPropertyInfo *property_info;
3970 guint registration_id;
3971 guint subtree_registration_id;
3975 property_data_free (PropertyData *data)
3977 g_object_unref (data->connection);
3978 g_object_unref (data->message);
3982 /* called in thread where object was registered - no locks held */
3984 invoke_get_property_in_idle_cb (gpointer _data)
3986 PropertyData *data = _data;
3989 GDBusMessage *reply;
3991 if (has_object_been_unregistered (data->connection,
3992 data->registration_id,
3993 data->subtree_registration_id))
3995 reply = g_dbus_message_new_method_error (data->message,
3996 "org.freedesktop.DBus.Error.UnknownMethod",
3997 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3998 g_dbus_message_get_path (data->message));
3999 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4000 g_object_unref (reply);
4005 value = data->vtable->get_property (data->connection,
4006 g_dbus_message_get_sender (data->message),
4007 g_dbus_message_get_path (data->message),
4008 data->interface_info->name,
4009 data->property_name,
4016 g_assert_no_error (error);
4018 g_variant_take_ref (value);
4019 reply = g_dbus_message_new_method_reply (data->message);
4020 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4021 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4022 g_variant_unref (value);
4023 g_object_unref (reply);
4027 gchar *dbus_error_name;
4028 g_assert (error != NULL);
4029 dbus_error_name = g_dbus_error_encode_gerror (error);
4030 reply = g_dbus_message_new_method_error_literal (data->message,
4033 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4034 g_free (dbus_error_name);
4035 g_error_free (error);
4036 g_object_unref (reply);
4043 /* called in thread where object was registered - no locks held */
4045 invoke_set_property_in_idle_cb (gpointer _data)
4047 PropertyData *data = _data;
4049 GDBusMessage *reply;
4055 g_variant_get (g_dbus_message_get_body (data->message),
4061 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4062 * of the given value is wrong
4064 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4066 reply = g_dbus_message_new_method_error (data->message,
4067 "org.freedesktop.DBus.Error.InvalidArgs",
4068 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4069 data->property_info->name,
4070 data->property_info->signature,
4071 g_variant_get_type_string (value));
4075 if (!data->vtable->set_property (data->connection,
4076 g_dbus_message_get_sender (data->message),
4077 g_dbus_message_get_path (data->message),
4078 data->interface_info->name,
4079 data->property_name,
4084 gchar *dbus_error_name;
4085 g_assert (error != NULL);
4086 dbus_error_name = g_dbus_error_encode_gerror (error);
4087 reply = g_dbus_message_new_method_error_literal (data->message,
4090 g_free (dbus_error_name);
4091 g_error_free (error);
4095 reply = g_dbus_message_new_method_reply (data->message);
4099 g_assert (reply != NULL);
4100 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4101 g_object_unref (reply);
4102 g_variant_unref (value);
4107 /* called in any thread with connection's lock held */
4109 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4110 GDBusMessage *message,
4111 guint registration_id,
4112 guint subtree_registration_id,
4114 GDBusInterfaceInfo *interface_info,
4115 const GDBusInterfaceVTable *vtable,
4116 GMainContext *main_context,
4120 const char *interface_name;
4121 const char *property_name;
4122 const GDBusPropertyInfo *property_info;
4123 GSource *idle_source;
4124 PropertyData *property_data;
4125 GDBusMessage *reply;
4130 g_variant_get (g_dbus_message_get_body (message),
4135 g_variant_get (g_dbus_message_get_body (message),
4144 if (vtable == NULL || vtable->get_property == NULL)
4149 if (vtable == NULL || vtable->set_property == NULL)
4153 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4155 property_info = NULL;
4157 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4158 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4159 if (property_info == NULL)
4161 reply = g_dbus_message_new_method_error (message,
4162 "org.freedesktop.DBus.Error.InvalidArgs",
4163 _("No such property `%s'"),
4165 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4166 g_object_unref (reply);
4171 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4173 reply = g_dbus_message_new_method_error (message,
4174 "org.freedesktop.DBus.Error.InvalidArgs",
4175 _("Property `%s' is not readable"),
4177 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4178 g_object_unref (reply);
4182 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4184 reply = g_dbus_message_new_method_error (message,
4185 "org.freedesktop.DBus.Error.InvalidArgs",
4186 _("Property `%s' is not writable"),
4188 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4189 g_object_unref (reply);
4194 /* ok, got the property info - call user code in an idle handler */
4195 property_data = g_new0 (PropertyData, 1);
4196 property_data->connection = g_object_ref (connection);
4197 property_data->message = g_object_ref (message);
4198 property_data->user_data = user_data;
4199 property_data->property_name = property_name;
4200 property_data->vtable = vtable;
4201 property_data->interface_info = interface_info;
4202 property_data->property_info = property_info;
4203 property_data->registration_id = registration_id;
4204 property_data->subtree_registration_id = subtree_registration_id;
4206 idle_source = g_idle_source_new ();
4207 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4208 g_source_set_callback (idle_source,
4209 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4211 (GDestroyNotify) property_data_free);
4212 g_source_attach (idle_source, main_context);
4213 g_source_unref (idle_source);
4221 /* called in GDBusWorker thread with connection's lock held */
4223 handle_getset_property (GDBusConnection *connection,
4225 GDBusMessage *message,
4228 ExportedInterface *ei;
4230 const char *interface_name;
4231 const char *property_name;
4236 g_variant_get (g_dbus_message_get_body (message),
4241 g_variant_get (g_dbus_message_get_body (message),
4247 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4248 * no such interface registered
4250 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4253 GDBusMessage *reply;
4254 reply = g_dbus_message_new_method_error (message,
4255 "org.freedesktop.DBus.Error.InvalidArgs",
4256 _("No such interface `%s'"),
4258 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4259 g_object_unref (reply);
4264 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4277 /* ---------------------------------------------------------------------------------------------------- */
4281 GDBusConnection *connection;
4282 GDBusMessage *message;
4284 const GDBusInterfaceVTable *vtable;
4285 GDBusInterfaceInfo *interface_info;
4286 guint registration_id;
4287 guint subtree_registration_id;
4288 } PropertyGetAllData;
4291 property_get_all_data_free (PropertyData *data)
4293 g_object_unref (data->connection);
4294 g_object_unref (data->message);
4298 /* called in thread where object was registered - no locks held */
4300 invoke_get_all_properties_in_idle_cb (gpointer _data)
4302 PropertyGetAllData *data = _data;
4303 GVariantBuilder builder;
4304 GDBusMessage *reply;
4307 if (has_object_been_unregistered (data->connection,
4308 data->registration_id,
4309 data->subtree_registration_id))
4311 reply = g_dbus_message_new_method_error (data->message,
4312 "org.freedesktop.DBus.Error.UnknownMethod",
4313 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4314 g_dbus_message_get_path (data->message));
4315 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4316 g_object_unref (reply);
4320 /* TODO: Right now we never fail this call - we just omit values if
4321 * a get_property() call is failing.
4323 * We could fail the whole call if just a single get_property() call
4324 * returns an error. We need clarification in the D-Bus spec about this.
4326 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4327 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4328 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4330 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4333 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4336 value = data->vtable->get_property (data->connection,
4337 g_dbus_message_get_sender (data->message),
4338 g_dbus_message_get_path (data->message),
4339 data->interface_info->name,
4340 property_info->name,
4347 g_variant_take_ref (value);
4348 g_variant_builder_add (&builder,
4350 property_info->name,
4352 g_variant_unref (value);
4354 g_variant_builder_close (&builder);
4356 reply = g_dbus_message_new_method_reply (data->message);
4357 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4358 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4359 g_object_unref (reply);
4365 /* called in any thread with connection's lock held */
4367 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4368 GDBusMessage *message,
4369 guint registration_id,
4370 guint subtree_registration_id,
4371 GDBusInterfaceInfo *interface_info,
4372 const GDBusInterfaceVTable *vtable,
4373 GMainContext *main_context,
4377 const char *interface_name;
4378 GSource *idle_source;
4379 PropertyGetAllData *property_get_all_data;
4383 g_variant_get (g_dbus_message_get_body (message),
4387 if (vtable == NULL || vtable->get_property == NULL)
4390 /* ok, got the property info - call user in an idle handler */
4391 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4392 property_get_all_data->connection = g_object_ref (connection);
4393 property_get_all_data->message = g_object_ref (message);
4394 property_get_all_data->user_data = user_data;
4395 property_get_all_data->vtable = vtable;
4396 property_get_all_data->interface_info = interface_info;
4397 property_get_all_data->registration_id = registration_id;
4398 property_get_all_data->subtree_registration_id = subtree_registration_id;
4400 idle_source = g_idle_source_new ();
4401 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4402 g_source_set_callback (idle_source,
4403 invoke_get_all_properties_in_idle_cb,
4404 property_get_all_data,
4405 (GDestroyNotify) property_get_all_data_free);
4406 g_source_attach (idle_source, main_context);
4407 g_source_unref (idle_source);
4415 /* called in GDBusWorker thread with connection's lock held */
4417 handle_get_all_properties (GDBusConnection *connection,
4419 GDBusMessage *message)
4421 ExportedInterface *ei;
4423 const char *interface_name;
4427 g_variant_get (g_dbus_message_get_body (message),
4431 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4432 * no such interface registered
4434 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4437 GDBusMessage *reply;
4438 reply = g_dbus_message_new_method_error (message,
4439 "org.freedesktop.DBus.Error.InvalidArgs",
4440 _("No such interface"),
4442 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4443 g_object_unref (reply);
4448 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4460 /* ---------------------------------------------------------------------------------------------------- */
4462 static const gchar introspect_header[] =
4463 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4464 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4465 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4468 static const gchar introspect_tail[] =
4471 static const gchar introspect_properties_interface[] =
4472 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4473 " <method name=\"Get\">\n"
4474 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4475 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4476 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4478 " <method name=\"GetAll\">\n"
4479 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4480 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4482 " <method name=\"Set\">\n"
4483 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4484 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4485 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4487 " <signal name=\"PropertiesChanged\">\n"
4488 " <arg type=\"s\" name=\"interface_name\"/>\n"
4489 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4490 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4494 static const gchar introspect_introspectable_interface[] =
4495 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4496 " <method name=\"Introspect\">\n"
4497 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4500 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4501 " <method name=\"Ping\"/>\n"
4502 " <method name=\"GetMachineId\">\n"
4503 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4508 introspect_append_header (GString *s)
4510 g_string_append (s, introspect_header);
4514 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4516 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4522 begin = object_path + path_len;
4523 end = strchr (begin, '/');
4525 s = g_strndup (begin, end - begin);
4527 s = g_strdup (begin);
4529 if (g_hash_table_lookup (set, s) == NULL)
4530 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4536 /* TODO: we want a nicer public interface for this */
4537 /* called in any thread with connection's lock held */
4539 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4544 GHashTableIter hash_iter;
4545 const gchar *object_path;
4551 CONNECTION_ENSURE_LOCK (connection);
4553 path_len = strlen (path);
4557 set = g_hash_table_new (g_str_hash, g_str_equal);
4559 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4560 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4561 maybe_add_path (path, path_len, object_path, set);
4563 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4564 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4565 maybe_add_path (path, path_len, object_path, set);
4567 p = g_ptr_array_new ();
4568 keys = g_hash_table_get_keys (set);
4569 for (l = keys; l != NULL; l = l->next)
4570 g_ptr_array_add (p, l->data);
4571 g_hash_table_unref (set);
4574 g_ptr_array_add (p, NULL);
4575 ret = (gchar **) g_ptr_array_free (p, FALSE);
4579 /* called in any thread with connection's lock not held */
4581 g_dbus_connection_list_registered (GDBusConnection *connection,
4585 CONNECTION_LOCK (connection);
4586 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4587 CONNECTION_UNLOCK (connection);
4591 /* called in GDBusWorker thread with connection's lock held */
4593 handle_introspect (GDBusConnection *connection,
4595 GDBusMessage *message)
4599 GDBusMessage *reply;
4600 GHashTableIter hash_iter;
4601 ExportedInterface *ei;
4604 /* first the header with the standard interfaces */
4605 s = g_string_sized_new (sizeof (introspect_header) +
4606 sizeof (introspect_properties_interface) +
4607 sizeof (introspect_introspectable_interface) +
4608 sizeof (introspect_tail));
4609 introspect_append_header (s);
4610 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4611 "org.freedesktop.DBus.Properties"))
4612 g_string_append (s, introspect_properties_interface);
4614 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4615 "org.freedesktop.DBus.Introspectable"))
4616 g_string_append (s, introspect_introspectable_interface);
4618 /* then include the registered interfaces */
4619 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4620 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4621 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4623 /* finally include nodes registered below us */
4624 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4625 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4626 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4627 g_strfreev (registered);
4628 g_string_append (s, introspect_tail);
4630 reply = g_dbus_message_new_method_reply (message);
4631 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4632 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4633 g_object_unref (reply);
4634 g_string_free (s, TRUE);
4639 /* called in thread where object was registered - no locks held */
4641 call_in_idle_cb (gpointer user_data)
4643 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4644 GDBusInterfaceVTable *vtable;
4645 guint registration_id;
4646 guint subtree_registration_id;
4648 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4649 g_assert (vtable != NULL && vtable->method_call != NULL);
4651 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4652 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4654 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4656 subtree_registration_id))
4658 GDBusMessage *reply;
4659 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4660 "org.freedesktop.DBus.Error.UnknownMethod",
4661 _("No such interface `%s' on object at path %s"),
4662 g_dbus_method_invocation_get_interface_name (invocation),
4663 g_dbus_method_invocation_get_object_path (invocation));
4664 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4665 g_object_unref (reply);
4669 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4670 g_dbus_method_invocation_get_sender (invocation),
4671 g_dbus_method_invocation_get_object_path (invocation),
4672 g_dbus_method_invocation_get_interface_name (invocation),
4673 g_dbus_method_invocation_get_method_name (invocation),
4674 g_dbus_method_invocation_get_parameters (invocation),
4675 g_object_ref (invocation),
4676 g_dbus_method_invocation_get_user_data (invocation));
4682 /* called in GDBusWorker thread with connection's lock held */
4684 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4685 GDBusMessage *message,
4686 guint registration_id,
4687 guint subtree_registration_id,
4688 GDBusInterfaceInfo *interface_info,
4689 const GDBusInterfaceVTable *vtable,
4690 GMainContext *main_context,
4693 GDBusMethodInvocation *invocation;
4694 const GDBusMethodInfo *method_info;
4695 GDBusMessage *reply;
4696 GVariant *parameters;
4697 GSource *idle_source;
4699 GVariantType *in_type;
4703 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4704 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4706 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4707 * error to the caller
4709 if (method_info == NULL)
4711 reply = g_dbus_message_new_method_error (message,
4712 "org.freedesktop.DBus.Error.UnknownMethod",
4713 _("No such method `%s'"),
4714 g_dbus_message_get_member (message));
4715 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4716 g_object_unref (reply);
4721 parameters = g_dbus_message_get_body (message);
4722 if (parameters == NULL)
4724 parameters = g_variant_new ("()");
4725 g_variant_ref_sink (parameters);
4729 g_variant_ref (parameters);
4732 /* Check that the incoming args are of the right type - if they are not, return
4733 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4735 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4736 if (!g_variant_is_of_type (parameters, in_type))
4740 type_string = g_variant_type_dup_string (in_type);
4742 reply = g_dbus_message_new_method_error (message,
4743 "org.freedesktop.DBus.Error.InvalidArgs",
4744 _("Type of message, `%s', does not match expected type `%s'"),
4745 g_variant_get_type_string (parameters),
4747 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4748 g_variant_type_free (in_type);
4749 g_variant_unref (parameters);
4750 g_object_unref (reply);
4751 g_free (type_string);
4755 g_variant_type_free (in_type);
4757 /* schedule the call in idle */
4758 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4759 g_dbus_message_get_path (message),
4760 g_dbus_message_get_interface (message),
4761 g_dbus_message_get_member (message),
4767 g_variant_unref (parameters);
4769 /* TODO: would be nicer with a real MethodData like we already
4770 * have PropertyData and PropertyGetAllData... */
4771 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4772 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4773 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4775 idle_source = g_idle_source_new ();
4776 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4777 g_source_set_callback (idle_source,
4781 g_source_attach (idle_source, main_context);
4782 g_source_unref (idle_source);
4790 /* ---------------------------------------------------------------------------------------------------- */
4792 /* called in GDBusWorker thread with connection's lock held */
4794 obj_message_func (GDBusConnection *connection,
4796 GDBusMessage *message)
4798 const gchar *interface_name;
4799 const gchar *member;
4800 const gchar *signature;
4805 interface_name = g_dbus_message_get_interface (message);
4806 member = g_dbus_message_get_member (message);
4807 signature = g_dbus_message_get_signature (message);
4809 /* see if we have an interface for handling this call */
4810 if (interface_name != NULL)
4812 ExportedInterface *ei;
4813 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4816 /* we do - invoke the handler in idle in the right thread */
4818 /* handle no vtable or handler being present */
4819 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4822 handled = validate_and_maybe_schedule_method_call (connection,
4834 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4835 g_strcmp0 (member, "Introspect") == 0 &&
4836 g_strcmp0 (signature, "") == 0)
4838 handled = handle_introspect (connection, eo, message);
4841 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4842 g_strcmp0 (member, "Get") == 0 &&
4843 g_strcmp0 (signature, "ss") == 0)
4845 handled = handle_getset_property (connection, eo, message, TRUE);
4848 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4849 g_strcmp0 (member, "Set") == 0 &&
4850 g_strcmp0 (signature, "ssv") == 0)
4852 handled = handle_getset_property (connection, eo, message, FALSE);
4855 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4856 g_strcmp0 (member, "GetAll") == 0 &&
4857 g_strcmp0 (signature, "s") == 0)
4859 handled = handle_get_all_properties (connection, eo, message);
4868 * g_dbus_connection_register_object:
4869 * @connection: A #GDBusConnection.
4870 * @object_path: The object path to register at.
4871 * @interface_info: Introspection data for the interface.
4872 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4873 * @user_data: (allow-none): Data to pass to functions in @vtable.
4874 * @user_data_free_func: Function to call when the object path is unregistered.
4875 * @error: Return location for error or %NULL.
4877 * Registers callbacks for exported objects at @object_path with the
4878 * D-Bus interface that is described in @interface_info.
4880 * Calls to functions in @vtable (and @user_data_free_func) will
4881 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4882 * loop</link> of the thread you are calling this method from.
4884 * Note that all #GVariant values passed to functions in @vtable will match
4885 * the signature given in @interface_info - if a remote caller passes
4886 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4887 * is returned to the remote caller.
4889 * Additionally, if the remote caller attempts to invoke methods or
4890 * access properties not mentioned in @interface_info the
4891 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4892 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4893 * are returned to the caller.
4895 * It is considered a programming error if the
4896 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4897 * #GVariant of incorrect type.
4899 * If an existing callback is already registered at @object_path and
4900 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4902 * GDBus automatically implements the standard D-Bus interfaces
4903 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4904 * and org.freedesktop.Peer, so you don't have to implement those for
4905 * the objects you export. You <emphasis>can</emphasis> implement
4906 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4907 * and setting of properties asynchronously.
4909 * Note that the reference count on @interface_info will be
4910 * incremented by 1 (unless allocated statically, e.g. if the
4911 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4912 * as the object is exported. Also note that @vtable will be copied.
4914 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4916 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4917 * that can be used with g_dbus_connection_unregister_object() .
4922 g_dbus_connection_register_object (GDBusConnection *connection,
4923 const gchar *object_path,
4924 GDBusInterfaceInfo *interface_info,
4925 const GDBusInterfaceVTable *vtable,
4927 GDestroyNotify user_data_free_func,
4931 ExportedInterface *ei;
4934 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4935 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4936 g_return_val_if_fail (interface_info != NULL, 0);
4937 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4938 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4939 g_return_val_if_fail (check_initialized (connection), 0);
4943 CONNECTION_LOCK (connection);
4945 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4948 eo = g_new0 (ExportedObject, 1);
4949 eo->object_path = g_strdup (object_path);
4950 eo->connection = connection;
4951 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4954 (GDestroyNotify) exported_interface_free);
4955 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4958 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4964 _("An object is already exported for the interface %s at %s"),
4965 interface_info->name,
4970 ei = g_new0 (ExportedInterface, 1);
4971 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4973 ei->user_data = user_data;
4974 ei->user_data_free_func = user_data_free_func;
4975 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4976 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4977 g_dbus_interface_info_cache_build (ei->interface_info);
4978 ei->interface_name = g_strdup (interface_info->name);
4979 ei->context = g_main_context_ref_thread_default ();
4981 g_hash_table_insert (eo->map_if_name_to_ei,
4982 (gpointer) ei->interface_name,
4984 g_hash_table_insert (connection->map_id_to_ei,
4985 GUINT_TO_POINTER (ei->id),
4991 CONNECTION_UNLOCK (connection);
4997 * g_dbus_connection_unregister_object:
4998 * @connection: A #GDBusConnection.
4999 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5001 * Unregisters an object.
5003 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5008 g_dbus_connection_unregister_object (GDBusConnection *connection,
5009 guint registration_id)
5011 ExportedInterface *ei;
5015 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5016 g_return_val_if_fail (check_initialized (connection), FALSE);
5020 CONNECTION_LOCK (connection);
5022 ei = g_hash_table_lookup (connection->map_id_to_ei,
5023 GUINT_TO_POINTER (registration_id));
5029 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5030 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5031 /* unregister object path if we have no more exported interfaces */
5032 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5033 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5039 CONNECTION_UNLOCK (connection);
5044 /* ---------------------------------------------------------------------------------------------------- */
5047 * g_dbus_connection_emit_signal:
5048 * @connection: A #GDBusConnection.
5049 * @destination_bus_name: (allow-none): The unique bus name for the destination
5050 * for the signal or %NULL to emit to all listeners.
5051 * @object_path: Path of remote object.
5052 * @interface_name: D-Bus interface to emit a signal on.
5053 * @signal_name: The name of the signal to emit.
5054 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5055 * or %NULL if not passing parameters.
5056 * @error: Return location for error or %NULL.
5060 * If the parameters GVariant is floating, it is consumed.
5062 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5064 * Returns: %TRUE unless @error is set.
5069 g_dbus_connection_emit_signal (GDBusConnection *connection,
5070 const gchar *destination_bus_name,
5071 const gchar *object_path,
5072 const gchar *interface_name,
5073 const gchar *signal_name,
5074 GVariant *parameters,
5077 GDBusMessage *message;
5083 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5084 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5085 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5086 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5087 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5088 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5089 g_return_val_if_fail (check_initialized (connection), FALSE);
5091 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5093 _g_dbus_debug_print_lock ();
5094 g_print ("========================================================================\n"
5095 "GDBus-debug:Emission:\n"
5096 " >>>> SIGNAL EMISSION %s.%s()\n"
5098 " destination %s\n",
5099 interface_name, signal_name,
5101 destination_bus_name != NULL ? destination_bus_name : "(none)");
5102 _g_dbus_debug_print_unlock ();
5105 message = g_dbus_message_new_signal (object_path,
5109 if (destination_bus_name != NULL)
5110 g_dbus_message_set_header (message,
5111 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5112 g_variant_new_string (destination_bus_name));
5114 if (parameters != NULL)
5115 g_dbus_message_set_body (message, parameters);
5117 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5118 g_object_unref (message);
5124 add_call_flags (GDBusMessage *message,
5125 GDBusCallFlags flags)
5127 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5128 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5132 decode_method_reply (GDBusMessage *reply,
5133 const gchar *method_name,
5134 const GVariantType *reply_type,
5135 GUnixFDList **out_fd_list,
5141 switch (g_dbus_message_get_message_type (reply))
5143 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5144 result = g_dbus_message_get_body (reply);
5147 result = g_variant_new ("()");
5148 g_variant_ref_sink (result);
5152 g_variant_ref (result);
5155 if (!g_variant_is_of_type (result, reply_type))
5157 gchar *type_string = g_variant_type_dup_string (reply_type);
5161 G_IO_ERROR_INVALID_ARGUMENT,
5162 _("Method `%s' returned type `%s', but expected `%s'"),
5163 method_name, g_variant_get_type_string (result), type_string);
5165 g_variant_unref (result);
5166 g_free (type_string);
5173 if (out_fd_list != NULL)
5175 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5176 if (*out_fd_list != NULL)
5177 g_object_ref (*out_fd_list);
5183 case G_DBUS_MESSAGE_TYPE_ERROR:
5184 g_dbus_message_to_gerror (reply, error);
5188 g_assert_not_reached ();
5198 GSimpleAsyncResult *simple;
5199 GVariantType *reply_type;
5200 gchar *method_name; /* for error message */
5204 GUnixFDList *fd_list;
5208 call_state_free (CallState *state)
5210 g_variant_type_free (state->reply_type);
5211 g_free (state->method_name);
5213 if (state->value != NULL)
5214 g_variant_unref (state->value);
5215 if (state->fd_list != NULL)
5216 g_object_unref (state->fd_list);
5217 g_slice_free (CallState, state);
5220 /* called in any thread, with the connection's lock not held */
5222 g_dbus_connection_call_done (GObject *source,
5223 GAsyncResult *result,
5226 GSimpleAsyncResult *simple;
5227 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5228 CallState *state = user_data;
5230 GDBusMessage *reply;
5233 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5237 if (G_UNLIKELY (_g_dbus_debug_call ()))
5239 _g_dbus_debug_print_lock ();
5240 g_print ("========================================================================\n"
5241 "GDBus-debug:Call:\n"
5242 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5248 g_print ("SUCCESS\n");
5252 g_print ("FAILED: %s\n",
5255 _g_dbus_debug_print_unlock ();
5259 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5261 simple = state->simple; /* why? because state is freed before we unref simple.. */
5264 g_simple_async_result_take_error (state->simple, error);
5265 g_simple_async_result_complete (state->simple);
5266 call_state_free (state);
5270 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5271 g_simple_async_result_complete (state->simple);
5272 g_object_unref (reply);
5274 g_object_unref (simple);
5277 /* called in any thread, with the connection's lock not held */
5279 g_dbus_connection_call_internal (GDBusConnection *connection,
5280 const gchar *bus_name,
5281 const gchar *object_path,
5282 const gchar *interface_name,
5283 const gchar *method_name,
5284 GVariant *parameters,
5285 const GVariantType *reply_type,
5286 GDBusCallFlags flags,
5288 GUnixFDList *fd_list,
5289 GCancellable *cancellable,
5290 GAsyncReadyCallback callback,
5293 GDBusMessage *message;
5296 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5297 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5298 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5299 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5300 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5301 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5302 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5303 g_return_if_fail (check_initialized (connection));
5305 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5307 g_return_if_fail (fd_list == NULL);
5310 state = g_slice_new0 (CallState);
5311 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5312 callback, user_data,
5313 g_dbus_connection_call_internal);
5314 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5316 if (reply_type == NULL)
5317 reply_type = G_VARIANT_TYPE_ANY;
5319 state->reply_type = g_variant_type_copy (reply_type);
5321 message = g_dbus_message_new_method_call (bus_name,
5325 add_call_flags (message, flags);
5326 if (parameters != NULL)
5327 g_dbus_message_set_body (message, parameters);
5330 if (fd_list != NULL)
5331 g_dbus_message_set_unix_fd_list (message, fd_list);
5334 g_dbus_connection_send_message_with_reply (connection,
5336 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5340 g_dbus_connection_call_done,
5343 if (G_UNLIKELY (_g_dbus_debug_call ()))
5345 _g_dbus_debug_print_lock ();
5346 g_print ("========================================================================\n"
5347 "GDBus-debug:Call:\n"
5348 " >>>> ASYNC %s.%s()\n"
5350 " owned by name %s (serial %d)\n",
5354 bus_name != NULL ? bus_name : "(none)",
5356 _g_dbus_debug_print_unlock ();
5359 if (message != NULL)
5360 g_object_unref (message);
5363 /* called in any thread, with the connection's lock not held */
5365 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5366 GUnixFDList **out_fd_list,
5370 GSimpleAsyncResult *simple;
5373 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5374 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5375 g_dbus_connection_call_internal), NULL);
5376 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5378 simple = G_SIMPLE_ASYNC_RESULT (res);
5380 if (g_simple_async_result_propagate_error (simple, error))
5383 state = g_simple_async_result_get_op_res_gpointer (simple);
5384 if (out_fd_list != NULL)
5385 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5386 return g_variant_ref (state->value);
5389 /* called in any user thread, with the connection's lock not held */
5391 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5392 const gchar *bus_name,
5393 const gchar *object_path,
5394 const gchar *interface_name,
5395 const gchar *method_name,
5396 GVariant *parameters,
5397 const GVariantType *reply_type,
5398 GDBusCallFlags flags,
5400 GUnixFDList *fd_list,
5401 GUnixFDList **out_fd_list,
5402 GCancellable *cancellable,
5405 GDBusMessage *message;
5406 GDBusMessage *reply;
5408 GError *local_error;
5409 GDBusSendMessageFlags send_flags;
5415 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5416 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5417 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5418 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5419 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5420 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5421 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5423 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5425 g_return_val_if_fail (fd_list == NULL, NULL);
5427 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5429 if (!(flags & CALL_FLAGS_INITIALIZING))
5430 g_return_val_if_fail (check_initialized (connection), FALSE);
5432 if (reply_type == NULL)
5433 reply_type = G_VARIANT_TYPE_ANY;
5435 message = g_dbus_message_new_method_call (bus_name,
5439 add_call_flags (message, flags);
5440 if (parameters != NULL)
5441 g_dbus_message_set_body (message, parameters);
5444 if (fd_list != NULL)
5445 g_dbus_message_set_unix_fd_list (message, fd_list);
5448 if (G_UNLIKELY (_g_dbus_debug_call ()))
5450 _g_dbus_debug_print_lock ();
5451 g_print ("========================================================================\n"
5452 "GDBus-debug:Call:\n"
5453 " >>>> SYNC %s.%s()\n"
5455 " owned by name %s\n",
5459 bus_name != NULL ? bus_name : "(none)");
5460 _g_dbus_debug_print_unlock ();
5465 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5467 /* translate from one flavour of flags to another... */
5468 if (flags & CALL_FLAGS_INITIALIZING)
5469 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5471 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5475 NULL, /* volatile guint32 *out_serial */
5479 if (G_UNLIKELY (_g_dbus_debug_call ()))
5481 _g_dbus_debug_print_lock ();
5482 g_print ("========================================================================\n"
5483 "GDBus-debug:Call:\n"
5484 " <<<< SYNC COMPLETE %s.%s()\n"
5490 g_print ("SUCCESS\n");
5494 g_print ("FAILED: %s\n",
5495 local_error->message);
5497 _g_dbus_debug_print_unlock ();
5503 *error = local_error;
5505 g_error_free (local_error);
5509 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5512 if (message != NULL)
5513 g_object_unref (message);
5515 g_object_unref (reply);
5520 /* ---------------------------------------------------------------------------------------------------- */
5523 * g_dbus_connection_call:
5524 * @connection: A #GDBusConnection.
5525 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5526 * @connection is not a message bus connection.
5527 * @object_path: Path of remote object.
5528 * @interface_name: D-Bus interface to invoke method on.
5529 * @method_name: The name of the method to invoke.
5530 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5531 * or %NULL if not passing parameters.
5532 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5533 * @flags: Flags from the #GDBusCallFlags enumeration.
5534 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5535 * timeout or %G_MAXINT for no timeout.
5536 * @cancellable: A #GCancellable or %NULL.
5537 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5538 * satisfied or %NULL if you don't * care about the result of the
5539 * method invocation.
5540 * @user_data: The data to pass to @callback.
5542 * Asynchronously invokes the @method_name method on the
5543 * @interface_name D-Bus interface on the remote object at
5544 * @object_path owned by @bus_name.
5546 * If @connection is closed then the operation will fail with
5547 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5548 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5549 * not compatible with the D-Bus protocol, the operation fails with
5550 * %G_IO_ERROR_INVALID_ARGUMENT.
5552 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5553 * error will be raised if it does not match. Said another way, if you give a @reply_type
5554 * then any non-%NULL return value will be of this type.
5556 * If the @parameters #GVariant is floating, it is consumed. This allows
5557 * convenient 'inline' use of g_variant_new(), e.g.:
5559 * g_dbus_connection_call (connection,
5560 * "org.freedesktop.StringThings",
5561 * "/org/freedesktop/StringThings",
5562 * "org.freedesktop.StringThings",
5564 * g_variant_new ("(ss)",
5568 * G_DBUS_CALL_FLAGS_NONE,
5571 * (GAsyncReadyCallback) two_strings_done,
5575 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5576 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5577 * of the thread you are calling this method from. You can then call
5578 * g_dbus_connection_call_finish() to get the result of the operation.
5579 * See g_dbus_connection_call_sync() for the synchronous version of this
5585 g_dbus_connection_call (GDBusConnection *connection,
5586 const gchar *bus_name,
5587 const gchar *object_path,
5588 const gchar *interface_name,
5589 const gchar *method_name,
5590 GVariant *parameters,
5591 const GVariantType *reply_type,
5592 GDBusCallFlags flags,
5594 GCancellable *cancellable,
5595 GAsyncReadyCallback callback,
5598 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);
5602 * g_dbus_connection_call_finish:
5603 * @connection: A #GDBusConnection.
5604 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5605 * @error: Return location for error or %NULL.
5607 * Finishes an operation started with g_dbus_connection_call().
5609 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5610 * return values. Free with g_variant_unref().
5615 g_dbus_connection_call_finish (GDBusConnection *connection,
5619 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5623 * g_dbus_connection_call_sync:
5624 * @connection: A #GDBusConnection.
5625 * @bus_name: A unique or well-known bus name.
5626 * @object_path: Path of remote object.
5627 * @interface_name: D-Bus interface to invoke method on.
5628 * @method_name: The name of the method to invoke.
5629 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5630 * or %NULL if not passing parameters.
5631 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5632 * @flags: Flags from the #GDBusCallFlags enumeration.
5633 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5634 * timeout or %G_MAXINT for no timeout.
5635 * @cancellable: A #GCancellable or %NULL.
5636 * @error: Return location for error or %NULL.
5638 * Synchronously invokes the @method_name method on the
5639 * @interface_name D-Bus interface on the remote object at
5640 * @object_path owned by @bus_name.
5642 * If @connection is closed then the operation will fail with
5643 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5644 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5645 * contains a value not compatible with the D-Bus protocol, the operation
5646 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5648 * If @reply_type is non-%NULL then the reply will be checked for having
5649 * this type and an error will be raised if it does not match. Said
5650 * another way, if you give a @reply_type then any non-%NULL return
5651 * value will be of this type.
5653 * If the @parameters #GVariant is floating, it is consumed.
5654 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5656 * g_dbus_connection_call_sync (connection,
5657 * "org.freedesktop.StringThings",
5658 * "/org/freedesktop/StringThings",
5659 * "org.freedesktop.StringThings",
5661 * g_variant_new ("(ss)",
5665 * G_DBUS_CALL_FLAGS_NONE,
5671 * The calling thread is blocked until a reply is received. See
5672 * g_dbus_connection_call() for the asynchronous version of
5675 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5676 * return values. Free with g_variant_unref().
5681 g_dbus_connection_call_sync (GDBusConnection *connection,
5682 const gchar *bus_name,
5683 const gchar *object_path,
5684 const gchar *interface_name,
5685 const gchar *method_name,
5686 GVariant *parameters,
5687 const GVariantType *reply_type,
5688 GDBusCallFlags flags,
5690 GCancellable *cancellable,
5693 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);
5696 /* ---------------------------------------------------------------------------------------------------- */
5701 * g_dbus_connection_call_with_unix_fd_list:
5702 * @connection: A #GDBusConnection.
5703 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5704 * @connection is not a message bus connection.
5705 * @object_path: Path of remote object.
5706 * @interface_name: D-Bus interface to invoke method on.
5707 * @method_name: The name of the method to invoke.
5708 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5709 * or %NULL if not passing parameters.
5710 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5711 * @flags: Flags from the #GDBusCallFlags enumeration.
5712 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5713 * timeout or %G_MAXINT for no timeout.
5714 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5715 * @cancellable: A #GCancellable or %NULL.
5716 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5717 * satisfied or %NULL if you don't * care about the result of the
5718 * method invocation.
5719 * @user_data: The data to pass to @callback.
5721 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5723 * This method is only available on UNIX.
5728 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5729 const gchar *bus_name,
5730 const gchar *object_path,
5731 const gchar *interface_name,
5732 const gchar *method_name,
5733 GVariant *parameters,
5734 const GVariantType *reply_type,
5735 GDBusCallFlags flags,
5737 GUnixFDList *fd_list,
5738 GCancellable *cancellable,
5739 GAsyncReadyCallback callback,
5742 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);
5746 * g_dbus_connection_call_with_unix_fd_list_finish:
5747 * @connection: A #GDBusConnection.
5748 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5749 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5750 * @error: Return location for error or %NULL.
5752 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5754 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5755 * return values. Free with g_variant_unref().
5760 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5761 GUnixFDList **out_fd_list,
5765 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5769 * g_dbus_connection_call_with_unix_fd_list_sync:
5770 * @connection: A #GDBusConnection.
5771 * @bus_name: A unique or well-known bus name.
5772 * @object_path: Path of remote object.
5773 * @interface_name: D-Bus interface to invoke method on.
5774 * @method_name: The name of the method to invoke.
5775 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5776 * or %NULL if not passing parameters.
5777 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5778 * @flags: Flags from the #GDBusCallFlags enumeration.
5779 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5780 * timeout or %G_MAXINT for no timeout.
5781 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5782 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5783 * @cancellable: A #GCancellable or %NULL.
5784 * @error: Return location for error or %NULL.
5786 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5788 * This method is only available on UNIX.
5790 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5791 * return values. Free with g_variant_unref().
5796 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5797 const gchar *bus_name,
5798 const gchar *object_path,
5799 const gchar *interface_name,
5800 const gchar *method_name,
5801 GVariant *parameters,
5802 const GVariantType *reply_type,
5803 GDBusCallFlags flags,
5805 GUnixFDList *fd_list,
5806 GUnixFDList **out_fd_list,
5807 GCancellable *cancellable,
5810 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);
5813 #endif /* G_OS_UNIX */
5815 /* ---------------------------------------------------------------------------------------------------- */
5817 struct ExportedSubtree
5821 GDBusConnection *connection;
5822 GDBusSubtreeVTable *vtable;
5823 GDBusSubtreeFlags flags;
5825 GMainContext *context;
5827 GDestroyNotify user_data_free_func;
5831 exported_subtree_free (ExportedSubtree *es)
5833 call_destroy_notify (es->context,
5834 es->user_data_free_func,
5837 g_main_context_unref (es->context);
5839 _g_dbus_subtree_vtable_free (es->vtable);
5840 g_free (es->object_path);
5844 /* called without lock held in the thread where the caller registered
5848 handle_subtree_introspect (GDBusConnection *connection,
5849 ExportedSubtree *es,
5850 GDBusMessage *message)
5854 GDBusMessage *reply;
5857 const gchar *sender;
5858 const gchar *requested_object_path;
5859 const gchar *requested_node;
5860 GDBusInterfaceInfo **interfaces;
5862 gchar **subnode_paths;
5863 gboolean has_properties_interface;
5864 gboolean has_introspectable_interface;
5868 requested_object_path = g_dbus_message_get_path (message);
5869 sender = g_dbus_message_get_sender (message);
5870 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5872 s = g_string_new (NULL);
5873 introspect_append_header (s);
5875 /* Strictly we don't need the children in dynamic mode, but we avoid the
5876 * conditionals to preserve code clarity
5878 children = es->vtable->enumerate (es->connection,
5885 requested_node = strrchr (requested_object_path, '/') + 1;
5887 /* Assert existence of object if we are not dynamic */
5888 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5889 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5894 requested_node = NULL;
5897 interfaces = es->vtable->introspect (es->connection,
5902 if (interfaces != NULL)
5904 has_properties_interface = FALSE;
5905 has_introspectable_interface = FALSE;
5907 for (n = 0; interfaces[n] != NULL; n++)
5909 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5910 has_properties_interface = TRUE;
5911 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5912 has_introspectable_interface = TRUE;
5914 if (!has_properties_interface)
5915 g_string_append (s, introspect_properties_interface);
5916 if (!has_introspectable_interface)
5917 g_string_append (s, introspect_introspectable_interface);
5919 for (n = 0; interfaces[n] != NULL; n++)
5921 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5922 g_dbus_interface_info_unref (interfaces[n]);
5924 g_free (interfaces);
5927 /* then include <node> entries from the Subtree for the root */
5930 for (n = 0; children != NULL && children[n] != NULL; n++)
5931 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5934 /* finally include nodes registered below us */
5935 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5936 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5937 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5938 g_strfreev (subnode_paths);
5940 g_string_append (s, "</node>\n");
5942 reply = g_dbus_message_new_method_reply (message);
5943 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5944 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5945 g_object_unref (reply);
5950 g_string_free (s, TRUE);
5951 g_strfreev (children);
5955 /* called without lock held in the thread where the caller registered
5959 handle_subtree_method_invocation (GDBusConnection *connection,
5960 ExportedSubtree *es,
5961 GDBusMessage *message)
5964 const gchar *sender;
5965 const gchar *interface_name;
5966 const gchar *member;
5967 const gchar *signature;
5968 const gchar *requested_object_path;
5969 const gchar *requested_node;
5971 GDBusInterfaceInfo *interface_info;
5972 const GDBusInterfaceVTable *interface_vtable;
5973 gpointer interface_user_data;
5975 GDBusInterfaceInfo **interfaces;
5976 gboolean is_property_get;
5977 gboolean is_property_set;
5978 gboolean is_property_get_all;
5983 requested_object_path = g_dbus_message_get_path (message);
5984 sender = g_dbus_message_get_sender (message);
5985 interface_name = g_dbus_message_get_interface (message);
5986 member = g_dbus_message_get_member (message);
5987 signature = g_dbus_message_get_signature (message);
5988 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5990 is_property_get = FALSE;
5991 is_property_set = FALSE;
5992 is_property_get_all = FALSE;
5993 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5995 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5996 is_property_get = TRUE;
5997 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5998 is_property_set = TRUE;
5999 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6000 is_property_get_all = TRUE;
6005 requested_node = strrchr (requested_object_path, '/') + 1;
6007 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6009 /* We don't want to dispatch to unenumerated
6010 * nodes, so ensure that the child exists.
6015 children = es->vtable->enumerate (es->connection,
6020 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6021 g_strfreev (children);
6029 requested_node = NULL;
6032 /* get introspection data for the node */
6033 interfaces = es->vtable->introspect (es->connection,
6035 requested_object_path,
6039 if (interfaces == NULL)
6042 interface_info = NULL;
6043 for (n = 0; interfaces[n] != NULL; n++)
6045 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6046 interface_info = interfaces[n];
6049 /* dispatch the call if the user wants to handle it */
6050 if (interface_info != NULL)
6052 /* figure out where to dispatch the method call */
6053 interface_user_data = NULL;
6054 interface_vtable = es->vtable->dispatch (es->connection,
6059 &interface_user_data,
6061 if (interface_vtable == NULL)
6064 CONNECTION_LOCK (connection);
6065 handled = validate_and_maybe_schedule_method_call (es->connection,
6072 interface_user_data);
6073 CONNECTION_UNLOCK (connection);
6075 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6076 else if (is_property_get || is_property_set || is_property_get_all)
6078 if (is_property_get)
6079 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6080 else if (is_property_set)
6081 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6082 else if (is_property_get_all)
6083 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6085 g_assert_not_reached ();
6087 /* see if the object supports this interface at all */
6088 for (n = 0; interfaces[n] != NULL; n++)
6090 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6091 interface_info = interfaces[n];
6094 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6095 * claims it won't support the interface
6097 if (interface_info == NULL)
6099 GDBusMessage *reply;
6100 reply = g_dbus_message_new_method_error (message,
6101 "org.freedesktop.DBus.Error.InvalidArgs",
6102 _("No such interface `%s'"),
6104 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6105 g_object_unref (reply);
6110 /* figure out where to dispatch the property get/set/getall calls */
6111 interface_user_data = NULL;
6112 interface_vtable = es->vtable->dispatch (es->connection,
6117 &interface_user_data,
6119 if (interface_vtable == NULL)
6121 g_warning ("The subtree introspection function indicates that '%s' "
6122 "is a valid interface name, but calling the dispatch "
6123 "function on that interface gave us NULL", interface_name);
6127 if (is_property_get || is_property_set)
6129 CONNECTION_LOCK (connection);
6130 handled = validate_and_maybe_schedule_property_getset (es->connection,
6138 interface_user_data);
6139 CONNECTION_UNLOCK (connection);
6141 else if (is_property_get_all)
6143 CONNECTION_LOCK (connection);
6144 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6151 interface_user_data);
6152 CONNECTION_UNLOCK (connection);
6157 if (interfaces != NULL)
6159 for (n = 0; interfaces[n] != NULL; n++)
6160 g_dbus_interface_info_unref (interfaces[n]);
6161 g_free (interfaces);
6169 GDBusMessage *message;
6170 ExportedSubtree *es;
6171 } SubtreeDeferredData;
6174 subtree_deferred_data_free (SubtreeDeferredData *data)
6176 g_object_unref (data->message);
6180 /* called without lock held in the thread where the caller registered the subtree */
6182 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6184 SubtreeDeferredData *data = _data;
6189 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6190 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6191 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6192 handled = handle_subtree_introspect (data->es->connection,
6196 handled = handle_subtree_method_invocation (data->es->connection,
6202 CONNECTION_LOCK (data->es->connection);
6203 handled = handle_generic_unlocked (data->es->connection, data->message);
6204 CONNECTION_UNLOCK (data->es->connection);
6207 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6210 GDBusMessage *reply;
6211 reply = g_dbus_message_new_method_error (data->message,
6212 "org.freedesktop.DBus.Error.UnknownMethod",
6213 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6214 g_dbus_message_get_member (data->message),
6215 g_dbus_message_get_interface (data->message),
6216 g_dbus_message_get_signature (data->message));
6217 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6218 g_object_unref (reply);
6224 /* called in GDBusWorker thread with connection's lock held */
6226 subtree_message_func (GDBusConnection *connection,
6227 ExportedSubtree *es,
6228 GDBusMessage *message)
6230 GSource *idle_source;
6231 SubtreeDeferredData *data;
6233 data = g_new0 (SubtreeDeferredData, 1);
6234 data->message = g_object_ref (message);
6237 /* defer this call to an idle handler in the right thread */
6238 idle_source = g_idle_source_new ();
6239 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6240 g_source_set_callback (idle_source,
6241 process_subtree_vtable_message_in_idle_cb,
6243 (GDestroyNotify) subtree_deferred_data_free);
6244 g_source_attach (idle_source, es->context);
6245 g_source_unref (idle_source);
6247 /* since we own the entire subtree, handlers for objects not in the subtree have been
6248 * tried already by libdbus-1 - so we just need to ensure that we're always going
6249 * to reply to the message
6255 * g_dbus_connection_register_subtree:
6256 * @connection: A #GDBusConnection.
6257 * @object_path: The object path to register the subtree at.
6258 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6259 * @flags: Flags used to fine tune the behavior of the subtree.
6260 * @user_data: Data to pass to functions in @vtable.
6261 * @user_data_free_func: Function to call when the subtree is unregistered.
6262 * @error: Return location for error or %NULL.
6264 * Registers a whole subtree of <quote>dynamic</quote> objects.
6266 * The @enumerate and @introspection functions in @vtable are used to
6267 * convey, to remote callers, what nodes exist in the subtree rooted
6270 * When handling remote calls into any node in the subtree, first the
6271 * @enumerate function is used to check if the node exists. If the node exists
6272 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6273 * the @introspection function is used to check if the node supports the
6274 * requested method. If so, the @dispatch function is used to determine
6275 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6276 * #gpointer will be used to call into the interface vtable for processing
6279 * All calls into user-provided code will be invoked in the <link
6280 * linkend="g-main-context-push-thread-default">thread-default main
6281 * loop</link> of the thread you are calling this method from.
6283 * If an existing subtree is already registered at @object_path or
6284 * then @error is set to #G_IO_ERROR_EXISTS.
6286 * Note that it is valid to register regular objects (using
6287 * g_dbus_connection_register_object()) in a subtree registered with
6288 * g_dbus_connection_register_subtree() - if so, the subtree handler
6289 * is tried as the last resort. One way to think about a subtree
6290 * handler is to consider it a <quote>fallback handler</quote>
6291 * for object paths not registered via g_dbus_connection_register_object()
6292 * or other bindings.
6294 * Note that @vtable will be copied so you cannot change it after
6297 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6299 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6300 * that can be used with g_dbus_connection_unregister_subtree() .
6305 g_dbus_connection_register_subtree (GDBusConnection *connection,
6306 const gchar *object_path,
6307 const GDBusSubtreeVTable *vtable,
6308 GDBusSubtreeFlags flags,
6310 GDestroyNotify user_data_free_func,
6314 ExportedSubtree *es;
6316 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6317 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6318 g_return_val_if_fail (vtable != NULL, 0);
6319 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6320 g_return_val_if_fail (check_initialized (connection), 0);
6324 CONNECTION_LOCK (connection);
6326 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6332 _("A subtree is already exported for %s"),
6337 es = g_new0 (ExportedSubtree, 1);
6338 es->object_path = g_strdup (object_path);
6339 es->connection = connection;
6341 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6343 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6344 es->user_data = user_data;
6345 es->user_data_free_func = user_data_free_func;
6346 es->context = g_main_context_ref_thread_default ();
6348 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6349 g_hash_table_insert (connection->map_id_to_es,
6350 GUINT_TO_POINTER (es->id),
6356 CONNECTION_UNLOCK (connection);
6361 /* ---------------------------------------------------------------------------------------------------- */
6364 * g_dbus_connection_unregister_subtree:
6365 * @connection: A #GDBusConnection.
6366 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6368 * Unregisters a subtree.
6370 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6375 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6376 guint registration_id)
6378 ExportedSubtree *es;
6381 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6382 g_return_val_if_fail (check_initialized (connection), FALSE);
6386 CONNECTION_LOCK (connection);
6388 es = g_hash_table_lookup (connection->map_id_to_es,
6389 GUINT_TO_POINTER (registration_id));
6393 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6394 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6399 CONNECTION_UNLOCK (connection);
6404 /* ---------------------------------------------------------------------------------------------------- */
6406 /* may be called in any thread, with connection's lock held */
6408 handle_generic_ping_unlocked (GDBusConnection *connection,
6409 const gchar *object_path,
6410 GDBusMessage *message)
6412 GDBusMessage *reply;
6413 reply = g_dbus_message_new_method_reply (message);
6414 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6415 g_object_unref (reply);
6418 /* may be called in any thread, with connection's lock held */
6420 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6421 const gchar *object_path,
6422 GDBusMessage *message)
6424 GDBusMessage *reply;
6427 if (connection->machine_id == NULL)
6432 connection->machine_id = _g_dbus_get_machine_id (&error);
6433 if (connection->machine_id == NULL)
6435 reply = g_dbus_message_new_method_error_literal (message,
6436 "org.freedesktop.DBus.Error.Failed",
6438 g_error_free (error);
6444 reply = g_dbus_message_new_method_reply (message);
6445 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6447 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6448 g_object_unref (reply);
6451 /* may be called in any thread, with connection's lock held */
6453 handle_generic_introspect_unlocked (GDBusConnection *connection,
6454 const gchar *object_path,
6455 GDBusMessage *message)
6460 GDBusMessage *reply;
6462 /* first the header */
6463 s = g_string_new (NULL);
6464 introspect_append_header (s);
6466 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6467 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6468 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6469 g_strfreev (registered);
6470 g_string_append (s, "</node>\n");
6472 reply = g_dbus_message_new_method_reply (message);
6473 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6474 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6475 g_object_unref (reply);
6476 g_string_free (s, TRUE);
6479 /* may be called in any thread, with connection's lock held */
6481 handle_generic_unlocked (GDBusConnection *connection,
6482 GDBusMessage *message)
6485 const gchar *interface_name;
6486 const gchar *member;
6487 const gchar *signature;
6490 CONNECTION_ENSURE_LOCK (connection);
6494 interface_name = g_dbus_message_get_interface (message);
6495 member = g_dbus_message_get_member (message);
6496 signature = g_dbus_message_get_signature (message);
6497 path = g_dbus_message_get_path (message);
6499 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6500 g_strcmp0 (member, "Introspect") == 0 &&
6501 g_strcmp0 (signature, "") == 0)
6503 handle_generic_introspect_unlocked (connection, path, message);
6506 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6507 g_strcmp0 (member, "Ping") == 0 &&
6508 g_strcmp0 (signature, "") == 0)
6510 handle_generic_ping_unlocked (connection, path, message);
6513 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6514 g_strcmp0 (member, "GetMachineId") == 0 &&
6515 g_strcmp0 (signature, "") == 0)
6517 handle_generic_get_machine_id_unlocked (connection, path, message);
6524 /* ---------------------------------------------------------------------------------------------------- */
6526 /* called in GDBusWorker thread with connection's lock held */
6528 distribute_method_call (GDBusConnection *connection,
6529 GDBusMessage *message)
6531 GDBusMessage *reply;
6533 ExportedSubtree *es;
6534 const gchar *object_path;
6535 const gchar *interface_name;
6536 const gchar *member;
6538 gchar *subtree_path;
6541 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6543 interface_name = g_dbus_message_get_interface (message);
6544 member = g_dbus_message_get_member (message);
6545 path = g_dbus_message_get_path (message);
6546 subtree_path = g_strdup (path);
6547 needle = strrchr (subtree_path, '/');
6548 if (needle != NULL && needle != subtree_path)
6554 g_free (subtree_path);
6555 subtree_path = NULL;
6559 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6561 _g_dbus_debug_print_lock ();
6562 g_print ("========================================================================\n"
6563 "GDBus-debug:Incoming:\n"
6564 " <<<< METHOD INVOCATION %s.%s()\n"
6566 " invoked by name %s\n"
6568 interface_name, member,
6570 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6571 g_dbus_message_get_serial (message));
6572 _g_dbus_debug_print_unlock ();
6575 object_path = g_dbus_message_get_path (message);
6576 g_assert (object_path != NULL);
6578 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6581 if (obj_message_func (connection, eo, message))
6585 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6588 if (subtree_message_func (connection, es, message))
6592 if (subtree_path != NULL)
6594 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6597 if (subtree_message_func (connection, es, message))
6602 if (handle_generic_unlocked (connection, message))
6605 /* if we end up here, the message has not been not handled - so return an error saying this */
6606 reply = g_dbus_message_new_method_error (message,
6607 "org.freedesktop.DBus.Error.UnknownMethod",
6608 _("No such interface `%s' on object at path %s"),
6611 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6612 g_object_unref (reply);
6615 g_free (subtree_path);
6618 /* ---------------------------------------------------------------------------------------------------- */
6620 /* Called in any user thread, with the message_bus_lock held. */
6621 static GDBusConnection **
6622 message_bus_get_singleton (GBusType bus_type,
6625 GDBusConnection **ret;
6626 const gchar *starter_bus;
6632 case G_BUS_TYPE_SESSION:
6633 ret = &the_session_bus;
6636 case G_BUS_TYPE_SYSTEM:
6637 ret = &the_system_bus;
6640 case G_BUS_TYPE_STARTER:
6641 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6642 if (g_strcmp0 (starter_bus, "session") == 0)
6644 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6647 else if (g_strcmp0 (starter_bus, "system") == 0)
6649 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6654 if (starter_bus != NULL)
6658 G_IO_ERROR_INVALID_ARGUMENT,
6659 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6660 " - unknown value `%s'"),
6665 g_set_error_literal (error,
6667 G_IO_ERROR_INVALID_ARGUMENT,
6668 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6669 "variable is not set"));
6675 g_assert_not_reached ();
6683 /* Called in any user thread, without holding locks. */
6684 static GDBusConnection *
6685 get_uninitialized_connection (GBusType bus_type,
6686 GCancellable *cancellable,
6689 GDBusConnection **singleton;
6690 GDBusConnection *ret;
6694 G_LOCK (message_bus_lock);
6695 singleton = message_bus_get_singleton (bus_type, error);
6696 if (singleton == NULL)
6699 if (*singleton == NULL)
6702 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6703 if (address == NULL)
6705 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6707 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6708 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6709 "exit-on-close", TRUE,
6715 ret = g_object_ref (*singleton);
6718 g_assert (ret != NULL);
6721 G_UNLOCK (message_bus_lock);
6727 * @bus_type: A #GBusType.
6728 * @cancellable: A #GCancellable or %NULL.
6729 * @error: Return location for error or %NULL.
6731 * Synchronously connects to the message bus specified by @bus_type.
6732 * Note that the returned object may shared with other callers,
6733 * e.g. if two separate parts of a process calls this function with
6734 * the same @bus_type, they will share the same object.
6736 * This is a synchronous failable function. See g_bus_get() and
6737 * g_bus_get_finish() for the asynchronous version.
6739 * The returned object is a singleton, that is, shared with other
6740 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6741 * event that you need a private message bus connection, use
6742 * g_dbus_address_get_for_bus_sync() and
6743 * g_dbus_connection_new_for_address().
6745 * Note that the returned #GDBusConnection object will (usually) have
6746 * the #GDBusConnection:exit-on-close property set to %TRUE.
6748 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6753 g_bus_get_sync (GBusType bus_type,
6754 GCancellable *cancellable,
6757 GDBusConnection *connection;
6759 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6761 connection = get_uninitialized_connection (bus_type, cancellable, error);
6762 if (connection == NULL)
6765 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6767 g_object_unref (connection);
6776 bus_get_async_initable_cb (GObject *source_object,
6780 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6784 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6788 g_assert (error != NULL);
6789 g_simple_async_result_take_error (simple, error);
6790 g_object_unref (source_object);
6794 g_simple_async_result_set_op_res_gpointer (simple,
6798 g_simple_async_result_complete_in_idle (simple);
6799 g_object_unref (simple);
6804 * @bus_type: A #GBusType.
6805 * @cancellable: A #GCancellable or %NULL.
6806 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6807 * @user_data: The data to pass to @callback.
6809 * Asynchronously connects to the message bus specified by @bus_type.
6811 * When the operation is finished, @callback will be invoked. You can
6812 * then call g_bus_get_finish() to get the result of the operation.
6814 * This is a asynchronous failable function. See g_bus_get_sync() for
6815 * the synchronous version.
6820 g_bus_get (GBusType bus_type,
6821 GCancellable *cancellable,
6822 GAsyncReadyCallback callback,
6825 GDBusConnection *connection;
6826 GSimpleAsyncResult *simple;
6829 simple = g_simple_async_result_new (NULL,
6835 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6836 if (connection == NULL)
6838 g_assert (error != NULL);
6839 g_simple_async_result_take_error (simple, error);
6840 g_simple_async_result_complete_in_idle (simple);
6841 g_object_unref (simple);
6845 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6848 bus_get_async_initable_cb,
6855 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6856 * @error: Return location for error or %NULL.
6858 * Finishes an operation started with g_bus_get().
6860 * The returned object is a singleton, that is, shared with other
6861 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6862 * event that you need a private message bus connection, use
6863 * g_dbus_address_get_for_bus_sync() and
6864 * g_dbus_connection_new_for_address().
6866 * Note that the returned #GDBusConnection object will (usually) have
6867 * the #GDBusConnection:exit-on-close property set to %TRUE.
6869 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6874 g_bus_get_finish (GAsyncResult *res,
6877 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6879 GDBusConnection *ret;
6881 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6883 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6887 if (g_simple_async_result_propagate_error (simple, error))
6890 object = g_simple_async_result_get_op_res_gpointer (simple);
6891 g_assert (object != NULL);
6892 ret = g_object_ref (G_DBUS_CONNECTION (object));
6898 /* ---------------------------------------------------------------------------------------------------- */