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 (excect
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 acheive 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 "gio-marshal.h"
125 #include "ginitable.h"
126 #include "gasyncinitable.h"
127 #include "giostream.h"
128 #include "gasyncresult.h"
129 #include "gsimpleasyncresult.h"
132 #include "gunixconnection.h"
133 #include "gunixfdmessage.h"
136 #include "glibintl.h"
139 * SECTION:gdbusconnection
140 * @short_description: D-Bus Connections
141 * @include: gio/gio.h
143 * The #GDBusConnection type is used for D-Bus connections to remote
144 * peers such as a message buses. It is a low-level API that offers a
145 * lot of flexibility. For instance, it lets you establish a connection
146 * over any transport that can by represented as an #GIOStream.
148 * This class is rarely used directly in D-Bus clients. If you are writing
149 * an D-Bus client, it is often easier to use the g_bus_own_name(),
150 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
152 * <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>
154 * <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>
156 * <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>
158 * <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>
161 /* ---------------------------------------------------------------------------------------------------- */
163 typedef struct _GDBusConnectionClass GDBusConnectionClass;
166 * GDBusConnectionClass:
167 * @closed: Signal class handler for the #GDBusConnection::closed signal.
169 * Class structure for #GDBusConnection.
173 struct _GDBusConnectionClass
176 GObjectClass parent_class;
180 void (*closed) (GDBusConnection *connection,
181 gboolean remote_peer_vanished,
185 G_LOCK_DEFINE_STATIC (message_bus_lock);
187 static GDBusConnection *the_session_bus = NULL;
188 static GDBusConnection *the_system_bus = NULL;
190 /* ---------------------------------------------------------------------------------------------------- */
194 GDestroyNotify callback;
196 GMainContext *context;
197 } CallDestroyNotifyData;
200 call_destroy_notify_data_in_idle (gpointer user_data)
202 CallDestroyNotifyData *data = user_data;
203 data->callback (data->user_data);
208 call_destroy_notify_data_free (CallDestroyNotifyData *data)
210 if (data->context != NULL)
211 g_main_context_unref (data->context);
216 * call_destroy_notify: <internal>
217 * @context: A #GMainContext or %NULL.
218 * @callback: A #GDestroyNotify or %NULL.
219 * @user_data: Data to pass to @callback.
221 * Schedules @callback to run in @context.
224 call_destroy_notify (GMainContext *context,
225 GDestroyNotify callback,
228 if (callback == NULL)
231 if (context == g_main_context_get_thread_default ())
233 callback (user_data);
237 GSource *idle_source;
238 CallDestroyNotifyData *data;
240 data = g_new0 (CallDestroyNotifyData, 1);
241 data->callback = callback;
242 data->user_data = user_data;
243 data->context = context;
244 if (data->context != NULL)
245 g_main_context_ref (data->context);
247 idle_source = g_idle_source_new ();
248 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
249 g_source_set_callback (idle_source,
250 call_destroy_notify_data_in_idle,
252 (GDestroyNotify) call_destroy_notify_data_free);
253 g_source_attach (idle_source, data->context);
254 g_source_unref (idle_source);
261 /* ---------------------------------------------------------------------------------------------------- */
264 _g_strv_has_string (const gchar* const *haystack,
269 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
271 if (g_strcmp0 (haystack[n], needle) == 0)
277 /* ---------------------------------------------------------------------------------------------------- */
280 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
282 // TODO: for some reason this doesn't work on Windows
283 #define CONNECTION_ENSURE_LOCK(obj) do { \
284 if (G_UNLIKELY (g_mutex_trylock((obj)->lock))) \
286 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
287 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
292 #define CONNECTION_LOCK(obj) do { \
293 g_mutex_lock ((obj)->lock); \
296 #define CONNECTION_UNLOCK(obj) do { \
297 g_mutex_unlock ((obj)->lock); \
303 * The #GDBusConnection structure contains only private data and
304 * should only be accessed using the provided API.
308 struct _GDBusConnection
311 GObject parent_instance;
313 /* ------------------------------------------------------------------------ */
314 /* -- General object state ------------------------------------------------ */
315 /* ------------------------------------------------------------------------ */
317 /* object-wide lock */
320 /* A lock used in the init() method of the GInitable interface - see comments
321 * in initable_init() for why a separate lock is needed
325 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
326 * someone calls org.freedesktop.DBus.GetMachineId()
330 /* The underlying stream used for communication */
333 /* The object used for authentication (if any) */
336 /* Set to TRUE if the connection has been closed */
339 /* Last serial used */
342 /* The object used to send/receive message */
345 /* If connected to a message bus, this contains the unique name assigned to
346 * us by the bus (e.g. ":1.42")
348 gchar *bus_unique_name;
350 /* The GUID returned by the other side if we authenticed as a client or
351 * the GUID to use if authenticating as a server
355 /* set to TRUE exactly when initable_init() has finished running */
356 gboolean is_initialized;
358 /* If the connection could not be established during initable_init(), this GError will set */
359 GError *initialization_error;
361 /* The result of g_main_context_get_thread_default() when the object
362 * was created (the GObject _init() function) - this is used for delivery
363 * of the :closed GObject signal.
365 GMainContext *main_context_at_construction;
367 /* construct properties */
369 GDBusConnectionFlags flags;
371 /* Map used for managing method replies */
372 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
374 /* Maps used for managing signal subscription */
375 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
376 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
377 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
379 /* Maps used for managing exported objects and subtrees */
380 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
381 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
382 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
383 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
385 /* Structure used for message filters */
388 /* Whether to exit on close */
389 gboolean exit_on_close;
391 /* Capabilities negotiated during authentication */
392 GDBusCapabilityFlags capabilities;
394 GDBusAuthObserver *authentication_observer;
395 GCredentials *credentials;
397 /* set to TRUE when finalizing */
401 typedef struct ExportedObject ExportedObject;
402 static void exported_object_free (ExportedObject *eo);
404 typedef struct ExportedSubtree ExportedSubtree;
405 static void exported_subtree_free (ExportedSubtree *es);
423 PROP_CAPABILITY_FLAGS,
424 PROP_AUTHENTICATION_OBSERVER,
427 static void distribute_signals (GDBusConnection *connection,
428 GDBusMessage *message);
430 static void distribute_method_call (GDBusConnection *connection,
431 GDBusMessage *message);
433 static gboolean handle_generic_unlocked (GDBusConnection *connection,
434 GDBusMessage *message);
437 static void purge_all_signal_subscriptions (GDBusConnection *connection);
438 static void purge_all_filters (GDBusConnection *connection);
440 #define _G_ENSURE_LOCK(name) do { \
441 if (G_UNLIKELY (G_TRYLOCK(name))) \
443 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
444 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
448 static guint signals[LAST_SIGNAL] = { 0 };
450 static void initable_iface_init (GInitableIface *initable_iface);
451 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
453 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
454 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
455 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
458 static GHashTable *alive_connections = NULL;
461 g_dbus_connection_dispose (GObject *object)
463 GDBusConnection *connection = G_DBUS_CONNECTION (object);
465 G_LOCK (message_bus_lock);
466 if (connection == the_session_bus)
468 the_session_bus = NULL;
470 else if (connection == the_system_bus)
472 the_system_bus = NULL;
474 CONNECTION_LOCK (connection);
475 if (connection->worker != NULL)
477 _g_dbus_worker_stop (connection->worker);
478 connection->worker = NULL;
479 if (alive_connections != NULL)
480 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
484 if (alive_connections != NULL)
485 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
487 CONNECTION_UNLOCK (connection);
488 G_UNLOCK (message_bus_lock);
490 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
491 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
495 g_dbus_connection_finalize (GObject *object)
497 GDBusConnection *connection = G_DBUS_CONNECTION (object);
499 connection->finalizing = TRUE;
501 purge_all_signal_subscriptions (connection);
503 purge_all_filters (connection);
504 g_ptr_array_unref (connection->filters);
506 if (connection->authentication_observer != NULL)
507 g_object_unref (connection->authentication_observer);
509 if (connection->auth != NULL)
510 g_object_unref (connection->auth);
512 if (connection->credentials)
513 g_object_unref (connection->credentials);
515 if (connection->stream != NULL)
517 /* We don't really care if closing the stream succeeds or not */
518 g_io_stream_close_async (connection->stream,
520 NULL, /* GCancellable */
521 NULL, /* GAsyncReadyCallback */
522 NULL); /* userdata */
523 g_object_unref (connection->stream);
524 connection->stream = NULL;
527 g_free (connection->address);
529 g_free (connection->guid);
530 g_free (connection->bus_unique_name);
532 if (connection->initialization_error != NULL)
533 g_error_free (connection->initialization_error);
535 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
537 g_hash_table_unref (connection->map_rule_to_signal_data);
538 g_hash_table_unref (connection->map_id_to_signal_data);
539 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
541 g_hash_table_unref (connection->map_id_to_ei);
542 g_hash_table_unref (connection->map_object_path_to_eo);
543 g_hash_table_unref (connection->map_id_to_es);
544 g_hash_table_unref (connection->map_object_path_to_es);
546 if (connection->main_context_at_construction != NULL)
547 g_main_context_unref (connection->main_context_at_construction);
549 g_free (connection->machine_id);
551 g_mutex_free (connection->init_lock);
552 g_mutex_free (connection->lock);
554 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
558 g_dbus_connection_get_property (GObject *object,
563 GDBusConnection *connection = G_DBUS_CONNECTION (object);
568 g_value_set_object (value, g_dbus_connection_get_stream (connection));
572 g_value_set_string (value, g_dbus_connection_get_guid (connection));
575 case PROP_UNIQUE_NAME:
576 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
580 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
583 case PROP_EXIT_ON_CLOSE:
584 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
587 case PROP_CAPABILITY_FLAGS:
588 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
592 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
598 g_dbus_connection_set_property (GObject *object,
603 GDBusConnection *connection = G_DBUS_CONNECTION (object);
608 connection->stream = g_value_dup_object (value);
612 connection->guid = g_value_dup_string (value);
616 connection->address = g_value_dup_string (value);
620 connection->flags = g_value_get_flags (value);
623 case PROP_EXIT_ON_CLOSE:
624 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
627 case PROP_AUTHENTICATION_OBSERVER:
628 connection->authentication_observer = g_value_dup_object (value);
632 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
638 g_dbus_connection_real_closed (GDBusConnection *connection,
639 gboolean remote_peer_vanished,
642 if (remote_peer_vanished && connection->exit_on_close)
646 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
649 g_quark_to_string (error->domain), error->code);
653 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
660 g_dbus_connection_class_init (GDBusConnectionClass *klass)
662 GObjectClass *gobject_class;
664 gobject_class = G_OBJECT_CLASS (klass);
666 gobject_class->finalize = g_dbus_connection_finalize;
667 gobject_class->dispose = g_dbus_connection_dispose;
668 gobject_class->set_property = g_dbus_connection_set_property;
669 gobject_class->get_property = g_dbus_connection_get_property;
671 klass->closed = g_dbus_connection_real_closed;
674 * GDBusConnection:stream:
676 * The underlying #GIOStream used for I/O.
680 g_object_class_install_property (gobject_class,
682 g_param_spec_object ("stream",
684 P_("The underlying streams used for I/O"),
688 G_PARAM_CONSTRUCT_ONLY |
689 G_PARAM_STATIC_NAME |
690 G_PARAM_STATIC_BLURB |
691 G_PARAM_STATIC_NICK));
694 * GDBusConnection:address:
696 * A D-Bus address specifying potential endpoints that can be used
697 * when establishing the connection.
701 g_object_class_install_property (gobject_class,
703 g_param_spec_string ("address",
705 P_("D-Bus address specifying potential socket endpoints"),
708 G_PARAM_CONSTRUCT_ONLY |
709 G_PARAM_STATIC_NAME |
710 G_PARAM_STATIC_BLURB |
711 G_PARAM_STATIC_NICK));
714 * GDBusConnection:flags:
716 * Flags from the #GDBusConnectionFlags enumeration.
720 g_object_class_install_property (gobject_class,
722 g_param_spec_flags ("flags",
725 G_TYPE_DBUS_CONNECTION_FLAGS,
726 G_DBUS_CONNECTION_FLAGS_NONE,
728 G_PARAM_CONSTRUCT_ONLY |
729 G_PARAM_STATIC_NAME |
730 G_PARAM_STATIC_BLURB |
731 G_PARAM_STATIC_NICK));
734 * GDBusConnection:guid:
736 * The GUID of the peer performing the role of server when
739 * If you are constructing a #GDBusConnection and pass
740 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
741 * #GDBusConnection:flags property then you MUST also set this
742 * property to a valid guid.
744 * If you are constructing a #GDBusConnection and pass
745 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
746 * #GDBusConnection:flags property you will be able to read the GUID
747 * of the other peer here after the connection has been successfully
752 g_object_class_install_property (gobject_class,
754 g_param_spec_string ("guid",
756 P_("GUID of the server peer"),
760 G_PARAM_CONSTRUCT_ONLY |
761 G_PARAM_STATIC_NAME |
762 G_PARAM_STATIC_BLURB |
763 G_PARAM_STATIC_NICK));
766 * GDBusConnection:unique-name:
768 * The unique name as assigned by the message bus or %NULL if the
769 * connection is not open or not a message bus connection.
773 g_object_class_install_property (gobject_class,
775 g_param_spec_string ("unique-name",
777 P_("Unique name of bus connection"),
780 G_PARAM_STATIC_NAME |
781 G_PARAM_STATIC_BLURB |
782 G_PARAM_STATIC_NICK));
785 * GDBusConnection:closed:
787 * A boolean specifying whether the connection has been closed.
791 g_object_class_install_property (gobject_class,
793 g_param_spec_boolean ("closed",
795 P_("Whether the connection is closed"),
798 G_PARAM_STATIC_NAME |
799 G_PARAM_STATIC_BLURB |
800 G_PARAM_STATIC_NICK));
803 * GDBusConnection:exit-on-close:
805 * A boolean specifying whether the process will be terminated (by
806 * calling <literal>raise(SIGTERM)</literal>) if the connection
807 * is closed by the remote peer.
811 g_object_class_install_property (gobject_class,
813 g_param_spec_boolean ("exit-on-close",
815 P_("Whether the process is terminated when the connection is closed"),
819 G_PARAM_STATIC_NAME |
820 G_PARAM_STATIC_BLURB |
821 G_PARAM_STATIC_NICK));
824 * GDBusConnection:capabilities:
826 * Flags from the #GDBusCapabilityFlags enumeration
827 * representing connection features negotiated with the other peer.
831 g_object_class_install_property (gobject_class,
832 PROP_CAPABILITY_FLAGS,
833 g_param_spec_flags ("capabilities",
836 G_TYPE_DBUS_CAPABILITY_FLAGS,
837 G_DBUS_CAPABILITY_FLAGS_NONE,
839 G_PARAM_STATIC_NAME |
840 G_PARAM_STATIC_BLURB |
841 G_PARAM_STATIC_NICK));
844 * GDBusConnection:authentication-observer:
846 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
850 g_object_class_install_property (gobject_class,
851 PROP_AUTHENTICATION_OBSERVER,
852 g_param_spec_object ("authentication-observer",
853 P_("Authentication Observer"),
854 P_("Object used to assist in the authentication process"),
855 G_TYPE_DBUS_AUTH_OBSERVER,
857 G_PARAM_CONSTRUCT_ONLY |
858 G_PARAM_STATIC_NAME |
859 G_PARAM_STATIC_BLURB |
860 G_PARAM_STATIC_NICK));
863 * GDBusConnection::closed:
864 * @connection: The #GDBusConnection emitting the signal.
865 * @remote_peer_vanished: %TRUE if @connection is closed because the
866 * remote peer closed its end of the connection.
867 * @error: A #GError with more details about the event or %NULL.
869 * Emitted when the connection is closed.
871 * The cause of this event can be
874 * If g_dbus_connection_close() is called. In this case
875 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
878 * If the remote peer closes the connection. In this case
879 * @remote_peer_vanished is set to %TRUE and @error is set.
882 * If the remote peer sends invalid or malformed data. In this
883 * case @remote_peer_vanished is set to %FALSE and @error
888 * Upon receiving this signal, you should give up your reference to
889 * @connection. You are guaranteed that this signal is emitted only
894 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
895 G_TYPE_DBUS_CONNECTION,
897 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
900 _gio_marshal_VOID__BOOLEAN_BOXED,
908 g_dbus_connection_init (GDBusConnection *connection)
910 connection->lock = g_mutex_new ();
911 connection->init_lock = g_mutex_new ();
913 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
915 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
917 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
919 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
922 (GDestroyNotify) g_ptr_array_unref);
924 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
927 (GDestroyNotify) exported_object_free);
929 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
932 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
935 (GDestroyNotify) exported_subtree_free);
937 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
940 connection->main_context_at_construction = g_main_context_get_thread_default ();
941 if (connection->main_context_at_construction != NULL)
942 g_main_context_ref (connection->main_context_at_construction);
944 connection->filters = g_ptr_array_new ();
948 * g_dbus_connection_get_stream:
949 * @connection: a #GDBusConnection
951 * Gets the underlying stream used for IO.
953 * Returns: (transfer none): the stream used for IO
958 g_dbus_connection_get_stream (GDBusConnection *connection)
960 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
961 return connection->stream;
965 * g_dbus_connection_start_message_processing:
966 * @connection: A #GDBusConnection.
968 * If @connection was created with
969 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
970 * starts processing messages. Does nothing on if @connection wasn't
971 * created with this flag or if the method has already been called.
976 g_dbus_connection_start_message_processing (GDBusConnection *connection)
978 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
979 _g_dbus_worker_unfreeze (connection->worker);
983 * g_dbus_connection_is_closed:
984 * @connection: A #GDBusConnection.
986 * Gets whether @connection is closed.
988 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
993 g_dbus_connection_is_closed (GDBusConnection *connection)
995 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
996 return connection->closed;
1000 * g_dbus_connection_get_capabilities:
1001 * @connection: A #GDBusConnection.
1003 * Gets the capabilities negotiated with the remote peer
1005 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1009 GDBusCapabilityFlags
1010 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1012 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1013 return connection->capabilities;
1016 /* ---------------------------------------------------------------------------------------------------- */
1019 flush_in_thread_func (GSimpleAsyncResult *res,
1021 GCancellable *cancellable)
1026 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1029 g_simple_async_result_take_error (res, error);
1033 * g_dbus_connection_flush:
1034 * @connection: A #GDBusConnection.
1035 * @cancellable: A #GCancellable or %NULL.
1036 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1037 * care about the result.
1038 * @user_data: The data to pass to @callback.
1040 * Asynchronously flushes @connection, that is, writes all queued
1041 * outgoing message to the transport and then flushes the transport
1042 * (using g_output_stream_flush_async()). This is useful in programs
1043 * that wants to emit a D-Bus signal and then exit
1044 * immediately. Without flushing the connection, there is no guarantee
1045 * that the message has been sent to the networking buffers in the OS
1048 * This is an asynchronous method. When the operation is finished,
1049 * @callback will be invoked in the <link
1050 * linkend="g-main-context-push-thread-default">thread-default main
1051 * loop</link> of the thread you are calling this method from. You can
1052 * then call g_dbus_connection_flush_finish() to get the result of the
1053 * operation. See g_dbus_connection_flush_sync() for the synchronous
1059 g_dbus_connection_flush (GDBusConnection *connection,
1060 GCancellable *cancellable,
1061 GAsyncReadyCallback callback,
1064 GSimpleAsyncResult *simple;
1066 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1068 simple = g_simple_async_result_new (G_OBJECT (connection),
1071 g_dbus_connection_flush);
1072 g_simple_async_result_run_in_thread (simple,
1073 flush_in_thread_func,
1076 g_object_unref (simple);
1080 * g_dbus_connection_flush_finish:
1081 * @connection: A #GDBusConnection.
1082 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1083 * @error: Return location for error or %NULL.
1085 * Finishes an operation started with g_dbus_connection_flush().
1087 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1092 g_dbus_connection_flush_finish (GDBusConnection *connection,
1096 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1101 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1102 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1103 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1105 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1107 if (g_simple_async_result_propagate_error (simple, error))
1117 * g_dbus_connection_flush_sync:
1118 * @connection: A #GDBusConnection.
1119 * @cancellable: A #GCancellable or %NULL.
1120 * @error: Return location for error or %NULL.
1122 * Synchronously flushes @connection. The calling thread is blocked
1123 * until this is done. See g_dbus_connection_flush() for the
1124 * asynchronous version of this method and more details about what it
1127 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1132 g_dbus_connection_flush_sync (GDBusConnection *connection,
1133 GCancellable *cancellable,
1138 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1139 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1143 if (connection->closed)
1145 g_set_error_literal (error,
1148 _("The connection is closed"));
1152 ret = _g_dbus_worker_flush_sync (connection->worker,
1160 /* ---------------------------------------------------------------------------------------------------- */
1164 GDBusConnection *connection;
1166 gboolean remote_peer_vanished;
1170 emit_closed_data_free (EmitClosedData *data)
1172 g_object_unref (data->connection);
1173 if (data->error != NULL)
1174 g_error_free (data->error);
1179 emit_closed_in_idle (gpointer user_data)
1181 EmitClosedData *data = user_data;
1184 g_object_notify (G_OBJECT (data->connection), "closed");
1185 g_signal_emit (data->connection,
1186 signals[CLOSED_SIGNAL],
1188 data->remote_peer_vanished,
1194 /* Can be called from any thread, must hold lock */
1196 set_closed_unlocked (GDBusConnection *connection,
1197 gboolean remote_peer_vanished,
1200 GSource *idle_source;
1201 EmitClosedData *data;
1203 CONNECTION_ENSURE_LOCK (connection);
1205 g_assert (!connection->closed);
1207 connection->closed = TRUE;
1209 data = g_new0 (EmitClosedData, 1);
1210 data->connection = g_object_ref (connection);
1211 data->remote_peer_vanished = remote_peer_vanished;
1212 data->error = error != NULL ? g_error_copy (error) : NULL;
1214 idle_source = g_idle_source_new ();
1215 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1216 g_source_set_callback (idle_source,
1217 emit_closed_in_idle,
1219 (GDestroyNotify) emit_closed_data_free);
1220 g_source_attach (idle_source, connection->main_context_at_construction);
1221 g_source_unref (idle_source);
1224 /* ---------------------------------------------------------------------------------------------------- */
1227 close_in_thread_func (GSimpleAsyncResult *res,
1229 GCancellable *cancellable)
1234 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1237 g_simple_async_result_take_error (res, error);
1241 * g_dbus_connection_close:
1242 * @connection: A #GDBusConnection.
1243 * @cancellable: A #GCancellable or %NULL.
1244 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1245 * care about the result.
1246 * @user_data: The data to pass to @callback.
1248 * Closes @connection. Note that this never causes the process to
1249 * exit (this might only happen if the other end of a shared message
1250 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1252 * Once the connection is closed, operations such as sending a message
1253 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1254 * will not automatically flush the connection so queued messages may
1255 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1257 * If @connection is already closed, this method fails with
1258 * %G_IO_ERROR_CLOSED.
1260 * When @connection has been closed, the #GDBusConnection::closed
1261 * signal is emitted in the <link
1262 * linkend="g-main-context-push-thread-default">thread-default main
1263 * loop</link> of the thread that @connection was constructed in.
1265 * This is an asynchronous method. When the operation is finished,
1266 * @callback will be invoked in the <link
1267 * linkend="g-main-context-push-thread-default">thread-default main
1268 * loop</link> of the thread you are calling this method from. You can
1269 * then call g_dbus_connection_close_finish() to get the result of the
1270 * operation. See g_dbus_connection_close_sync() for the synchronous
1276 g_dbus_connection_close (GDBusConnection *connection,
1277 GCancellable *cancellable,
1278 GAsyncReadyCallback callback,
1281 GSimpleAsyncResult *simple;
1283 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1285 simple = g_simple_async_result_new (G_OBJECT (connection),
1288 g_dbus_connection_close);
1289 g_simple_async_result_run_in_thread (simple,
1290 close_in_thread_func,
1293 g_object_unref (simple);
1297 * g_dbus_connection_close_finish:
1298 * @connection: A #GDBusConnection.
1299 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1300 * @error: Return location for error or %NULL.
1302 * Finishes an operation started with g_dbus_connection_close().
1304 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1309 g_dbus_connection_close_finish (GDBusConnection *connection,
1313 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1318 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1319 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1320 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1322 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1324 if (g_simple_async_result_propagate_error (simple, error))
1334 * g_dbus_connection_close_sync:
1335 * @connection: A #GDBusConnection.
1336 * @cancellable: A #GCancellable or %NULL.
1337 * @error: Return location for error or %NULL.
1339 * Synchronously closees @connection. The calling thread is blocked
1340 * until this is done. See g_dbus_connection_close() for the
1341 * asynchronous version of this method and more details about what it
1344 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1349 g_dbus_connection_close_sync (GDBusConnection *connection,
1350 GCancellable *cancellable,
1355 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1356 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1360 CONNECTION_LOCK (connection);
1361 if (!connection->closed)
1363 ret = g_io_stream_close (connection->stream,
1367 set_closed_unlocked (connection, FALSE, NULL);
1371 g_set_error_literal (error,
1374 _("The connection is closed"));
1376 CONNECTION_UNLOCK (connection);
1381 /* ---------------------------------------------------------------------------------------------------- */
1384 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1385 GDBusMessage *message,
1386 GDBusSendMessageFlags flags,
1387 volatile guint32 *out_serial,
1392 guint32 serial_to_use;
1395 CONNECTION_ENSURE_LOCK (connection);
1397 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1398 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1400 /* TODO: check all necessary headers are present */
1405 if (out_serial != NULL)
1408 if (connection->closed)
1410 g_set_error_literal (error,
1413 _("The connection is closed"));
1417 blob = g_dbus_message_to_blob (message,
1419 connection->capabilities,
1424 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1425 serial_to_use = g_dbus_message_get_serial (message);
1427 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1432 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1435 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1438 g_assert_not_reached ();
1443 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1444 blob_size, serial_to_use, connection);
1445 g_printerr ("----\n");
1446 hexdump (blob, blob_size);
1447 g_printerr ("----\n");
1450 /* TODO: use connection->auth to encode the blob */
1452 if (out_serial != NULL)
1453 *out_serial = serial_to_use;
1455 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1456 g_dbus_message_set_serial (message, serial_to_use);
1458 g_dbus_message_lock (message);
1459 _g_dbus_worker_send_message (connection->worker,
1463 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1474 * g_dbus_connection_send_message:
1475 * @connection: A #GDBusConnection.
1476 * @message: A #GDBusMessage
1477 * @flags: Flags affecting how the message is sent.
1478 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1479 * @error: Return location for error or %NULL.
1481 * Asynchronously sends @message to the peer represented by @connection.
1483 * Unless @flags contain the
1484 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1485 * will be assigned by @connection and set on @message via
1486 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1487 * serial number used will be written to this location prior to
1488 * submitting the message to the underlying transport.
1490 * If @connection is closed then the operation will fail with
1491 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1492 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1494 * See <xref linkend="gdbus-server"/> and <xref
1495 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1496 * low-level API to send and receive UNIX file descriptors.
1498 * Note that @message must be unlocked, unless @flags contain the
1499 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1501 * Returns: %TRUE if the message was well-formed and queued for
1502 * transmission, %FALSE if @error is set.
1507 g_dbus_connection_send_message (GDBusConnection *connection,
1508 GDBusMessage *message,
1509 GDBusSendMessageFlags flags,
1510 volatile guint32 *out_serial,
1515 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1516 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1517 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1518 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1520 CONNECTION_LOCK (connection);
1521 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1522 CONNECTION_UNLOCK (connection);
1526 /* ---------------------------------------------------------------------------------------------------- */
1530 volatile gint ref_count;
1531 GDBusConnection *connection;
1533 GSimpleAsyncResult *simple;
1535 GMainContext *main_context;
1537 GCancellable *cancellable;
1539 gulong cancellable_handler_id;
1541 GSource *timeout_source;
1546 static SendMessageData *
1547 send_message_data_ref (SendMessageData *data)
1549 g_atomic_int_inc (&data->ref_count);
1554 send_message_data_unref (SendMessageData *data)
1556 if (g_atomic_int_dec_and_test (&data->ref_count))
1558 g_assert (data->timeout_source == NULL);
1559 g_assert (data->simple == NULL);
1560 g_assert (data->cancellable_handler_id == 0);
1561 g_object_unref (data->connection);
1562 if (data->cancellable != NULL)
1563 g_object_unref (data->cancellable);
1564 if (data->main_context != NULL)
1565 g_main_context_unref (data->main_context);
1570 /* ---------------------------------------------------------------------------------------------------- */
1572 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1574 send_message_with_reply_deliver (SendMessageData *data)
1576 CONNECTION_ENSURE_LOCK (data->connection);
1578 g_assert (!data->delivered);
1580 data->delivered = TRUE;
1582 g_simple_async_result_complete_in_idle (data->simple);
1583 g_object_unref (data->simple);
1584 data->simple = NULL;
1586 if (data->timeout_source != NULL)
1588 g_source_destroy (data->timeout_source);
1589 data->timeout_source = NULL;
1591 if (data->cancellable_handler_id > 0)
1593 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1594 data->cancellable_handler_id = 0;
1597 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1598 GUINT_TO_POINTER (data->serial)));
1600 send_message_data_unref (data);
1603 /* ---------------------------------------------------------------------------------------------------- */
1605 /* must hold lock */
1607 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1608 GDBusMessage *reply)
1610 if (data->delivered)
1613 g_simple_async_result_set_op_res_gpointer (data->simple,
1614 g_object_ref (reply),
1617 send_message_with_reply_deliver (data);
1623 /* ---------------------------------------------------------------------------------------------------- */
1626 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1628 SendMessageData *data = user_data;
1630 CONNECTION_LOCK (data->connection);
1631 if (data->delivered)
1634 g_simple_async_result_set_error (data->simple,
1636 G_IO_ERROR_CANCELLED,
1637 _("Operation was cancelled"));
1639 send_message_with_reply_deliver (data);
1642 CONNECTION_UNLOCK (data->connection);
1646 /* Can be called from any thread with or without lock held */
1648 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1651 SendMessageData *data = user_data;
1652 GSource *idle_source;
1654 /* postpone cancellation to idle handler since we may be called directly
1655 * via g_cancellable_connect() (e.g. holding lock)
1657 idle_source = g_idle_source_new ();
1658 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1659 g_source_set_callback (idle_source,
1660 send_message_with_reply_cancelled_idle_cb,
1661 send_message_data_ref (data),
1662 (GDestroyNotify) send_message_data_unref);
1663 g_source_attach (idle_source, data->main_context);
1664 g_source_unref (idle_source);
1667 /* ---------------------------------------------------------------------------------------------------- */
1670 send_message_with_reply_timeout_cb (gpointer user_data)
1672 SendMessageData *data = user_data;
1674 CONNECTION_LOCK (data->connection);
1675 if (data->delivered)
1678 g_simple_async_result_set_error (data->simple,
1680 G_IO_ERROR_TIMED_OUT,
1681 _("Timeout was reached"));
1683 send_message_with_reply_deliver (data);
1686 CONNECTION_UNLOCK (data->connection);
1691 /* ---------------------------------------------------------------------------------------------------- */
1694 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1695 GDBusMessage *message,
1696 GDBusSendMessageFlags flags,
1698 volatile guint32 *out_serial,
1699 GCancellable *cancellable,
1700 GAsyncReadyCallback callback,
1703 GSimpleAsyncResult *simple;
1704 SendMessageData *data;
1706 volatile guint32 serial;
1710 if (out_serial == NULL)
1711 out_serial = &serial;
1713 if (timeout_msec == -1)
1714 timeout_msec = 25 * 1000;
1716 simple = g_simple_async_result_new (G_OBJECT (connection),
1719 g_dbus_connection_send_message_with_reply);
1721 if (g_cancellable_is_cancelled (cancellable))
1723 g_simple_async_result_set_error (simple,
1725 G_IO_ERROR_CANCELLED,
1726 _("Operation was cancelled"));
1727 g_simple_async_result_complete_in_idle (simple);
1728 g_object_unref (simple);
1732 if (connection->closed)
1734 g_simple_async_result_set_error (simple,
1737 _("The connection is closed"));
1738 g_simple_async_result_complete_in_idle (simple);
1739 g_object_unref (simple);
1744 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1746 g_simple_async_result_take_error (simple, error);
1747 g_simple_async_result_complete_in_idle (simple);
1748 g_object_unref (simple);
1752 data = g_new0 (SendMessageData, 1);
1753 data->ref_count = 1;
1754 data->connection = g_object_ref (connection);
1755 data->simple = simple;
1756 data->serial = *out_serial;
1757 data->main_context = g_main_context_get_thread_default ();
1758 if (data->main_context != NULL)
1759 g_main_context_ref (data->main_context);
1761 if (cancellable != NULL)
1763 data->cancellable = g_object_ref (cancellable);
1764 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1765 G_CALLBACK (send_message_with_reply_cancelled_cb),
1766 send_message_data_ref (data),
1767 (GDestroyNotify) send_message_data_unref);
1768 g_object_set_data_full (G_OBJECT (simple),
1770 g_object_ref (cancellable),
1771 (GDestroyNotify) g_object_unref);
1774 if (timeout_msec != G_MAXINT)
1776 data->timeout_source = g_timeout_source_new (timeout_msec);
1777 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1778 g_source_set_callback (data->timeout_source,
1779 send_message_with_reply_timeout_cb,
1780 send_message_data_ref (data),
1781 (GDestroyNotify) send_message_data_unref);
1782 g_source_attach (data->timeout_source, data->main_context);
1783 g_source_unref (data->timeout_source);
1786 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1787 GUINT_TO_POINTER (*out_serial),
1795 * g_dbus_connection_send_message_with_reply:
1796 * @connection: A #GDBusConnection.
1797 * @message: A #GDBusMessage.
1798 * @flags: Flags affecting how the message is sent.
1799 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1800 * timeout or %G_MAXINT for no timeout.
1801 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1802 * @cancellable: A #GCancellable or %NULL.
1803 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1804 * care about the result.
1805 * @user_data: The data to pass to @callback.
1807 * Asynchronously sends @message to the peer represented by @connection.
1809 * Unless @flags contain the
1810 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1811 * will be assigned by @connection and set on @message via
1812 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1813 * serial number used will be written to this location prior to
1814 * submitting the message to the underlying transport.
1816 * If @connection is closed then the operation will fail with
1817 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1818 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1819 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1821 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1822 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1823 * of the thread you are calling this method from. You can then call
1824 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1825 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1827 * Note that @message must be unlocked, unless @flags contain the
1828 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1830 * See <xref linkend="gdbus-server"/> and <xref
1831 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1832 * low-level API to send and receive UNIX file descriptors.
1837 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1838 GDBusMessage *message,
1839 GDBusSendMessageFlags flags,
1841 volatile guint32 *out_serial,
1842 GCancellable *cancellable,
1843 GAsyncReadyCallback callback,
1846 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1847 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1848 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1849 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1851 CONNECTION_LOCK (connection);
1852 g_dbus_connection_send_message_with_reply_unlocked (connection,
1860 CONNECTION_UNLOCK (connection);
1864 * g_dbus_connection_send_message_with_reply_finish:
1865 * @connection: a #GDBusConnection
1866 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1867 * @error: Return location for error or %NULL.
1869 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1871 * Note that @error is only set if a local in-process error
1872 * occured. That is to say that the returned #GDBusMessage object may
1873 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1874 * g_dbus_message_to_gerror() to transcode this to a #GError.
1876 * See <xref linkend="gdbus-server"/> and <xref
1877 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1878 * low-level API to send and receive UNIX file descriptors.
1880 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
1885 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1889 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1890 GDBusMessage *reply;
1891 GCancellable *cancellable;
1893 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1894 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1898 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1900 if (g_simple_async_result_propagate_error (simple, error))
1903 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1904 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1905 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1907 g_object_unref (reply);
1909 g_set_error_literal (error,
1911 G_IO_ERROR_CANCELLED,
1912 _("Operation was cancelled"));
1918 /* ---------------------------------------------------------------------------------------------------- */
1923 GMainContext *context;
1925 } SendMessageSyncData;
1928 send_message_with_reply_sync_cb (GDBusConnection *connection,
1932 SendMessageSyncData *data = user_data;
1933 data->res = g_object_ref (res);
1934 g_main_loop_quit (data->loop);
1938 * g_dbus_connection_send_message_with_reply_sync:
1939 * @connection: A #GDBusConnection.
1940 * @message: A #GDBusMessage.
1941 * @flags: Flags affecting how the message is sent.
1942 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1943 * timeout or %G_MAXINT for no timeout.
1944 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1945 * @cancellable: A #GCancellable or %NULL.
1946 * @error: Return location for error or %NULL.
1948 * Synchronously sends @message to the peer represented by @connection
1949 * and blocks the calling thread until a reply is received or the
1950 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1951 * for the asynchronous version of this method.
1953 * Unless @flags contain the
1954 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1955 * will be assigned by @connection and set on @message via
1956 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1957 * serial number used will be written to this location prior to
1958 * submitting the message to the underlying transport.
1960 * If @connection is closed then the operation will fail with
1961 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1962 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1963 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1965 * Note that @error is only set if a local in-process error
1966 * occured. That is to say that the returned #GDBusMessage object may
1967 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1968 * g_dbus_message_to_gerror() to transcode this to a #GError.
1970 * See <xref linkend="gdbus-server"/> and <xref
1971 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1972 * low-level API to send and receive UNIX file descriptors.
1974 * Note that @message must be unlocked, unless @flags contain the
1975 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1977 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
1982 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1983 GDBusMessage *message,
1984 GDBusSendMessageFlags flags,
1986 volatile guint32 *out_serial,
1987 GCancellable *cancellable,
1990 SendMessageSyncData *data;
1991 GDBusMessage *reply;
1993 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1994 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1995 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1996 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1997 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1999 data = g_new0 (SendMessageSyncData, 1);
2000 data->context = g_main_context_new ();
2001 data->loop = g_main_loop_new (data->context, FALSE);
2003 g_main_context_push_thread_default (data->context);
2005 g_dbus_connection_send_message_with_reply (connection,
2011 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2013 g_main_loop_run (data->loop);
2014 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2018 g_main_context_pop_thread_default (data->context);
2020 g_main_context_unref (data->context);
2021 g_main_loop_unref (data->loop);
2022 g_object_unref (data->res);
2028 /* ---------------------------------------------------------------------------------------------------- */
2032 GDBusMessageFilterFunction func;
2039 GDBusMessageFilterFunction filter_function;
2041 GDestroyNotify user_data_free_func;
2044 /* Called in worker's thread - we must not block */
2046 on_worker_message_received (GDBusWorker *worker,
2047 GDBusMessage *message,
2050 GDBusConnection *connection;
2051 FilterCallback *filters;
2052 gboolean consumed_by_filter;
2053 gboolean altered_by_filter;
2058 G_LOCK (message_bus_lock);
2059 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2062 G_UNLOCK (message_bus_lock);
2065 connection = G_DBUS_CONNECTION (user_data);
2066 g_object_ref (connection);
2067 G_UNLOCK (message_bus_lock);
2069 //g_debug ("in on_worker_message_received");
2071 g_object_ref (message);
2072 g_dbus_message_lock (message);
2074 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2076 /* First collect the set of callback functions */
2077 CONNECTION_LOCK (connection);
2078 num_filters = connection->filters->len;
2079 filters = g_new0 (FilterCallback, num_filters);
2080 for (n = 0; n < num_filters; n++)
2082 FilterData *data = connection->filters->pdata[n];
2083 filters[n].func = data->filter_function;
2084 filters[n].user_data = data->user_data;
2086 CONNECTION_UNLOCK (connection);
2088 /* then call the filters in order (without holding the lock) */
2089 consumed_by_filter = FALSE;
2090 altered_by_filter = FALSE;
2091 for (n = 0; n < num_filters; n++)
2093 message = filters[n].func (connection,
2096 filters[n].user_data);
2097 if (message == NULL)
2099 g_dbus_message_lock (message);
2102 /* Standard dispatch unless the filter ate the message - no need to
2103 * do anything if the message was altered
2105 if (message != NULL)
2107 GDBusMessageType message_type;
2109 message_type = g_dbus_message_get_message_type (message);
2110 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2112 guint32 reply_serial;
2113 SendMessageData *send_message_data;
2115 reply_serial = g_dbus_message_get_reply_serial (message);
2116 CONNECTION_LOCK (connection);
2117 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2118 GUINT_TO_POINTER (reply_serial));
2119 if (send_message_data != NULL)
2121 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2122 send_message_data_deliver_reply_unlocked (send_message_data, message);
2126 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2128 CONNECTION_UNLOCK (connection);
2130 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2132 CONNECTION_LOCK (connection);
2133 distribute_signals (connection, message);
2134 CONNECTION_UNLOCK (connection);
2136 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2138 CONNECTION_LOCK (connection);
2139 distribute_method_call (connection, message);
2140 CONNECTION_UNLOCK (connection);
2144 if (message != NULL)
2145 g_object_unref (message);
2146 g_object_unref (connection);
2150 /* Called in worker's thread */
2151 static GDBusMessage *
2152 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2153 GDBusMessage *message,
2156 GDBusConnection *connection;
2157 FilterCallback *filters;
2162 G_LOCK (message_bus_lock);
2163 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2166 G_UNLOCK (message_bus_lock);
2169 connection = G_DBUS_CONNECTION (user_data);
2170 g_object_ref (connection);
2171 G_UNLOCK (message_bus_lock);
2173 //g_debug ("in on_worker_message_about_to_be_sent");
2175 /* First collect the set of callback functions */
2176 CONNECTION_LOCK (connection);
2177 num_filters = connection->filters->len;
2178 filters = g_new0 (FilterCallback, num_filters);
2179 for (n = 0; n < num_filters; n++)
2181 FilterData *data = connection->filters->pdata[n];
2182 filters[n].func = data->filter_function;
2183 filters[n].user_data = data->user_data;
2185 CONNECTION_UNLOCK (connection);
2187 /* then call the filters in order (without holding the lock) */
2188 for (n = 0; n < num_filters; n++)
2190 g_dbus_message_lock (message);
2191 message = filters[n].func (connection,
2194 filters[n].user_data);
2195 if (message == NULL)
2199 g_object_unref (connection);
2205 /* Called in worker's thread - we must not block */
2207 on_worker_closed (GDBusWorker *worker,
2208 gboolean remote_peer_vanished,
2212 GDBusConnection *connection;
2215 G_LOCK (message_bus_lock);
2216 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2219 G_UNLOCK (message_bus_lock);
2222 connection = G_DBUS_CONNECTION (user_data);
2223 g_object_ref (connection);
2224 G_UNLOCK (message_bus_lock);
2226 //g_debug ("in on_worker_closed: %s", error->message);
2228 CONNECTION_LOCK (connection);
2229 if (!connection->closed)
2230 set_closed_unlocked (connection, remote_peer_vanished, error);
2231 CONNECTION_UNLOCK (connection);
2233 g_object_unref (connection);
2236 /* ---------------------------------------------------------------------------------------------------- */
2238 /* Determines the biggest set of capabilities we can support on this connection */
2239 static GDBusCapabilityFlags
2240 get_offered_capabilities_max (GDBusConnection *connection)
2242 GDBusCapabilityFlags ret;
2243 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2245 if (G_IS_UNIX_CONNECTION (connection->stream))
2246 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2252 initable_init (GInitable *initable,
2253 GCancellable *cancellable,
2256 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2259 /* This method needs to be idempotent to work with the singleton
2260 * pattern. See the docs for g_initable_init(). We implement this by
2263 * Unfortunately we can't use the main lock since the on_worker_*()
2264 * callbacks above needs the lock during initialization (for message
2265 * bus connections we do a synchronous Hello() call on the bus).
2267 g_mutex_lock (connection->init_lock);
2271 if (connection->is_initialized)
2273 if (connection->stream != NULL)
2276 g_assert (connection->initialization_error != NULL);
2279 g_assert (connection->initialization_error == NULL);
2281 /* The user can pass multiple (but mutally exclusive) construct
2284 * - stream (of type GIOStream)
2285 * - address (of type gchar*)
2287 * At the end of the day we end up with a non-NULL GIOStream
2288 * object in connection->stream.
2290 if (connection->address != NULL)
2292 g_assert (connection->stream == NULL);
2294 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2295 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2297 g_set_error_literal (error,
2299 G_IO_ERROR_INVALID_ARGUMENT,
2300 _("Unsupported flags encountered when constructing a client-side connection"));
2304 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2305 NULL, /* TODO: out_guid */
2307 &connection->initialization_error);
2308 if (connection->stream == NULL)
2311 else if (connection->stream != NULL)
2317 g_assert_not_reached ();
2320 /* Authenticate the connection */
2321 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2323 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2324 g_assert (connection->guid != NULL);
2325 connection->auth = _g_dbus_auth_new (connection->stream);
2326 if (!_g_dbus_auth_run_server (connection->auth,
2327 connection->authentication_observer,
2329 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2330 get_offered_capabilities_max (connection),
2331 &connection->capabilities,
2332 &connection->credentials,
2334 &connection->initialization_error))
2337 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2339 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2340 g_assert (connection->guid == NULL);
2341 connection->auth = _g_dbus_auth_new (connection->stream);
2342 connection->guid = _g_dbus_auth_run_client (connection->auth,
2343 get_offered_capabilities_max (connection),
2344 &connection->capabilities,
2346 &connection->initialization_error);
2347 if (connection->guid == NULL)
2351 if (connection->authentication_observer != NULL)
2353 g_object_unref (connection->authentication_observer);
2354 connection->authentication_observer = NULL;
2357 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2359 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2364 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
2368 if (G_IS_SOCKET_CONNECTION (connection->stream))
2370 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2374 G_LOCK (message_bus_lock);
2375 if (alive_connections == NULL)
2376 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2377 g_hash_table_insert (alive_connections, connection, connection);
2378 G_UNLOCK (message_bus_lock);
2380 connection->worker = _g_dbus_worker_new (connection->stream,
2381 connection->capabilities,
2382 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2383 on_worker_message_received,
2384 on_worker_message_about_to_be_sent,
2388 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2389 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2391 GVariant *hello_result;
2393 /* we could lift this restriction by adding code in gdbusprivate.c */
2394 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2396 g_set_error_literal (&connection->initialization_error,
2399 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2403 hello_result = g_dbus_connection_call_sync (connection,
2404 "org.freedesktop.DBus", /* name */
2405 "/org/freedesktop/DBus", /* path */
2406 "org.freedesktop.DBus", /* interface */
2408 NULL, /* parameters */
2409 G_VARIANT_TYPE ("(s)"),
2410 G_DBUS_CALL_FLAGS_NONE,
2412 NULL, /* TODO: cancellable */
2413 &connection->initialization_error);
2414 if (hello_result == NULL)
2417 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2418 g_variant_unref (hello_result);
2419 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2422 connection->is_initialized = TRUE;
2428 g_assert (connection->initialization_error != NULL);
2429 g_propagate_error (error, g_error_copy (connection->initialization_error));
2432 g_mutex_unlock (connection->init_lock);
2438 initable_iface_init (GInitableIface *initable_iface)
2440 initable_iface->init = initable_init;
2443 /* ---------------------------------------------------------------------------------------------------- */
2446 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2451 /* ---------------------------------------------------------------------------------------------------- */
2454 * g_dbus_connection_new:
2455 * @stream: A #GIOStream.
2456 * @guid: The GUID to use if a authenticating as a server or %NULL.
2457 * @flags: Flags describing how to make the connection.
2458 * @observer: A #GDBusAuthObserver or %NULL.
2459 * @cancellable: A #GCancellable or %NULL.
2460 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2461 * @user_data: The data to pass to @callback.
2463 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2464 * with the end represented by @stream.
2466 * If @observer is not %NULL it may be used to control the
2467 * authentication process.
2469 * When the operation is finished, @callback will be invoked. You can
2470 * then call g_dbus_connection_new_finish() to get the result of the
2473 * This is a asynchronous failable constructor. See
2474 * g_dbus_connection_new_sync() for the synchronous
2480 g_dbus_connection_new (GIOStream *stream,
2482 GDBusConnectionFlags flags,
2483 GDBusAuthObserver *observer,
2484 GCancellable *cancellable,
2485 GAsyncReadyCallback callback,
2488 g_return_if_fail (G_IS_IO_STREAM (stream));
2489 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2497 "authentication-observer", observer,
2502 * g_dbus_connection_new_finish:
2503 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2504 * @error: Return location for error or %NULL.
2506 * Finishes an operation started with g_dbus_connection_new().
2508 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2513 g_dbus_connection_new_finish (GAsyncResult *res,
2517 GObject *source_object;
2519 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2520 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2522 source_object = g_async_result_get_source_object (res);
2523 g_assert (source_object != NULL);
2524 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2527 g_object_unref (source_object);
2529 return G_DBUS_CONNECTION (object);
2535 * g_dbus_connection_new_sync:
2536 * @stream: A #GIOStream.
2537 * @guid: The GUID to use if a authenticating as a server or %NULL.
2538 * @flags: Flags describing how to make the connection.
2539 * @observer: A #GDBusAuthObserver or %NULL.
2540 * @cancellable: A #GCancellable or %NULL.
2541 * @error: Return location for error or %NULL.
2543 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2544 * with the end represented by @stream.
2546 * If @observer is not %NULL it may be used to control the
2547 * authentication process.
2549 * This is a synchronous failable constructor. See
2550 * g_dbus_connection_new() for the asynchronous version.
2552 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2557 g_dbus_connection_new_sync (GIOStream *stream,
2559 GDBusConnectionFlags flags,
2560 GDBusAuthObserver *observer,
2561 GCancellable *cancellable,
2564 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2565 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2566 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2572 "authentication-observer", observer,
2576 /* ---------------------------------------------------------------------------------------------------- */
2579 * g_dbus_connection_new_for_address:
2580 * @address: A D-Bus address.
2581 * @flags: Flags describing how to make the connection.
2582 * @observer: A #GDBusAuthObserver or %NULL.
2583 * @cancellable: A #GCancellable or %NULL.
2584 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2585 * @user_data: The data to pass to @callback.
2587 * Asynchronously connects and sets up a D-Bus client connection for
2588 * exchanging D-Bus messages with an endpoint specified by @address
2589 * which must be in the D-Bus address format.
2591 * This constructor can only be used to initiate client-side
2592 * connections - use g_dbus_connection_new() if you need to act as the
2593 * server. In particular, @flags cannot contain the
2594 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2595 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2597 * When the operation is finished, @callback will be invoked. You can
2598 * then call g_dbus_connection_new_finish() to get the result of the
2601 * If @observer is not %NULL it may be used to control the
2602 * authentication process.
2604 * This is a asynchronous failable constructor. See
2605 * g_dbus_connection_new_for_address_sync() for the synchronous
2611 g_dbus_connection_new_for_address (const gchar *address,
2612 GDBusConnectionFlags flags,
2613 GDBusAuthObserver *observer,
2614 GCancellable *cancellable,
2615 GAsyncReadyCallback callback,
2618 g_return_if_fail (address != NULL);
2619 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2626 "authentication-observer", observer,
2631 * g_dbus_connection_new_for_address_finish:
2632 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2633 * @error: Return location for error or %NULL.
2635 * Finishes an operation started with g_dbus_connection_new_for_address().
2637 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2642 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2646 GObject *source_object;
2648 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2649 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2651 source_object = g_async_result_get_source_object (res);
2652 g_assert (source_object != NULL);
2653 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2656 g_object_unref (source_object);
2658 return G_DBUS_CONNECTION (object);
2664 * g_dbus_connection_new_for_address_sync:
2665 * @address: A D-Bus address.
2666 * @flags: Flags describing how to make the connection.
2667 * @observer: A #GDBusAuthObserver or %NULL.
2668 * @cancellable: A #GCancellable or %NULL.
2669 * @error: Return location for error or %NULL.
2671 * Synchronously connects and sets up a D-Bus client connection for
2672 * exchanging D-Bus messages with an endpoint specified by @address
2673 * which must be in the D-Bus address format.
2675 * This constructor can only be used to initiate client-side
2676 * connections - use g_dbus_connection_new_sync() if you need to act
2677 * as the server. In particular, @flags cannot contain the
2678 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2679 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2681 * This is a synchronous failable constructor. See
2682 * g_dbus_connection_new_for_address() for the asynchronous version.
2684 * If @observer is not %NULL it may be used to control the
2685 * authentication process.
2687 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2692 g_dbus_connection_new_for_address_sync (const gchar *address,
2693 GDBusConnectionFlags flags,
2694 GDBusAuthObserver *observer,
2695 GCancellable *cancellable,
2698 g_return_val_if_fail (address != NULL, NULL);
2699 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2700 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2705 "authentication-observer", observer,
2709 /* ---------------------------------------------------------------------------------------------------- */
2712 * g_dbus_connection_set_exit_on_close:
2713 * @connection: A #GDBusConnection.
2714 * @exit_on_close: Whether the process should be terminated
2715 * when @connection is closed by the remote peer.
2717 * Sets whether the process should be terminated when @connection is
2718 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2724 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2725 gboolean exit_on_close)
2727 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2728 connection->exit_on_close = exit_on_close;
2732 * g_dbus_connection_get_exit_on_close:
2733 * @connection: A #GDBusConnection.
2735 * Gets whether the process is terminated when @connection is
2736 * closed by the remote peer. See
2737 * #GDBusConnection:exit-on-close for more details.
2739 * Returns: Whether the process is terminated when @connection is
2740 * closed by the remote peer.
2745 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2747 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2748 return connection->exit_on_close;
2752 * g_dbus_connection_get_guid:
2753 * @connection: A #GDBusConnection.
2755 * The GUID of the peer performing the role of server when
2756 * authenticating. See #GDBusConnection:guid for more details.
2758 * Returns: The GUID. Do not free this string, it is owned by
2764 g_dbus_connection_get_guid (GDBusConnection *connection)
2766 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2767 return connection->guid;
2771 * g_dbus_connection_get_unique_name:
2772 * @connection: A #GDBusConnection.
2774 * Gets the unique name of @connection as assigned by the message
2775 * bus. This can also be used to figure out if @connection is a
2776 * message bus connection.
2778 * Returns: The unique name or %NULL if @connection is not a message
2779 * bus connection. Do not free this string, it is owned by
2785 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2787 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2788 return connection->bus_unique_name;
2792 * g_dbus_connection_get_peer_credentials:
2793 * @connection: A #GDBusConnection.
2795 * Gets the credentials of the authenticated peer. This will always
2796 * return %NULL unless @connection acted as a server
2797 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2798 * when set up and the client passed credentials as part of the
2799 * authentication process.
2801 * In a message bus setup, the message bus is always the server and
2802 * each application is a client. So this method will always return
2803 * %NULL for message bus clients.
2805 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
2806 * this object, it is owned by @connection.
2811 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2813 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2814 return connection->credentials;
2817 /* ---------------------------------------------------------------------------------------------------- */
2819 static guint _global_filter_id = 1;
2822 * g_dbus_connection_add_filter:
2823 * @connection: A #GDBusConnection.
2824 * @filter_function: A filter function.
2825 * @user_data: User data to pass to @filter_function.
2826 * @user_data_free_func: Function to free @user_data with when filter
2827 * is removed or %NULL.
2829 * Adds a message filter. Filters are handlers that are run on all
2830 * incoming and outgoing messages, prior to standard dispatch. Filters
2831 * are run in the order that they were added. The same handler can be
2832 * added as a filter more than once, in which case it will be run more
2833 * than once. Filters added during a filter callback won't be run on
2834 * the message being processed. Filter functions are allowed to modify
2835 * and even drop messages - see the #GDBusMessageFilterResult
2836 * enumeration for details.
2838 * Note that filters are run in a dedicated message handling thread so
2839 * they can't block and, generally, can't do anything but signal a
2840 * worker thread. Also note that filters are rarely needed - use API
2841 * such as g_dbus_connection_send_message_with_reply(),
2842 * g_dbus_connection_signal_subscribe() or
2843 * g_dbus_connection_call() instead.
2845 * If a filter consumes an incoming message the message is not
2846 * dispatched anywhere else - not even the standard dispatch machinery
2847 * (that API such as g_dbus_connection_signal_subscribe() and
2848 * g_dbus_connection_send_message_with_reply() relies on) will see the
2849 * message. Similary, if a filter consumes an outgoing message, the
2850 * message will not be sent to the other peer.
2852 * Returns: A filter identifier that can be used with
2853 * g_dbus_connection_remove_filter().
2858 g_dbus_connection_add_filter (GDBusConnection *connection,
2859 GDBusMessageFilterFunction filter_function,
2861 GDestroyNotify user_data_free_func)
2865 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2866 g_return_val_if_fail (filter_function != NULL, 0);
2868 CONNECTION_LOCK (connection);
2869 data = g_new0 (FilterData, 1);
2870 data->id = _global_filter_id++; /* TODO: overflow etc. */
2871 data->filter_function = filter_function;
2872 data->user_data = user_data;
2873 data->user_data_free_func = user_data_free_func;
2874 g_ptr_array_add (connection->filters, data);
2875 CONNECTION_UNLOCK (connection);
2880 /* only called from finalize(), removes all filters */
2882 purge_all_filters (GDBusConnection *connection)
2885 for (n = 0; n < connection->filters->len; n++)
2887 FilterData *data = connection->filters->pdata[n];
2888 if (data->user_data_free_func != NULL)
2889 data->user_data_free_func (data->user_data);
2895 * g_dbus_connection_remove_filter:
2896 * @connection: a #GDBusConnection
2897 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2904 g_dbus_connection_remove_filter (GDBusConnection *connection,
2908 FilterData *to_destroy;
2910 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2912 CONNECTION_LOCK (connection);
2914 for (n = 0; n < connection->filters->len; n++)
2916 FilterData *data = connection->filters->pdata[n];
2917 if (data->id == filter_id)
2919 g_ptr_array_remove_index (connection->filters, n);
2924 CONNECTION_UNLOCK (connection);
2926 /* do free without holding lock */
2927 if (to_destroy != NULL)
2929 if (to_destroy->user_data_free_func != NULL)
2930 to_destroy->user_data_free_func (to_destroy->user_data);
2931 g_free (to_destroy);
2935 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2939 /* ---------------------------------------------------------------------------------------------------- */
2945 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2946 gchar *interface_name;
2950 GArray *subscribers;
2955 GDBusSignalCallback callback;
2957 GDestroyNotify user_data_free_func;
2959 GMainContext *context;
2963 signal_data_free (SignalData *signal_data)
2965 g_free (signal_data->rule);
2966 g_free (signal_data->sender);
2967 g_free (signal_data->sender_unique_name);
2968 g_free (signal_data->interface_name);
2969 g_free (signal_data->member);
2970 g_free (signal_data->object_path);
2971 g_free (signal_data->arg0);
2972 g_array_free (signal_data->subscribers, TRUE);
2973 g_free (signal_data);
2977 args_to_rule (const gchar *sender,
2978 const gchar *interface_name,
2979 const gchar *member,
2980 const gchar *object_path,
2986 rule = g_string_new ("type='signal'");
2988 g_string_prepend_c (rule, '-');
2990 g_string_append_printf (rule, ",sender='%s'", sender);
2991 if (interface_name != NULL)
2992 g_string_append_printf (rule, ",interface='%s'", interface_name);
2994 g_string_append_printf (rule, ",member='%s'", member);
2995 if (object_path != NULL)
2996 g_string_append_printf (rule, ",path='%s'", object_path);
2998 g_string_append_printf (rule, ",arg0='%s'", arg0);
3000 return g_string_free (rule, FALSE);
3003 static guint _global_subscriber_id = 1;
3004 static guint _global_registration_id = 1;
3005 static guint _global_subtree_registration_id = 1;
3007 /* ---------------------------------------------------------------------------------------------------- */
3009 /* must hold lock when calling */
3011 add_match_rule (GDBusConnection *connection,
3012 const gchar *match_rule)
3015 GDBusMessage *message;
3017 if (match_rule[0] == '-')
3020 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3021 "/org/freedesktop/DBus", /* path */
3022 "org.freedesktop.DBus", /* interface */
3024 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3026 if (!g_dbus_connection_send_message_unlocked (connection,
3028 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3032 g_critical ("Error while sending AddMatch() message: %s", error->message);
3033 g_error_free (error);
3035 g_object_unref (message);
3038 /* ---------------------------------------------------------------------------------------------------- */
3040 /* must hold lock when calling */
3042 remove_match_rule (GDBusConnection *connection,
3043 const gchar *match_rule)
3046 GDBusMessage *message;
3048 if (match_rule[0] == '-')
3051 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3052 "/org/freedesktop/DBus", /* path */
3053 "org.freedesktop.DBus", /* interface */
3055 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3058 if (!g_dbus_connection_send_message_unlocked (connection,
3060 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3064 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3065 g_error_free (error);
3067 g_object_unref (message);
3070 /* ---------------------------------------------------------------------------------------------------- */
3073 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3075 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3076 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3077 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3078 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3079 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3082 /* ---------------------------------------------------------------------------------------------------- */
3085 * g_dbus_connection_signal_subscribe:
3086 * @connection: A #GDBusConnection.
3087 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
3088 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
3089 * @member: D-Bus signal name to match on or %NULL to match on all signals.
3090 * @object_path: Object path to match on or %NULL to match on all object paths.
3091 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
3092 * @flags: Flags describing how to subscribe to the signal (currently unused).
3093 * @callback: Callback to invoke when there is a signal matching the requested data.
3094 * @user_data: User data to pass to @callback.
3095 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
3097 * Subscribes to signals on @connection and invokes @callback with a
3098 * whenever the signal is received. Note that @callback
3099 * will be invoked in the <link
3100 * linkend="g-main-context-push-thread-default">thread-default main
3101 * loop</link> of the thread you are calling this method from.
3103 * If @connection is not a message bus connection, @sender must be
3106 * If @sender is a well-known name note that @callback is invoked with
3107 * the unique name for the owner of @sender, not the well-known name
3108 * as one would expect. This is because the message bus rewrites the
3109 * name. As such, to avoid certain race conditions, users should be
3110 * tracking the name owner of the well-known name and use that when
3111 * processing the received signal.
3113 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3118 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3119 const gchar *sender,
3120 const gchar *interface_name,
3121 const gchar *member,
3122 const gchar *object_path,
3124 GDBusSignalFlags flags,
3125 GDBusSignalCallback callback,
3127 GDestroyNotify user_data_free_func)
3130 SignalData *signal_data;
3131 SignalSubscriber subscriber;
3132 GPtrArray *signal_data_array;
3133 const gchar *sender_unique_name;
3135 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3136 * an OOM condition. We might want to change that but that would involve making
3137 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3138 * handle that. And there's really no sensible way of handling this short of retrying
3139 * to add the match rule... and then there's the little thing that, hey, maybe there's
3140 * a reason the bus in an OOM condition.
3142 * Doable, but not really sure it's worth it...
3145 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3146 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3147 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3148 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3149 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3150 g_return_val_if_fail (callback != NULL, 0);
3152 CONNECTION_LOCK (connection);
3154 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3155 * with a '-' character to prefix the rule (which will otherwise be
3158 * This allows us to hash the rule and do our lifecycle tracking in
3159 * the usual way, but the '-' prevents the match rule from ever
3160 * actually being send to the bus (either for add or remove).
3162 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3163 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3165 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3166 sender_unique_name = sender;
3168 sender_unique_name = "";
3170 subscriber.callback = callback;
3171 subscriber.user_data = user_data;
3172 subscriber.user_data_free_func = user_data_free_func;
3173 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3174 subscriber.context = g_main_context_get_thread_default ();
3175 if (subscriber.context != NULL)
3176 g_main_context_ref (subscriber.context);
3178 /* see if we've already have this rule */
3179 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3180 if (signal_data != NULL)
3182 g_array_append_val (signal_data->subscribers, subscriber);
3187 signal_data = g_new0 (SignalData, 1);
3188 signal_data->rule = rule;
3189 signal_data->sender = g_strdup (sender);
3190 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3191 signal_data->interface_name = g_strdup (interface_name);
3192 signal_data->member = g_strdup (member);
3193 signal_data->object_path = g_strdup (object_path);
3194 signal_data->arg0 = g_strdup (arg0);
3195 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3196 g_array_append_val (signal_data->subscribers, subscriber);
3198 g_hash_table_insert (connection->map_rule_to_signal_data,
3202 /* Add the match rule to the bus...
3204 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3205 * always send such messages to us.
3207 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3209 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3210 add_match_rule (connection, signal_data->rule);
3213 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3214 signal_data->sender_unique_name);
3215 if (signal_data_array == NULL)
3217 signal_data_array = g_ptr_array_new ();
3218 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3219 g_strdup (signal_data->sender_unique_name),
3222 g_ptr_array_add (signal_data_array, signal_data);
3225 g_hash_table_insert (connection->map_id_to_signal_data,
3226 GUINT_TO_POINTER (subscriber.id),
3229 CONNECTION_UNLOCK (connection);
3231 return subscriber.id;
3234 /* ---------------------------------------------------------------------------------------------------- */
3236 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3238 unsubscribe_id_internal (GDBusConnection *connection,
3239 guint subscription_id,
3240 GArray *out_removed_subscribers)
3242 SignalData *signal_data;
3243 GPtrArray *signal_data_array;
3246 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3247 GUINT_TO_POINTER (subscription_id));
3248 if (signal_data == NULL)
3250 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3254 for (n = 0; n < signal_data->subscribers->len; n++)
3256 SignalSubscriber *subscriber;
3258 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3259 if (subscriber->id != subscription_id)
3262 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3263 GUINT_TO_POINTER (subscription_id)));
3264 g_array_append_val (out_removed_subscribers, *subscriber);
3265 g_array_remove_index (signal_data->subscribers, n);
3267 if (signal_data->subscribers->len == 0)
3269 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3271 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3272 signal_data->sender_unique_name);
3273 g_warn_if_fail (signal_data_array != NULL);
3274 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3276 if (signal_data_array->len == 0)
3278 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3279 signal_data->sender_unique_name));
3282 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3283 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3285 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3286 if (!connection->closed && !connection->finalizing)
3287 remove_match_rule (connection, signal_data->rule);
3289 signal_data_free (signal_data);
3295 g_assert_not_reached ();
3302 * g_dbus_connection_signal_unsubscribe:
3303 * @connection: A #GDBusConnection.
3304 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3306 * Unsubscribes from signals.
3311 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3312 guint subscription_id)
3314 GArray *subscribers;
3317 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3319 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3321 CONNECTION_LOCK (connection);
3322 unsubscribe_id_internal (connection,
3325 CONNECTION_UNLOCK (connection);
3328 g_assert (subscribers->len == 0 || subscribers->len == 1);
3330 /* call GDestroyNotify without lock held */
3331 for (n = 0; n < subscribers->len; n++)
3333 SignalSubscriber *subscriber;
3334 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3335 call_destroy_notify (subscriber->context,
3336 subscriber->user_data_free_func,
3337 subscriber->user_data);
3338 if (subscriber->context != NULL)
3339 g_main_context_unref (subscriber->context);
3342 g_array_free (subscribers, TRUE);
3345 /* ---------------------------------------------------------------------------------------------------- */
3349 guint subscription_id;
3350 GDBusSignalCallback callback;
3352 GDBusMessage *message;
3353 GDBusConnection *connection;
3354 const gchar *sender;
3356 const gchar *interface;
3357 const gchar *member;
3360 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3364 emit_signal_instance_in_idle_cb (gpointer data)
3366 SignalInstance *signal_instance = data;
3367 GVariant *parameters;
3368 gboolean has_subscription;
3370 parameters = g_dbus_message_get_body (signal_instance->message);
3371 if (parameters == NULL)
3373 parameters = g_variant_new ("()");
3374 g_variant_ref_sink (parameters);
3378 g_variant_ref_sink (parameters);
3382 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3383 signal_instance->subscription_id,
3384 signal_instance->sender,
3385 signal_instance->path,
3386 signal_instance->interface,
3387 signal_instance->member,
3388 g_variant_print (parameters, TRUE));
3391 /* Careful here, don't do the callback if we no longer has the subscription */
3392 CONNECTION_LOCK (signal_instance->connection);
3393 has_subscription = FALSE;
3394 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3395 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3396 has_subscription = TRUE;
3397 CONNECTION_UNLOCK (signal_instance->connection);
3399 if (has_subscription)
3400 signal_instance->callback (signal_instance->connection,
3401 signal_instance->sender,
3402 signal_instance->path,
3403 signal_instance->interface,
3404 signal_instance->member,
3406 signal_instance->user_data);
3408 if (parameters != NULL)
3409 g_variant_unref (parameters);
3415 signal_instance_free (SignalInstance *signal_instance)
3417 g_object_unref (signal_instance->message);
3418 g_object_unref (signal_instance->connection);
3419 g_free (signal_instance);
3422 /* called in message handler thread WITH lock held */
3424 schedule_callbacks (GDBusConnection *connection,
3425 GPtrArray *signal_data_array,
3426 GDBusMessage *message,
3427 const gchar *sender)
3430 const gchar *interface;
3431 const gchar *member;
3440 interface = g_dbus_message_get_interface (message);
3441 member = g_dbus_message_get_member (message);
3442 path = g_dbus_message_get_path (message);
3443 arg0 = g_dbus_message_get_arg0 (message);
3446 g_print ("In schedule_callbacks:\n"
3448 " interface = `%s'\n"
3459 /* TODO: if this is slow, then we can change signal_data_array into
3460 * map_object_path_to_signal_data_array or something.
3462 for (n = 0; n < signal_data_array->len; n++)
3464 SignalData *signal_data = signal_data_array->pdata[n];
3466 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3469 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3472 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3475 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3478 for (m = 0; m < signal_data->subscribers->len; m++)
3480 SignalSubscriber *subscriber;
3481 GSource *idle_source;
3482 SignalInstance *signal_instance;
3484 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3486 signal_instance = g_new0 (SignalInstance, 1);
3487 signal_instance->subscription_id = subscriber->id;
3488 signal_instance->callback = subscriber->callback;
3489 signal_instance->user_data = subscriber->user_data;
3490 signal_instance->message = g_object_ref (message);
3491 signal_instance->connection = g_object_ref (connection);
3492 signal_instance->sender = sender;
3493 signal_instance->path = path;
3494 signal_instance->interface = interface;
3495 signal_instance->member = member;
3497 idle_source = g_idle_source_new ();
3498 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3499 g_source_set_callback (idle_source,
3500 emit_signal_instance_in_idle_cb,
3502 (GDestroyNotify) signal_instance_free);
3503 g_source_attach (idle_source, subscriber->context);
3504 g_source_unref (idle_source);
3509 /* called in message handler thread with lock held */
3511 distribute_signals (GDBusConnection *connection,
3512 GDBusMessage *message)
3514 GPtrArray *signal_data_array;
3515 const gchar *sender;
3517 sender = g_dbus_message_get_sender (message);
3519 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3521 _g_dbus_debug_print_lock ();
3522 g_print ("========================================================================\n"
3523 "GDBus-debug:Signal:\n"
3524 " <<<< RECEIVED SIGNAL %s.%s\n"
3526 " sent by name %s\n",
3527 g_dbus_message_get_interface (message),
3528 g_dbus_message_get_member (message),
3529 g_dbus_message_get_path (message),
3530 sender != NULL ? sender : "(none)");
3531 _g_dbus_debug_print_unlock ();
3534 /* collect subscribers that match on sender */
3537 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3538 if (signal_data_array != NULL)
3539 schedule_callbacks (connection, signal_data_array, message, sender);
3542 /* collect subscribers not matching on sender */
3543 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3544 if (signal_data_array != NULL)
3545 schedule_callbacks (connection, signal_data_array, message, sender);
3548 /* ---------------------------------------------------------------------------------------------------- */
3550 /* only called from finalize(), removes all subscriptions */
3552 purge_all_signal_subscriptions (GDBusConnection *connection)
3554 GHashTableIter iter;
3557 GArray *subscribers;
3560 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3561 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3562 while (g_hash_table_iter_next (&iter, &key, NULL))
3564 guint subscription_id = GPOINTER_TO_UINT (key);
3565 g_array_append_val (ids, subscription_id);
3568 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3569 for (n = 0; n < ids->len; n++)
3571 guint subscription_id = g_array_index (ids, guint, n);
3572 unsubscribe_id_internal (connection,
3576 g_array_free (ids, TRUE);
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 if (subscriber->context != NULL)
3587 g_main_context_unref (subscriber->context);
3590 g_array_free (subscribers, TRUE);
3593 /* ---------------------------------------------------------------------------------------------------- */
3595 static GDBusInterfaceVTable *
3596 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3598 /* Don't waste memory by copying padding - remember to update this
3599 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3601 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3605 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3610 /* ---------------------------------------------------------------------------------------------------- */
3612 static GDBusSubtreeVTable *
3613 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3615 /* Don't waste memory by copying padding - remember to update this
3616 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3618 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3622 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3627 /* ---------------------------------------------------------------------------------------------------- */
3629 struct ExportedObject
3632 GDBusConnection *connection;
3634 /* maps gchar* -> ExportedInterface* */
3635 GHashTable *map_if_name_to_ei;
3638 /* only called with lock held */
3640 exported_object_free (ExportedObject *eo)
3642 g_free (eo->object_path);
3643 g_hash_table_unref (eo->map_if_name_to_ei);
3652 gchar *interface_name;
3653 GDBusInterfaceVTable *vtable;
3654 GDBusInterfaceInfo *interface_info;
3656 GMainContext *context;
3658 GDestroyNotify user_data_free_func;
3659 } ExportedInterface;
3661 /* called with lock held */
3663 exported_interface_free (ExportedInterface *ei)
3665 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3667 call_destroy_notify (ei->context,
3668 ei->user_data_free_func,
3671 if (ei->context != NULL)
3672 g_main_context_unref (ei->context);
3674 g_free (ei->interface_name);
3675 _g_dbus_interface_vtable_free (ei->vtable);
3679 /* ---------------------------------------------------------------------------------------------------- */
3681 /* Convenience function to check if @registration_id (if not zero) or
3682 * @subtree_registration_id (if not zero) has been unregistered. If
3683 * so, returns %TRUE.
3685 * Caller must *not* hold lock.
3688 has_object_been_unregistered (GDBusConnection *connection,
3689 guint registration_id,
3690 guint subtree_registration_id)
3694 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3698 CONNECTION_LOCK (connection);
3699 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3700 GUINT_TO_POINTER (registration_id)) == NULL)
3704 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3705 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3709 CONNECTION_UNLOCK (connection);
3714 /* ---------------------------------------------------------------------------------------------------- */
3718 GDBusConnection *connection;
3719 GDBusMessage *message;
3721 const gchar *property_name;
3722 const GDBusInterfaceVTable *vtable;
3723 GDBusInterfaceInfo *interface_info;
3724 const GDBusPropertyInfo *property_info;
3725 guint registration_id;
3726 guint subtree_registration_id;
3730 property_data_free (PropertyData *data)
3732 g_object_unref (data->connection);
3733 g_object_unref (data->message);
3737 /* called in thread where object was registered - no locks held */
3739 invoke_get_property_in_idle_cb (gpointer _data)
3741 PropertyData *data = _data;
3744 GDBusMessage *reply;
3746 if (has_object_been_unregistered (data->connection,
3747 data->registration_id,
3748 data->subtree_registration_id))
3750 reply = g_dbus_message_new_method_error (data->message,
3751 "org.freedesktop.DBus.Error.UnknownMethod",
3752 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3753 g_dbus_message_get_path (data->message));
3754 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3755 g_object_unref (reply);
3760 value = data->vtable->get_property (data->connection,
3761 g_dbus_message_get_sender (data->message),
3762 g_dbus_message_get_path (data->message),
3763 data->interface_info->name,
3764 data->property_name,
3771 g_assert_no_error (error);
3773 if (g_variant_is_floating (value))
3774 g_variant_ref_sink (value);
3775 reply = g_dbus_message_new_method_reply (data->message);
3776 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3777 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3778 g_variant_unref (value);
3779 g_object_unref (reply);
3783 gchar *dbus_error_name;
3784 g_assert (error != NULL);
3785 dbus_error_name = g_dbus_error_encode_gerror (error);
3786 reply = g_dbus_message_new_method_error_literal (data->message,
3789 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3790 g_free (dbus_error_name);
3791 g_error_free (error);
3792 g_object_unref (reply);
3799 /* called in thread where object was registered - no locks held */
3801 invoke_set_property_in_idle_cb (gpointer _data)
3803 PropertyData *data = _data;
3805 GDBusMessage *reply;
3811 g_variant_get (g_dbus_message_get_body (data->message),
3817 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3818 * of the given value is wrong
3820 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3822 reply = g_dbus_message_new_method_error (data->message,
3823 "org.freedesktop.DBus.Error.InvalidArgs",
3824 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3825 data->property_info->name,
3826 data->property_info->signature,
3827 g_variant_get_type_string (value));
3831 if (!data->vtable->set_property (data->connection,
3832 g_dbus_message_get_sender (data->message),
3833 g_dbus_message_get_path (data->message),
3834 data->interface_info->name,
3835 data->property_name,
3840 gchar *dbus_error_name;
3841 g_assert (error != NULL);
3842 dbus_error_name = g_dbus_error_encode_gerror (error);
3843 reply = g_dbus_message_new_method_error_literal (data->message,
3846 g_free (dbus_error_name);
3847 g_error_free (error);
3851 reply = g_dbus_message_new_method_reply (data->message);
3855 g_assert (reply != NULL);
3856 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3857 g_object_unref (reply);
3858 g_variant_unref (value);
3863 /* called with lock held */
3865 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3866 GDBusMessage *message,
3867 guint registration_id,
3868 guint subtree_registration_id,
3870 GDBusInterfaceInfo *interface_info,
3871 const GDBusInterfaceVTable *vtable,
3872 GMainContext *main_context,
3876 const char *interface_name;
3877 const char *property_name;
3878 const GDBusPropertyInfo *property_info;
3879 GSource *idle_source;
3880 PropertyData *property_data;
3881 GDBusMessage *reply;
3886 g_variant_get (g_dbus_message_get_body (message),
3891 g_variant_get (g_dbus_message_get_body (message),
3900 if (vtable == NULL || vtable->get_property == NULL)
3905 if (vtable == NULL || vtable->set_property == NULL)
3909 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3911 property_info = NULL;
3913 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3914 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3915 if (property_info == NULL)
3917 reply = g_dbus_message_new_method_error (message,
3918 "org.freedesktop.DBus.Error.InvalidArgs",
3919 _("No such property `%s'"),
3921 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3922 g_object_unref (reply);
3927 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3929 reply = g_dbus_message_new_method_error (message,
3930 "org.freedesktop.DBus.Error.InvalidArgs",
3931 _("Property `%s' is not readable"),
3933 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3934 g_object_unref (reply);
3938 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3940 reply = g_dbus_message_new_method_error (message,
3941 "org.freedesktop.DBus.Error.InvalidArgs",
3942 _("Property `%s' is not writable"),
3944 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3945 g_object_unref (reply);
3950 /* ok, got the property info - call user code in an idle handler */
3951 property_data = g_new0 (PropertyData, 1);
3952 property_data->connection = g_object_ref (connection);
3953 property_data->message = g_object_ref (message);
3954 property_data->user_data = user_data;
3955 property_data->property_name = property_name;
3956 property_data->vtable = vtable;
3957 property_data->interface_info = interface_info;
3958 property_data->property_info = property_info;
3959 property_data->registration_id = registration_id;
3960 property_data->subtree_registration_id = subtree_registration_id;
3962 idle_source = g_idle_source_new ();
3963 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3964 g_source_set_callback (idle_source,
3965 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3967 (GDestroyNotify) property_data_free);
3968 g_source_attach (idle_source, main_context);
3969 g_source_unref (idle_source);
3977 /* called with lock held */
3979 handle_getset_property (GDBusConnection *connection,
3981 GDBusMessage *message,
3984 ExportedInterface *ei;
3986 const char *interface_name;
3987 const char *property_name;
3992 g_variant_get (g_dbus_message_get_body (message),
3997 g_variant_get (g_dbus_message_get_body (message),
4003 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4004 * no such interface registered
4006 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4009 GDBusMessage *reply;
4010 reply = g_dbus_message_new_method_error (message,
4011 "org.freedesktop.DBus.Error.InvalidArgs",
4012 _("No such interface `%s'"),
4014 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4015 g_object_unref (reply);
4020 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4033 /* ---------------------------------------------------------------------------------------------------- */
4037 GDBusConnection *connection;
4038 GDBusMessage *message;
4040 const GDBusInterfaceVTable *vtable;
4041 GDBusInterfaceInfo *interface_info;
4042 guint registration_id;
4043 guint subtree_registration_id;
4044 } PropertyGetAllData;
4047 property_get_all_data_free (PropertyData *data)
4049 g_object_unref (data->connection);
4050 g_object_unref (data->message);
4054 /* called in thread where object was registered - no locks held */
4056 invoke_get_all_properties_in_idle_cb (gpointer _data)
4058 PropertyGetAllData *data = _data;
4059 GVariantBuilder builder;
4061 GDBusMessage *reply;
4064 if (has_object_been_unregistered (data->connection,
4065 data->registration_id,
4066 data->subtree_registration_id))
4068 reply = g_dbus_message_new_method_error (data->message,
4069 "org.freedesktop.DBus.Error.UnknownMethod",
4070 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4071 g_dbus_message_get_path (data->message));
4072 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4073 g_object_unref (reply);
4079 /* TODO: Right now we never fail this call - we just omit values if
4080 * a get_property() call is failing.
4082 * We could fail the whole call if just a single get_property() call
4083 * returns an error. We need clarification in the D-Bus spec about this.
4085 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4086 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4087 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4089 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4092 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4095 value = data->vtable->get_property (data->connection,
4096 g_dbus_message_get_sender (data->message),
4097 g_dbus_message_get_path (data->message),
4098 data->interface_info->name,
4099 property_info->name,
4106 if (g_variant_is_floating (value))
4107 g_variant_ref_sink (value);
4108 g_variant_builder_add (&builder,
4110 property_info->name,
4112 g_variant_unref (value);
4114 g_variant_builder_close (&builder);
4116 reply = g_dbus_message_new_method_reply (data->message);
4117 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4118 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4119 g_object_unref (reply);
4125 /* called with lock held */
4127 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4128 GDBusMessage *message,
4129 guint registration_id,
4130 guint subtree_registration_id,
4131 GDBusInterfaceInfo *interface_info,
4132 const GDBusInterfaceVTable *vtable,
4133 GMainContext *main_context,
4137 const char *interface_name;
4138 GSource *idle_source;
4139 PropertyGetAllData *property_get_all_data;
4143 g_variant_get (g_dbus_message_get_body (message),
4147 if (vtable == NULL || vtable->get_property == NULL)
4150 /* ok, got the property info - call user in an idle handler */
4151 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4152 property_get_all_data->connection = g_object_ref (connection);
4153 property_get_all_data->message = g_object_ref (message);
4154 property_get_all_data->user_data = user_data;
4155 property_get_all_data->vtable = vtable;
4156 property_get_all_data->interface_info = interface_info;
4157 property_get_all_data->registration_id = registration_id;
4158 property_get_all_data->subtree_registration_id = subtree_registration_id;
4160 idle_source = g_idle_source_new ();
4161 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4162 g_source_set_callback (idle_source,
4163 invoke_get_all_properties_in_idle_cb,
4164 property_get_all_data,
4165 (GDestroyNotify) property_get_all_data_free);
4166 g_source_attach (idle_source, main_context);
4167 g_source_unref (idle_source);
4175 /* called with lock held */
4177 handle_get_all_properties (GDBusConnection *connection,
4179 GDBusMessage *message)
4181 ExportedInterface *ei;
4183 const char *interface_name;
4187 g_variant_get (g_dbus_message_get_body (message),
4191 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4192 * no such interface registered
4194 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4197 GDBusMessage *reply;
4198 reply = g_dbus_message_new_method_error (message,
4199 "org.freedesktop.DBus.Error.InvalidArgs",
4200 _("No such interface"),
4202 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4203 g_object_unref (reply);
4208 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4220 /* ---------------------------------------------------------------------------------------------------- */
4222 static const gchar introspect_header[] =
4223 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4224 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4225 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4228 static const gchar introspect_tail[] =
4231 static const gchar introspect_standard_interfaces[] =
4232 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4233 " <method name=\"Get\">\n"
4234 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4235 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4236 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4238 " <method name=\"GetAll\">\n"
4239 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4240 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4242 " <method name=\"Set\">\n"
4243 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4244 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4245 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4247 " <signal name=\"PropertiesChanged\">\n"
4248 " <arg type=\"s\" name=\"interface_name\"/>\n"
4249 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4250 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4253 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4254 " <method name=\"Introspect\">\n"
4255 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4258 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4259 " <method name=\"Ping\"/>\n"
4260 " <method name=\"GetMachineId\">\n"
4261 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4266 introspect_append_header (GString *s)
4268 g_string_append (s, introspect_header);
4272 introspect_append_standard_interfaces (GString *s)
4274 g_string_append (s, introspect_standard_interfaces);
4278 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4280 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4286 begin = object_path + path_len;
4287 end = strchr (begin, '/');
4289 s = g_strndup (begin, end - begin);
4291 s = g_strdup (begin);
4293 if (g_hash_table_lookup (set, s) == NULL)
4294 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4300 /* TODO: we want a nicer public interface for this */
4302 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4307 GHashTableIter hash_iter;
4308 const gchar *object_path;
4314 CONNECTION_ENSURE_LOCK (connection);
4316 path_len = strlen (path);
4320 set = g_hash_table_new (g_str_hash, g_str_equal);
4322 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4323 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4324 maybe_add_path (path, path_len, object_path, set);
4326 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4327 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4328 maybe_add_path (path, path_len, object_path, set);
4330 p = g_ptr_array_new ();
4331 keys = g_hash_table_get_keys (set);
4332 for (l = keys; l != NULL; l = l->next)
4333 g_ptr_array_add (p, l->data);
4334 g_hash_table_unref (set);
4337 g_ptr_array_add (p, NULL);
4338 ret = (gchar **) g_ptr_array_free (p, FALSE);
4343 g_dbus_connection_list_registered (GDBusConnection *connection,
4347 CONNECTION_LOCK (connection);
4348 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4349 CONNECTION_UNLOCK (connection);
4353 /* called in message handler thread with lock held */
4355 handle_introspect (GDBusConnection *connection,
4357 GDBusMessage *message)
4361 GDBusMessage *reply;
4362 GHashTableIter hash_iter;
4363 ExportedInterface *ei;
4366 /* first the header with the standard interfaces */
4367 s = g_string_sized_new (sizeof (introspect_header) +
4368 sizeof (introspect_standard_interfaces) +
4369 sizeof (introspect_tail));
4370 introspect_append_header (s);
4371 introspect_append_standard_interfaces (s);
4373 /* then include the registered interfaces */
4374 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4375 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4376 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4378 /* finally include nodes registered below us */
4379 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4380 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4381 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4382 g_strfreev (registered);
4383 g_string_append (s, introspect_tail);
4385 reply = g_dbus_message_new_method_reply (message);
4386 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4387 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4388 g_object_unref (reply);
4389 g_string_free (s, TRUE);
4394 /* called in thread where object was registered - no locks held */
4396 call_in_idle_cb (gpointer user_data)
4398 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4399 GDBusInterfaceVTable *vtable;
4400 guint registration_id;
4401 guint subtree_registration_id;
4403 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4404 g_assert (vtable != NULL && vtable->method_call != NULL);
4406 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4407 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4409 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4411 subtree_registration_id))
4413 GDBusMessage *reply;
4414 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4415 "org.freedesktop.DBus.Error.UnknownMethod",
4416 _("No such interface `%s' on object at path %s"),
4417 g_dbus_method_invocation_get_interface_name (invocation),
4418 g_dbus_method_invocation_get_object_path (invocation));
4419 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4420 g_object_unref (reply);
4424 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4425 g_dbus_method_invocation_get_sender (invocation),
4426 g_dbus_method_invocation_get_object_path (invocation),
4427 g_dbus_method_invocation_get_interface_name (invocation),
4428 g_dbus_method_invocation_get_method_name (invocation),
4429 g_dbus_method_invocation_get_parameters (invocation),
4430 g_object_ref (invocation),
4431 g_dbus_method_invocation_get_user_data (invocation));
4437 /* called in message handler thread with lock held */
4439 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4440 GDBusMessage *message,
4441 guint registration_id,
4442 guint subtree_registration_id,
4443 GDBusInterfaceInfo *interface_info,
4444 const GDBusInterfaceVTable *vtable,
4445 GMainContext *main_context,
4448 GDBusMethodInvocation *invocation;
4449 const GDBusMethodInfo *method_info;
4450 GDBusMessage *reply;
4451 GVariant *parameters;
4452 GSource *idle_source;
4454 GVariantType *in_type;
4458 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4459 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4461 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4462 * error to the caller
4464 if (method_info == NULL)
4466 reply = g_dbus_message_new_method_error (message,
4467 "org.freedesktop.DBus.Error.UnknownMethod",
4468 _("No such method `%s'"),
4469 g_dbus_message_get_member (message));
4470 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4471 g_object_unref (reply);
4476 parameters = g_dbus_message_get_body (message);
4477 if (parameters == NULL)
4479 parameters = g_variant_new ("()");
4480 g_variant_ref_sink (parameters);
4484 g_variant_ref (parameters);
4487 /* Check that the incoming args are of the right type - if they are not, return
4488 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4490 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4491 if (!g_variant_is_of_type (parameters, in_type))
4495 type_string = g_variant_type_dup_string (in_type);
4497 reply = g_dbus_message_new_method_error (message,
4498 "org.freedesktop.DBus.Error.InvalidArgs",
4499 _("Type of message, `%s', does not match expected type `%s'"),
4500 g_variant_get_type_string (parameters),
4502 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4503 g_variant_type_free (in_type);
4504 g_variant_unref (parameters);
4505 g_object_unref (reply);
4506 g_free (type_string);
4510 g_variant_type_free (in_type);
4512 /* schedule the call in idle */
4513 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4514 g_dbus_message_get_path (message),
4515 g_dbus_message_get_interface (message),
4516 g_dbus_message_get_member (message),
4522 g_variant_unref (parameters);
4524 /* TODO: would be nicer with a real MethodData like we already
4525 * have PropertyData and PropertyGetAllData... */
4526 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4527 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4528 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4530 idle_source = g_idle_source_new ();
4531 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4532 g_source_set_callback (idle_source,
4536 g_source_attach (idle_source, main_context);
4537 g_source_unref (idle_source);
4545 /* ---------------------------------------------------------------------------------------------------- */
4547 /* called in message handler thread with lock held */
4549 obj_message_func (GDBusConnection *connection,
4551 GDBusMessage *message)
4553 const gchar *interface_name;
4554 const gchar *member;
4555 const gchar *signature;
4560 interface_name = g_dbus_message_get_interface (message);
4561 member = g_dbus_message_get_member (message);
4562 signature = g_dbus_message_get_signature (message);
4564 /* see if we have an interface for handling this call */
4565 if (interface_name != NULL)
4567 ExportedInterface *ei;
4568 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4571 /* we do - invoke the handler in idle in the right thread */
4573 /* handle no vtable or handler being present */
4574 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4577 handled = validate_and_maybe_schedule_method_call (connection,
4589 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4590 g_strcmp0 (member, "Introspect") == 0 &&
4591 g_strcmp0 (signature, "") == 0)
4593 handled = handle_introspect (connection, eo, message);
4596 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4597 g_strcmp0 (member, "Get") == 0 &&
4598 g_strcmp0 (signature, "ss") == 0)
4600 handled = handle_getset_property (connection, eo, message, TRUE);
4603 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4604 g_strcmp0 (member, "Set") == 0 &&
4605 g_strcmp0 (signature, "ssv") == 0)
4607 handled = handle_getset_property (connection, eo, message, FALSE);
4610 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4611 g_strcmp0 (member, "GetAll") == 0 &&
4612 g_strcmp0 (signature, "s") == 0)
4614 handled = handle_get_all_properties (connection, eo, message);
4623 * g_dbus_connection_register_object:
4624 * @connection: A #GDBusConnection.
4625 * @object_path: The object path to register at.
4626 * @interface_info: Introspection data for the interface.
4627 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4628 * @user_data: Data to pass to functions in @vtable.
4629 * @user_data_free_func: Function to call when the object path is unregistered.
4630 * @error: Return location for error or %NULL.
4632 * Registers callbacks for exported objects at @object_path with the
4633 * D-Bus interface that is described in @interface_info.
4635 * Calls to functions in @vtable (and @user_data_free_func) will
4636 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4637 * loop</link> of the thread you are calling this method from.
4639 * Note that all #GVariant values passed to functions in @vtable will match
4640 * the signature given in @interface_info - if a remote caller passes
4641 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4642 * is returned to the remote caller.
4644 * Additionally, if the remote caller attempts to invoke methods or
4645 * access properties not mentioned in @interface_info the
4646 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4647 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4648 * are returned to the caller.
4650 * It is considered a programming error if the
4651 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4652 * #GVariant of incorrect type.
4654 * If an existing callback is already registered at @object_path and
4655 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4657 * GDBus automatically implements the standard D-Bus interfaces
4658 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4659 * and org.freedesktop.Peer, so you don't have to implement those for
4660 * the objects you export. You <emphasis>can</emphasis> implement
4661 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4662 * and setting of properties asynchronously.
4664 * Note that the reference count on @interface_info will be
4665 * incremented by 1 (unless allocated statically, e.g. if the
4666 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4667 * as the object is exported. Also note that @vtable will be copied.
4669 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4671 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4672 * that can be used with g_dbus_connection_unregister_object() .
4677 g_dbus_connection_register_object (GDBusConnection *connection,
4678 const gchar *object_path,
4679 GDBusInterfaceInfo *interface_info,
4680 const GDBusInterfaceVTable *vtable,
4682 GDestroyNotify user_data_free_func,
4686 ExportedInterface *ei;
4689 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4690 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4691 g_return_val_if_fail (interface_info != NULL, 0);
4692 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4693 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4697 CONNECTION_LOCK (connection);
4699 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4702 eo = g_new0 (ExportedObject, 1);
4703 eo->object_path = g_strdup (object_path);
4704 eo->connection = connection;
4705 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4708 (GDestroyNotify) exported_interface_free);
4709 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4712 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4718 _("An object is already exported for the interface %s at %s"),
4719 interface_info->name,
4724 ei = g_new0 (ExportedInterface, 1);
4725 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4727 ei->user_data = user_data;
4728 ei->user_data_free_func = user_data_free_func;
4729 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4730 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4731 ei->interface_name = g_strdup (interface_info->name);
4732 ei->context = g_main_context_get_thread_default ();
4733 if (ei->context != NULL)
4734 g_main_context_ref (ei->context);
4736 g_hash_table_insert (eo->map_if_name_to_ei,
4737 (gpointer) ei->interface_name,
4739 g_hash_table_insert (connection->map_id_to_ei,
4740 GUINT_TO_POINTER (ei->id),
4746 CONNECTION_UNLOCK (connection);
4752 * g_dbus_connection_unregister_object:
4753 * @connection: A #GDBusConnection.
4754 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4756 * Unregisters an object.
4758 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4763 g_dbus_connection_unregister_object (GDBusConnection *connection,
4764 guint registration_id)
4766 ExportedInterface *ei;
4770 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4774 CONNECTION_LOCK (connection);
4776 ei = g_hash_table_lookup (connection->map_id_to_ei,
4777 GUINT_TO_POINTER (registration_id));
4783 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4784 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4785 /* unregister object path if we have no more exported interfaces */
4786 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4787 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4793 CONNECTION_UNLOCK (connection);
4798 /* ---------------------------------------------------------------------------------------------------- */
4801 * g_dbus_connection_emit_signal:
4802 * @connection: A #GDBusConnection.
4803 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4804 * @object_path: Path of remote object.
4805 * @interface_name: D-Bus interface to emit a signal on.
4806 * @signal_name: The name of the signal to emit.
4807 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4808 * @error: Return location for error or %NULL.
4812 * If the parameters GVariant is floating, it is consumed.
4814 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4816 * Returns: %TRUE unless @error is set.
4821 g_dbus_connection_emit_signal (GDBusConnection *connection,
4822 const gchar *destination_bus_name,
4823 const gchar *object_path,
4824 const gchar *interface_name,
4825 const gchar *signal_name,
4826 GVariant *parameters,
4829 GDBusMessage *message;
4835 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4836 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4837 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4838 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4839 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4840 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4842 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4844 _g_dbus_debug_print_lock ();
4845 g_print ("========================================================================\n"
4846 "GDBus-debug:Emission:\n"
4847 " >>>> SIGNAL EMISSION %s.%s()\n"
4849 " destination %s\n",
4850 interface_name, signal_name,
4852 destination_bus_name != NULL ? destination_bus_name : "(none)");
4853 _g_dbus_debug_print_unlock ();
4856 message = g_dbus_message_new_signal (object_path,
4860 if (destination_bus_name != NULL)
4861 g_dbus_message_set_header (message,
4862 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4863 g_variant_new_string (destination_bus_name));
4865 if (parameters != NULL)
4866 g_dbus_message_set_body (message, parameters);
4868 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4869 g_object_unref (message);
4875 add_call_flags (GDBusMessage *message,
4876 GDBusCallFlags flags)
4878 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4879 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4883 decode_method_reply (GDBusMessage *reply,
4884 const gchar *method_name,
4885 const GVariantType *reply_type,
4891 switch (g_dbus_message_get_message_type (reply))
4893 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4894 result = g_dbus_message_get_body (reply);
4897 result = g_variant_new ("()");
4898 g_variant_ref_sink (result);
4902 g_variant_ref (result);
4905 if (!g_variant_is_of_type (result, reply_type))
4907 gchar *type_string = g_variant_type_dup_string (reply_type);
4911 G_IO_ERROR_INVALID_ARGUMENT,
4912 _("Method `%s' returned type `%s', but expected `%s'"),
4913 method_name, g_variant_get_type_string (result), type_string);
4915 g_variant_unref (result);
4916 g_free (type_string);
4921 case G_DBUS_MESSAGE_TYPE_ERROR:
4922 g_dbus_message_to_gerror (reply, error);
4926 g_assert_not_reached ();
4936 GSimpleAsyncResult *simple;
4937 GVariantType *reply_type;
4938 gchar *method_name; /* for error message */
4943 g_dbus_connection_call_done (GObject *source,
4944 GAsyncResult *result,
4947 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4948 CallState *state = user_data;
4950 GDBusMessage *reply;
4954 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4958 if (G_UNLIKELY (_g_dbus_debug_call ()))
4960 _g_dbus_debug_print_lock ();
4961 g_print ("========================================================================\n"
4962 "GDBus-debug:Call:\n"
4963 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4969 g_print ("SUCCESS\n");
4973 g_print ("FAILED: %s\n",
4976 _g_dbus_debug_print_unlock ();
4982 value = decode_method_reply (reply, state->method_name,
4983 state->reply_type, &error);
4984 g_object_unref (reply);
4990 g_simple_async_result_take_error (state->simple, error);
4992 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4993 (GDestroyNotify) g_variant_unref);
4995 g_simple_async_result_complete (state->simple);
4996 g_variant_type_free (state->reply_type);
4997 g_object_unref (state->simple);
4998 g_free (state->method_name);
5000 g_slice_free (CallState, state);
5004 * g_dbus_connection_call:
5005 * @connection: A #GDBusConnection.
5006 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
5007 * @object_path: Path of remote object.
5008 * @interface_name: D-Bus interface to invoke method on.
5009 * @method_name: The name of the method to invoke.
5010 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5011 * @reply_type: The expected type of the reply, or %NULL.
5012 * @flags: Flags from the #GDBusCallFlags enumeration.
5013 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5014 * timeout or %G_MAXINT for no timeout.
5015 * @cancellable: A #GCancellable or %NULL.
5016 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
5017 * care about the result of the method invocation.
5018 * @user_data: The data to pass to @callback.
5020 * Asynchronously invokes the @method_name method on the
5021 * @interface_name D-Bus interface on the remote object at
5022 * @object_path owned by @bus_name.
5024 * If @connection is closed then the operation will fail with
5025 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5026 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5027 * not compatible with the D-Bus protocol, the operation fails with
5028 * %G_IO_ERROR_INVALID_ARGUMENT.
5030 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5031 * error will be raised if it does not match. Said another way, if you give a @reply_type
5032 * then any non-%NULL return value will be of this type.
5034 * If the @parameters #GVariant is floating, it is consumed. This allows
5035 * convenient 'inline' use of g_variant_new(), e.g.:
5037 * g_dbus_connection_call (connection,
5038 * "org.freedesktop.StringThings",
5039 * "/org/freedesktop/StringThings",
5040 * "org.freedesktop.StringThings",
5042 * g_variant_new ("(ss)",
5046 * G_DBUS_CALL_FLAGS_NONE,
5049 * (GAsyncReadyCallback) two_strings_done,
5053 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5054 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5055 * of the thread you are calling this method from. You can then call
5056 * g_dbus_connection_call_finish() to get the result of the operation.
5057 * See g_dbus_connection_call_sync() for the synchronous version of this
5063 g_dbus_connection_call (GDBusConnection *connection,
5064 const gchar *bus_name,
5065 const gchar *object_path,
5066 const gchar *interface_name,
5067 const gchar *method_name,
5068 GVariant *parameters,
5069 const GVariantType *reply_type,
5070 GDBusCallFlags flags,
5072 GCancellable *cancellable,
5073 GAsyncReadyCallback callback,
5076 GDBusMessage *message;
5079 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5080 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5081 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5082 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5083 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5084 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5085 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5087 state = g_slice_new (CallState);
5088 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5089 callback, user_data,
5090 g_dbus_connection_call);
5091 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5093 if (reply_type == NULL)
5094 reply_type = G_VARIANT_TYPE_ANY;
5096 state->reply_type = g_variant_type_copy (reply_type);
5098 message = g_dbus_message_new_method_call (bus_name,
5102 add_call_flags (message, flags);
5103 if (parameters != NULL)
5104 g_dbus_message_set_body (message, parameters);
5106 g_dbus_connection_send_message_with_reply (connection,
5108 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5112 g_dbus_connection_call_done,
5115 if (G_UNLIKELY (_g_dbus_debug_call ()))
5117 _g_dbus_debug_print_lock ();
5118 g_print ("========================================================================\n"
5119 "GDBus-debug:Call:\n"
5120 " >>>> ASYNC %s.%s()\n"
5122 " owned by name %s (serial %d)\n",
5126 bus_name != NULL ? bus_name : "(none)",
5128 _g_dbus_debug_print_unlock ();
5131 if (message != NULL)
5132 g_object_unref (message);
5136 * g_dbus_connection_call_finish:
5137 * @connection: A #GDBusConnection.
5138 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5139 * @error: Return location for error or %NULL.
5141 * Finishes an operation started with g_dbus_connection_call().
5143 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5144 * return values. Free with g_variant_unref().
5149 g_dbus_connection_call_finish (GDBusConnection *connection,
5153 GSimpleAsyncResult *simple;
5155 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5156 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5157 g_dbus_connection_call), NULL);
5158 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5160 simple = G_SIMPLE_ASYNC_RESULT (res);
5162 if (g_simple_async_result_propagate_error (simple, error))
5165 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
5168 /* ---------------------------------------------------------------------------------------------------- */
5171 * g_dbus_connection_call_sync:
5172 * @connection: A #GDBusConnection.
5173 * @bus_name: A unique or well-known bus name.
5174 * @object_path: Path of remote object.
5175 * @interface_name: D-Bus interface to invoke method on.
5176 * @method_name: The name of the method to invoke.
5177 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5178 * @reply_type: The expected type of the reply, or %NULL.
5179 * @flags: Flags from the #GDBusCallFlags enumeration.
5180 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5181 * timeout or %G_MAXINT for no timeout.
5182 * @cancellable: A #GCancellable or %NULL.
5183 * @error: Return location for error or %NULL.
5185 * Synchronously invokes the @method_name method on the
5186 * @interface_name D-Bus interface on the remote object at
5187 * @object_path owned by @bus_name.
5189 * If @connection is closed then the operation will fail with
5190 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5191 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5192 * contains a value not compatible with the D-Bus protocol, the operation
5193 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5195 * If @reply_type is non-%NULL then the reply will be checked for having
5196 * this type and an error will be raised if it does not match. Said
5197 * another way, if you give a @reply_type then any non-%NULL return
5198 * value will be of this type.
5200 * If the @parameters #GVariant is floating, it is consumed.
5201 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5203 * g_dbus_connection_call_sync (connection,
5204 * "org.freedesktop.StringThings",
5205 * "/org/freedesktop/StringThings",
5206 * "org.freedesktop.StringThings",
5208 * g_variant_new ("(ss)",
5212 * G_DBUS_CALL_FLAGS_NONE,
5218 * The calling thread is blocked until a reply is received. See
5219 * g_dbus_connection_call() for the asynchronous version of
5222 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5223 * return values. Free with g_variant_unref().
5228 g_dbus_connection_call_sync (GDBusConnection *connection,
5229 const gchar *bus_name,
5230 const gchar *object_path,
5231 const gchar *interface_name,
5232 const gchar *method_name,
5233 GVariant *parameters,
5234 const GVariantType *reply_type,
5235 GDBusCallFlags flags,
5237 GCancellable *cancellable,
5240 GDBusMessage *message;
5241 GDBusMessage *reply;
5243 GError *local_error;
5249 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5250 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5251 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5252 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5253 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5254 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5255 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5257 if (reply_type == NULL)
5258 reply_type = G_VARIANT_TYPE_ANY;
5260 message = g_dbus_message_new_method_call (bus_name,
5264 add_call_flags (message, flags);
5265 if (parameters != NULL)
5266 g_dbus_message_set_body (message, parameters);
5268 if (G_UNLIKELY (_g_dbus_debug_call ()))
5270 _g_dbus_debug_print_lock ();
5271 g_print ("========================================================================\n"
5272 "GDBus-debug:Call:\n"
5273 " >>>> SYNC %s.%s()\n"
5275 " owned by name %s\n",
5279 bus_name != NULL ? bus_name : "(none)");
5280 _g_dbus_debug_print_unlock ();
5284 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5286 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5288 NULL, /* volatile guint32 *out_serial */
5292 if (G_UNLIKELY (_g_dbus_debug_call ()))
5294 _g_dbus_debug_print_lock ();
5295 g_print ("========================================================================\n"
5296 "GDBus-debug:Call:\n"
5297 " <<<< SYNC COMPLETE %s.%s()\n"
5303 g_print ("SUCCESS\n");
5307 g_print ("FAILED: %s\n",
5308 local_error->message);
5310 _g_dbus_debug_print_unlock ();
5316 *error = local_error;
5318 g_error_free (local_error);
5322 result = decode_method_reply (reply, method_name, reply_type, error);
5325 if (message != NULL)
5326 g_object_unref (message);
5328 g_object_unref (reply);
5333 /* ---------------------------------------------------------------------------------------------------- */
5335 struct ExportedSubtree
5339 GDBusConnection *connection;
5340 GDBusSubtreeVTable *vtable;
5341 GDBusSubtreeFlags flags;
5343 GMainContext *context;
5345 GDestroyNotify user_data_free_func;
5349 exported_subtree_free (ExportedSubtree *es)
5351 call_destroy_notify (es->context,
5352 es->user_data_free_func,
5355 if (es->context != NULL)
5356 g_main_context_unref (es->context);
5358 _g_dbus_subtree_vtable_free (es->vtable);
5359 g_free (es->object_path);
5363 /* called without lock held */
5365 handle_subtree_introspect (GDBusConnection *connection,
5366 ExportedSubtree *es,
5367 GDBusMessage *message)
5371 GDBusMessage *reply;
5374 const gchar *sender;
5375 const gchar *requested_object_path;
5376 const gchar *requested_node;
5377 GDBusInterfaceInfo **interfaces;
5379 gchar **subnode_paths;
5383 requested_object_path = g_dbus_message_get_path (message);
5384 sender = g_dbus_message_get_sender (message);
5385 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5387 s = g_string_new (NULL);
5388 introspect_append_header (s);
5390 /* Strictly we don't need the children in dynamic mode, but we avoid the
5391 * conditionals to preserve code clarity
5393 children = es->vtable->enumerate (es->connection,
5400 requested_node = strrchr (requested_object_path, '/') + 1;
5402 /* Assert existence of object if we are not dynamic */
5403 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5404 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5409 requested_node = NULL;
5412 interfaces = es->vtable->introspect (es->connection,
5417 if (interfaces != NULL)
5419 introspect_append_standard_interfaces (s);
5421 for (n = 0; interfaces[n] != NULL; n++)
5423 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5424 g_dbus_interface_info_unref (interfaces[n]);
5426 g_free (interfaces);
5429 /* then include <node> entries from the Subtree for the root */
5432 for (n = 0; children != NULL && children[n] != NULL; n++)
5433 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5436 /* finally include nodes registered below us */
5437 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5438 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5439 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5440 g_strfreev (subnode_paths);
5442 g_string_append (s, "</node>\n");
5444 reply = g_dbus_message_new_method_reply (message);
5445 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5446 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5447 g_object_unref (reply);
5452 g_string_free (s, TRUE);
5453 g_strfreev (children);
5457 /* called without lock held */
5459 handle_subtree_method_invocation (GDBusConnection *connection,
5460 ExportedSubtree *es,
5461 GDBusMessage *message)
5464 const gchar *sender;
5465 const gchar *interface_name;
5466 const gchar *member;
5467 const gchar *signature;
5468 const gchar *requested_object_path;
5469 const gchar *requested_node;
5471 GDBusInterfaceInfo *interface_info;
5472 const GDBusInterfaceVTable *interface_vtable;
5473 gpointer interface_user_data;
5475 GDBusInterfaceInfo **interfaces;
5476 gboolean is_property_get;
5477 gboolean is_property_set;
5478 gboolean is_property_get_all;
5483 requested_object_path = g_dbus_message_get_path (message);
5484 sender = g_dbus_message_get_sender (message);
5485 interface_name = g_dbus_message_get_interface (message);
5486 member = g_dbus_message_get_member (message);
5487 signature = g_dbus_message_get_signature (message);
5488 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5490 is_property_get = FALSE;
5491 is_property_set = FALSE;
5492 is_property_get_all = FALSE;
5493 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5495 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5496 is_property_get = TRUE;
5497 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5498 is_property_set = TRUE;
5499 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5500 is_property_get_all = TRUE;
5505 requested_node = strrchr (requested_object_path, '/') + 1;
5507 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5509 /* We don't want to dispatch to unenumerated
5510 * nodes, so ensure that the child exists.
5515 children = es->vtable->enumerate (es->connection,
5520 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5521 g_strfreev (children);
5529 requested_node = NULL;
5532 /* get introspection data for the node */
5533 interfaces = es->vtable->introspect (es->connection,
5535 requested_object_path,
5539 if (interfaces == NULL)
5542 interface_info = NULL;
5543 for (n = 0; interfaces[n] != NULL; n++)
5545 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5546 interface_info = interfaces[n];
5549 /* dispatch the call if the user wants to handle it */
5550 if (interface_info != NULL)
5552 /* figure out where to dispatch the method call */
5553 interface_user_data = NULL;
5554 interface_vtable = es->vtable->dispatch (es->connection,
5559 &interface_user_data,
5561 if (interface_vtable == NULL)
5564 CONNECTION_LOCK (connection);
5565 handled = validate_and_maybe_schedule_method_call (es->connection,
5572 interface_user_data);
5573 CONNECTION_UNLOCK (connection);
5575 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5576 else if (is_property_get || is_property_set || is_property_get_all)
5578 if (is_property_get)
5579 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5580 else if (is_property_set)
5581 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5582 else if (is_property_get_all)
5583 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5585 g_assert_not_reached ();
5587 /* see if the object supports this interface at all */
5588 for (n = 0; interfaces[n] != NULL; n++)
5590 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5591 interface_info = interfaces[n];
5594 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5595 * claims it won't support the interface
5597 if (interface_info == NULL)
5599 GDBusMessage *reply;
5600 reply = g_dbus_message_new_method_error (message,
5601 "org.freedesktop.DBus.Error.InvalidArgs",
5602 _("No such interface `%s'"),
5604 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5605 g_object_unref (reply);
5610 /* figure out where to dispatch the property get/set/getall calls */
5611 interface_user_data = NULL;
5612 interface_vtable = es->vtable->dispatch (es->connection,
5617 &interface_user_data,
5619 if (interface_vtable == NULL)
5621 g_warning ("The subtree introspection function indicates that '%s' "
5622 "is a valid interface name, but calling the dispatch "
5623 "function on that interface gave us NULL", interface_name);
5627 if (is_property_get || is_property_set)
5629 CONNECTION_LOCK (connection);
5630 handled = validate_and_maybe_schedule_property_getset (es->connection,
5638 interface_user_data);
5639 CONNECTION_UNLOCK (connection);
5641 else if (is_property_get_all)
5643 CONNECTION_LOCK (connection);
5644 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5651 interface_user_data);
5652 CONNECTION_UNLOCK (connection);
5657 if (interfaces != NULL)
5659 for (n = 0; interfaces[n] != NULL; n++)
5660 g_dbus_interface_info_unref (interfaces[n]);
5661 g_free (interfaces);
5669 GDBusMessage *message;
5670 ExportedSubtree *es;
5671 } SubtreeDeferredData;
5674 subtree_deferred_data_free (SubtreeDeferredData *data)
5676 g_object_unref (data->message);
5680 /* called without lock held in the thread where the caller registered the subtree */
5682 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5684 SubtreeDeferredData *data = _data;
5689 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5690 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5691 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5692 handled = handle_subtree_introspect (data->es->connection,
5696 handled = handle_subtree_method_invocation (data->es->connection,
5702 CONNECTION_LOCK (data->es->connection);
5703 handled = handle_generic_unlocked (data->es->connection, data->message);
5704 CONNECTION_UNLOCK (data->es->connection);
5707 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5710 GDBusMessage *reply;
5711 reply = g_dbus_message_new_method_error (data->message,
5712 "org.freedesktop.DBus.Error.UnknownMethod",
5713 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5714 g_dbus_message_get_member (data->message),
5715 g_dbus_message_get_interface (data->message),
5716 g_dbus_message_get_signature (data->message));
5717 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5718 g_object_unref (reply);
5724 /* called in message handler thread with lock held */
5726 subtree_message_func (GDBusConnection *connection,
5727 ExportedSubtree *es,
5728 GDBusMessage *message)
5730 GSource *idle_source;
5731 SubtreeDeferredData *data;
5733 data = g_new0 (SubtreeDeferredData, 1);
5734 data->message = g_object_ref (message);
5737 /* defer this call to an idle handler in the right thread */
5738 idle_source = g_idle_source_new ();
5739 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5740 g_source_set_callback (idle_source,
5741 process_subtree_vtable_message_in_idle_cb,
5743 (GDestroyNotify) subtree_deferred_data_free);
5744 g_source_attach (idle_source, es->context);
5745 g_source_unref (idle_source);
5747 /* since we own the entire subtree, handlers for objects not in the subtree have been
5748 * tried already by libdbus-1 - so we just need to ensure that we're always going
5749 * to reply to the message
5755 * g_dbus_connection_register_subtree:
5756 * @connection: A #GDBusConnection.
5757 * @object_path: The object path to register the subtree at.
5758 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5759 * @flags: Flags used to fine tune the behavior of the subtree.
5760 * @user_data: Data to pass to functions in @vtable.
5761 * @user_data_free_func: Function to call when the subtree is unregistered.
5762 * @error: Return location for error or %NULL.
5764 * Registers a whole subtree of <quote>dynamic</quote> objects.
5766 * The @enumerate and @introspection functions in @vtable are used to
5767 * convey, to remote callers, what nodes exist in the subtree rooted
5770 * When handling remote calls into any node in the subtree, first the
5771 * @enumerate function is used to check if the node exists. If the node exists
5772 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5773 * the @introspection function is used to check if the node supports the
5774 * requested method. If so, the @dispatch function is used to determine
5775 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5776 * #gpointer will be used to call into the interface vtable for processing
5779 * All calls into user-provided code will be invoked in the <link
5780 * linkend="g-main-context-push-thread-default">thread-default main
5781 * loop</link> of the thread you are calling this method from.
5783 * If an existing subtree is already registered at @object_path or
5784 * then @error is set to #G_IO_ERROR_EXISTS.
5786 * Note that it is valid to register regular objects (using
5787 * g_dbus_connection_register_object()) in a subtree registered with
5788 * g_dbus_connection_register_subtree() - if so, the subtree handler
5789 * is tried as the last resort. One way to think about a subtree
5790 * handler is to consider it a <quote>fallback handler</quote>
5791 * for object paths not registered via g_dbus_connection_register_object()
5792 * or other bindings.
5794 * Note that @vtable will be copied so you cannot change it after
5797 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5799 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5800 * that can be used with g_dbus_connection_unregister_subtree() .
5805 g_dbus_connection_register_subtree (GDBusConnection *connection,
5806 const gchar *object_path,
5807 const GDBusSubtreeVTable *vtable,
5808 GDBusSubtreeFlags flags,
5810 GDestroyNotify user_data_free_func,
5814 ExportedSubtree *es;
5816 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5817 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5818 g_return_val_if_fail (vtable != NULL, 0);
5819 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5823 CONNECTION_LOCK (connection);
5825 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5831 _("A subtree is already exported for %s"),
5836 es = g_new0 (ExportedSubtree, 1);
5837 es->object_path = g_strdup (object_path);
5838 es->connection = connection;
5840 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5842 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5843 es->user_data = user_data;
5844 es->user_data_free_func = user_data_free_func;
5845 es->context = g_main_context_get_thread_default ();
5846 if (es->context != NULL)
5847 g_main_context_ref (es->context);
5849 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5850 g_hash_table_insert (connection->map_id_to_es,
5851 GUINT_TO_POINTER (es->id),
5857 CONNECTION_UNLOCK (connection);
5862 /* ---------------------------------------------------------------------------------------------------- */
5865 * g_dbus_connection_unregister_subtree:
5866 * @connection: A #GDBusConnection.
5867 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5869 * Unregisters a subtree.
5871 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5876 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5877 guint registration_id)
5879 ExportedSubtree *es;
5882 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5886 CONNECTION_LOCK (connection);
5888 es = g_hash_table_lookup (connection->map_id_to_es,
5889 GUINT_TO_POINTER (registration_id));
5893 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5894 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5899 CONNECTION_UNLOCK (connection);
5904 /* ---------------------------------------------------------------------------------------------------- */
5906 /* must be called with lock held */
5908 handle_generic_ping_unlocked (GDBusConnection *connection,
5909 const gchar *object_path,
5910 GDBusMessage *message)
5912 GDBusMessage *reply;
5913 reply = g_dbus_message_new_method_reply (message);
5914 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5915 g_object_unref (reply);
5918 /* must be called with lock held */
5920 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5921 const gchar *object_path,
5922 GDBusMessage *message)
5924 GDBusMessage *reply;
5927 if (connection->machine_id == NULL)
5932 connection->machine_id = _g_dbus_get_machine_id (&error);
5933 if (connection->machine_id == NULL)
5935 reply = g_dbus_message_new_method_error_literal (message,
5936 "org.freedesktop.DBus.Error.Failed",
5938 g_error_free (error);
5944 reply = g_dbus_message_new_method_reply (message);
5945 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5947 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5948 g_object_unref (reply);
5951 /* must be called with lock held */
5953 handle_generic_introspect_unlocked (GDBusConnection *connection,
5954 const gchar *object_path,
5955 GDBusMessage *message)
5960 GDBusMessage *reply;
5962 /* first the header */
5963 s = g_string_new (NULL);
5964 introspect_append_header (s);
5966 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5967 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5968 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5969 g_strfreev (registered);
5970 g_string_append (s, "</node>\n");
5972 reply = g_dbus_message_new_method_reply (message);
5973 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5974 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5975 g_object_unref (reply);
5976 g_string_free (s, TRUE);
5979 /* must be called with lock held */
5981 handle_generic_unlocked (GDBusConnection *connection,
5982 GDBusMessage *message)
5985 const gchar *interface_name;
5986 const gchar *member;
5987 const gchar *signature;
5990 CONNECTION_ENSURE_LOCK (connection);
5994 interface_name = g_dbus_message_get_interface (message);
5995 member = g_dbus_message_get_member (message);
5996 signature = g_dbus_message_get_signature (message);
5997 path = g_dbus_message_get_path (message);
5999 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6000 g_strcmp0 (member, "Introspect") == 0 &&
6001 g_strcmp0 (signature, "") == 0)
6003 handle_generic_introspect_unlocked (connection, path, message);
6006 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6007 g_strcmp0 (member, "Ping") == 0 &&
6008 g_strcmp0 (signature, "") == 0)
6010 handle_generic_ping_unlocked (connection, path, message);
6013 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6014 g_strcmp0 (member, "GetMachineId") == 0 &&
6015 g_strcmp0 (signature, "") == 0)
6017 handle_generic_get_machine_id_unlocked (connection, path, message);
6024 /* ---------------------------------------------------------------------------------------------------- */
6026 /* called in message handler thread with lock held */
6028 distribute_method_call (GDBusConnection *connection,
6029 GDBusMessage *message)
6031 GDBusMessage *reply;
6033 ExportedSubtree *es;
6034 const gchar *object_path;
6035 const gchar *interface_name;
6036 const gchar *member;
6037 const gchar *signature;
6039 gchar *subtree_path;
6042 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6044 interface_name = g_dbus_message_get_interface (message);
6045 member = g_dbus_message_get_member (message);
6046 signature = g_dbus_message_get_signature (message);
6047 path = g_dbus_message_get_path (message);
6048 subtree_path = g_strdup (path);
6049 needle = strrchr (subtree_path, '/');
6050 if (needle != NULL && needle != subtree_path)
6056 g_free (subtree_path);
6057 subtree_path = NULL;
6061 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6063 _g_dbus_debug_print_lock ();
6064 g_print ("========================================================================\n"
6065 "GDBus-debug:Incoming:\n"
6066 " <<<< METHOD INVOCATION %s.%s()\n"
6068 " invoked by name %s\n"
6070 interface_name, member,
6072 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6073 g_dbus_message_get_serial (message));
6074 _g_dbus_debug_print_unlock ();
6078 g_debug ("interface = `%s'", interface_name);
6079 g_debug ("member = `%s'", member);
6080 g_debug ("signature = `%s'", signature);
6081 g_debug ("path = `%s'", path);
6082 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
6085 object_path = g_dbus_message_get_path (message);
6086 g_assert (object_path != NULL);
6088 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6091 if (obj_message_func (connection, eo, message))
6095 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6098 if (subtree_message_func (connection, es, message))
6102 if (subtree_path != NULL)
6104 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6107 if (subtree_message_func (connection, es, message))
6112 if (handle_generic_unlocked (connection, message))
6115 /* if we end up here, the message has not been not handled - so return an error saying this */
6116 reply = g_dbus_message_new_method_error (message,
6117 "org.freedesktop.DBus.Error.UnknownMethod",
6118 _("No such interface `%s' on object at path %s"),
6121 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6122 g_object_unref (reply);
6125 g_free (subtree_path);
6128 /* ---------------------------------------------------------------------------------------------------- */
6130 static GDBusConnection **
6131 message_bus_get_singleton (GBusType bus_type,
6134 GDBusConnection **ret;
6135 const gchar *starter_bus;
6141 case G_BUS_TYPE_SESSION:
6142 ret = &the_session_bus;
6145 case G_BUS_TYPE_SYSTEM:
6146 ret = &the_system_bus;
6149 case G_BUS_TYPE_STARTER:
6150 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6151 if (g_strcmp0 (starter_bus, "session") == 0)
6153 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6156 else if (g_strcmp0 (starter_bus, "system") == 0)
6158 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6163 if (starter_bus != NULL)
6167 G_IO_ERROR_INVALID_ARGUMENT,
6168 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6169 " - unknown value `%s'"),
6174 g_set_error_literal (error,
6176 G_IO_ERROR_INVALID_ARGUMENT,
6177 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6178 "variable is not set"));
6184 g_assert_not_reached ();
6192 static GDBusConnection *
6193 get_uninitialized_connection (GBusType bus_type,
6194 GCancellable *cancellable,
6197 GDBusConnection **singleton;
6198 GDBusConnection *ret;
6202 G_LOCK (message_bus_lock);
6203 singleton = message_bus_get_singleton (bus_type, error);
6204 if (singleton == NULL)
6207 if (*singleton == NULL)
6210 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6211 if (address == NULL)
6213 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6215 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6216 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6217 "exit-on-close", TRUE,
6223 ret = g_object_ref (*singleton);
6226 g_assert (ret != NULL);
6229 G_UNLOCK (message_bus_lock);
6235 * @bus_type: A #GBusType.
6236 * @cancellable: A #GCancellable or %NULL.
6237 * @error: Return location for error or %NULL.
6239 * Synchronously connects to the message bus specified by @bus_type.
6240 * Note that the returned object may shared with other callers,
6241 * e.g. if two separate parts of a process calls this function with
6242 * the same @bus_type, they will share the same object.
6244 * This is a synchronous failable function. See g_bus_get() and
6245 * g_bus_get_finish() for the asynchronous version.
6247 * The returned object is a singleton, that is, shared with other
6248 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6249 * event that you need a private message bus connection, use
6250 * g_dbus_address_get_for_bus_sync() and
6251 * g_dbus_connection_new_for_address().
6253 * Note that the returned #GDBusConnection object will (usually) have
6254 * the #GDBusConnection:exit-on-close property set to %TRUE.
6256 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6261 g_bus_get_sync (GBusType bus_type,
6262 GCancellable *cancellable,
6265 GDBusConnection *connection;
6267 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6269 connection = get_uninitialized_connection (bus_type, cancellable, error);
6270 if (connection == NULL)
6273 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6275 g_object_unref (connection);
6284 bus_get_async_initable_cb (GObject *source_object,
6288 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6292 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6296 g_assert (error != NULL);
6297 g_simple_async_result_take_error (simple, error);
6298 g_object_unref (source_object);
6302 g_simple_async_result_set_op_res_gpointer (simple,
6306 g_simple_async_result_complete_in_idle (simple);
6307 g_object_unref (simple);
6312 * @bus_type: A #GBusType.
6313 * @cancellable: A #GCancellable or %NULL.
6314 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6315 * @user_data: The data to pass to @callback.
6317 * Asynchronously connects to the message bus specified by @bus_type.
6319 * When the operation is finished, @callback will be invoked. You can
6320 * then call g_bus_get_finish() to get the result of the operation.
6322 * This is a asynchronous failable function. See g_bus_get_sync() for
6323 * the synchronous version.
6328 g_bus_get (GBusType bus_type,
6329 GCancellable *cancellable,
6330 GAsyncReadyCallback callback,
6333 GDBusConnection *connection;
6334 GSimpleAsyncResult *simple;
6337 simple = g_simple_async_result_new (NULL,
6343 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6344 if (connection == NULL)
6346 g_assert (error != NULL);
6347 g_simple_async_result_take_error (simple, error);
6348 g_simple_async_result_complete_in_idle (simple);
6349 g_object_unref (simple);
6353 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6356 bus_get_async_initable_cb,
6363 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6364 * @error: Return location for error or %NULL.
6366 * Finishes an operation started with g_bus_get().
6368 * The returned object is a singleton, that is, shared with other
6369 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6370 * event that you need a private message bus connection, use
6371 * g_dbus_address_get_for_bus() and
6372 * g_dbus_connection_new_for_address().
6374 * Note that the returned #GDBusConnection object will (usually) have
6375 * the #GDBusConnection:exit-on-close property set to %TRUE.
6377 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6382 g_bus_get_finish (GAsyncResult *res,
6385 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6387 GDBusConnection *ret;
6389 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6391 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6395 if (g_simple_async_result_propagate_error (simple, error))
6398 object = g_simple_async_result_get_op_res_gpointer (simple);
6399 g_assert (object != NULL);
6400 ret = g_object_ref (G_DBUS_CONNECTION (object));
6406 /* ---------------------------------------------------------------------------------------------------- */