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;
2056 G_LOCK (message_bus_lock);
2057 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2060 G_UNLOCK (message_bus_lock);
2063 connection = G_DBUS_CONNECTION (user_data);
2064 g_object_ref (connection);
2065 G_UNLOCK (message_bus_lock);
2067 //g_debug ("in on_worker_message_received");
2069 g_object_ref (message);
2070 g_dbus_message_lock (message);
2072 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2074 /* First collect the set of callback functions */
2075 CONNECTION_LOCK (connection);
2076 num_filters = connection->filters->len;
2077 filters = g_new0 (FilterCallback, num_filters);
2078 for (n = 0; n < num_filters; n++)
2080 FilterData *data = connection->filters->pdata[n];
2081 filters[n].func = data->filter_function;
2082 filters[n].user_data = data->user_data;
2084 CONNECTION_UNLOCK (connection);
2086 /* then call the filters in order (without holding the lock) */
2087 for (n = 0; n < num_filters; n++)
2089 message = filters[n].func (connection,
2092 filters[n].user_data);
2093 if (message == NULL)
2095 g_dbus_message_lock (message);
2098 /* Standard dispatch unless the filter ate the message - no need to
2099 * do anything if the message was altered
2101 if (message != NULL)
2103 GDBusMessageType message_type;
2105 message_type = g_dbus_message_get_message_type (message);
2106 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2108 guint32 reply_serial;
2109 SendMessageData *send_message_data;
2111 reply_serial = g_dbus_message_get_reply_serial (message);
2112 CONNECTION_LOCK (connection);
2113 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2114 GUINT_TO_POINTER (reply_serial));
2115 if (send_message_data != NULL)
2117 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2118 send_message_data_deliver_reply_unlocked (send_message_data, message);
2122 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2124 CONNECTION_UNLOCK (connection);
2126 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2128 CONNECTION_LOCK (connection);
2129 distribute_signals (connection, message);
2130 CONNECTION_UNLOCK (connection);
2132 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2134 CONNECTION_LOCK (connection);
2135 distribute_method_call (connection, message);
2136 CONNECTION_UNLOCK (connection);
2140 if (message != NULL)
2141 g_object_unref (message);
2142 g_object_unref (connection);
2146 /* Called in worker's thread */
2147 static GDBusMessage *
2148 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2149 GDBusMessage *message,
2152 GDBusConnection *connection;
2153 FilterCallback *filters;
2158 G_LOCK (message_bus_lock);
2159 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2162 G_UNLOCK (message_bus_lock);
2165 connection = G_DBUS_CONNECTION (user_data);
2166 g_object_ref (connection);
2167 G_UNLOCK (message_bus_lock);
2169 //g_debug ("in on_worker_message_about_to_be_sent");
2171 /* First collect the set of callback functions */
2172 CONNECTION_LOCK (connection);
2173 num_filters = connection->filters->len;
2174 filters = g_new0 (FilterCallback, num_filters);
2175 for (n = 0; n < num_filters; n++)
2177 FilterData *data = connection->filters->pdata[n];
2178 filters[n].func = data->filter_function;
2179 filters[n].user_data = data->user_data;
2181 CONNECTION_UNLOCK (connection);
2183 /* then call the filters in order (without holding the lock) */
2184 for (n = 0; n < num_filters; n++)
2186 g_dbus_message_lock (message);
2187 message = filters[n].func (connection,
2190 filters[n].user_data);
2191 if (message == NULL)
2195 g_object_unref (connection);
2201 /* Called in worker's thread - we must not block */
2203 on_worker_closed (GDBusWorker *worker,
2204 gboolean remote_peer_vanished,
2208 GDBusConnection *connection;
2211 G_LOCK (message_bus_lock);
2212 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2215 G_UNLOCK (message_bus_lock);
2218 connection = G_DBUS_CONNECTION (user_data);
2219 g_object_ref (connection);
2220 G_UNLOCK (message_bus_lock);
2222 //g_debug ("in on_worker_closed: %s", error->message);
2224 CONNECTION_LOCK (connection);
2225 if (!connection->closed)
2226 set_closed_unlocked (connection, remote_peer_vanished, error);
2227 CONNECTION_UNLOCK (connection);
2229 g_object_unref (connection);
2232 /* ---------------------------------------------------------------------------------------------------- */
2234 /* Determines the biggest set of capabilities we can support on this connection */
2235 static GDBusCapabilityFlags
2236 get_offered_capabilities_max (GDBusConnection *connection)
2238 GDBusCapabilityFlags ret;
2239 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2241 if (G_IS_UNIX_CONNECTION (connection->stream))
2242 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2248 initable_init (GInitable *initable,
2249 GCancellable *cancellable,
2252 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2255 /* This method needs to be idempotent to work with the singleton
2256 * pattern. See the docs for g_initable_init(). We implement this by
2259 * Unfortunately we can't use the main lock since the on_worker_*()
2260 * callbacks above needs the lock during initialization (for message
2261 * bus connections we do a synchronous Hello() call on the bus).
2263 g_mutex_lock (connection->init_lock);
2267 /* First, handle the case where the connection already has an
2268 * initialization error set.
2270 if (connection->initialization_error != NULL)
2273 /* Also make this a no-op if we're already initialized fine */
2274 if (connection->is_initialized)
2280 g_assert (connection->initialization_error == NULL && !connection->is_initialized);
2282 /* The user can pass multiple (but mutally exclusive) construct
2285 * - stream (of type GIOStream)
2286 * - address (of type gchar*)
2288 * At the end of the day we end up with a non-NULL GIOStream
2289 * object in connection->stream.
2291 if (connection->address != NULL)
2293 g_assert (connection->stream == NULL);
2295 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2296 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2298 g_set_error_literal (error,
2300 G_IO_ERROR_INVALID_ARGUMENT,
2301 _("Unsupported flags encountered when constructing a client-side connection"));
2305 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2306 NULL, /* TODO: out_guid */
2308 &connection->initialization_error);
2309 if (connection->stream == NULL)
2312 else if (connection->stream != NULL)
2318 g_assert_not_reached ();
2321 /* Authenticate the connection */
2322 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2324 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2325 g_assert (connection->guid != NULL);
2326 connection->auth = _g_dbus_auth_new (connection->stream);
2327 if (!_g_dbus_auth_run_server (connection->auth,
2328 connection->authentication_observer,
2330 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2331 get_offered_capabilities_max (connection),
2332 &connection->capabilities,
2333 &connection->credentials,
2335 &connection->initialization_error))
2338 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2340 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2341 g_assert (connection->guid == NULL);
2342 connection->auth = _g_dbus_auth_new (connection->stream);
2343 connection->guid = _g_dbus_auth_run_client (connection->auth,
2344 get_offered_capabilities_max (connection),
2345 &connection->capabilities,
2347 &connection->initialization_error);
2348 if (connection->guid == NULL)
2352 if (connection->authentication_observer != NULL)
2354 g_object_unref (connection->authentication_observer);
2355 connection->authentication_observer = NULL;
2358 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2360 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2365 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
2369 if (G_IS_SOCKET_CONNECTION (connection->stream))
2371 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2375 G_LOCK (message_bus_lock);
2376 if (alive_connections == NULL)
2377 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2378 g_hash_table_insert (alive_connections, connection, connection);
2379 G_UNLOCK (message_bus_lock);
2381 connection->worker = _g_dbus_worker_new (connection->stream,
2382 connection->capabilities,
2383 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2384 on_worker_message_received,
2385 on_worker_message_about_to_be_sent,
2389 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2390 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2392 GVariant *hello_result;
2394 /* we could lift this restriction by adding code in gdbusprivate.c */
2395 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2397 g_set_error_literal (&connection->initialization_error,
2400 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2404 hello_result = g_dbus_connection_call_sync (connection,
2405 "org.freedesktop.DBus", /* name */
2406 "/org/freedesktop/DBus", /* path */
2407 "org.freedesktop.DBus", /* interface */
2409 NULL, /* parameters */
2410 G_VARIANT_TYPE ("(s)"),
2411 G_DBUS_CALL_FLAGS_NONE,
2413 NULL, /* TODO: cancellable */
2414 &connection->initialization_error);
2415 if (hello_result == NULL)
2418 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2419 g_variant_unref (hello_result);
2420 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2423 connection->is_initialized = TRUE;
2429 g_assert (connection->initialization_error != NULL);
2430 g_propagate_error (error, g_error_copy (connection->initialization_error));
2433 g_mutex_unlock (connection->init_lock);
2439 initable_iface_init (GInitableIface *initable_iface)
2441 initable_iface->init = initable_init;
2444 /* ---------------------------------------------------------------------------------------------------- */
2447 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2452 /* ---------------------------------------------------------------------------------------------------- */
2455 * g_dbus_connection_new:
2456 * @stream: A #GIOStream.
2457 * @guid: The GUID to use if a authenticating as a server or %NULL.
2458 * @flags: Flags describing how to make the connection.
2459 * @observer: A #GDBusAuthObserver or %NULL.
2460 * @cancellable: A #GCancellable or %NULL.
2461 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2462 * @user_data: The data to pass to @callback.
2464 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2465 * with the end represented by @stream.
2467 * If @observer is not %NULL it may be used to control the
2468 * authentication process.
2470 * When the operation is finished, @callback will be invoked. You can
2471 * then call g_dbus_connection_new_finish() to get the result of the
2474 * This is a asynchronous failable constructor. See
2475 * g_dbus_connection_new_sync() for the synchronous
2481 g_dbus_connection_new (GIOStream *stream,
2483 GDBusConnectionFlags flags,
2484 GDBusAuthObserver *observer,
2485 GCancellable *cancellable,
2486 GAsyncReadyCallback callback,
2489 g_return_if_fail (G_IS_IO_STREAM (stream));
2490 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2498 "authentication-observer", observer,
2503 * g_dbus_connection_new_finish:
2504 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2505 * @error: Return location for error or %NULL.
2507 * Finishes an operation started with g_dbus_connection_new().
2509 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2514 g_dbus_connection_new_finish (GAsyncResult *res,
2518 GObject *source_object;
2520 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2521 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2523 source_object = g_async_result_get_source_object (res);
2524 g_assert (source_object != NULL);
2525 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2528 g_object_unref (source_object);
2530 return G_DBUS_CONNECTION (object);
2536 * g_dbus_connection_new_sync:
2537 * @stream: A #GIOStream.
2538 * @guid: The GUID to use if a authenticating as a server or %NULL.
2539 * @flags: Flags describing how to make the connection.
2540 * @observer: A #GDBusAuthObserver or %NULL.
2541 * @cancellable: A #GCancellable or %NULL.
2542 * @error: Return location for error or %NULL.
2544 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2545 * with the end represented by @stream.
2547 * If @observer is not %NULL it may be used to control the
2548 * authentication process.
2550 * This is a synchronous failable constructor. See
2551 * g_dbus_connection_new() for the asynchronous version.
2553 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2558 g_dbus_connection_new_sync (GIOStream *stream,
2560 GDBusConnectionFlags flags,
2561 GDBusAuthObserver *observer,
2562 GCancellable *cancellable,
2565 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2566 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2567 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2573 "authentication-observer", observer,
2577 /* ---------------------------------------------------------------------------------------------------- */
2580 * g_dbus_connection_new_for_address:
2581 * @address: A D-Bus address.
2582 * @flags: Flags describing how to make the connection.
2583 * @observer: A #GDBusAuthObserver or %NULL.
2584 * @cancellable: A #GCancellable or %NULL.
2585 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2586 * @user_data: The data to pass to @callback.
2588 * Asynchronously connects and sets up a D-Bus client connection for
2589 * exchanging D-Bus messages with an endpoint specified by @address
2590 * which must be in the D-Bus address format.
2592 * This constructor can only be used to initiate client-side
2593 * connections - use g_dbus_connection_new() if you need to act as the
2594 * server. In particular, @flags cannot contain the
2595 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2596 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2598 * When the operation is finished, @callback will be invoked. You can
2599 * then call g_dbus_connection_new_finish() to get the result of the
2602 * If @observer is not %NULL it may be used to control the
2603 * authentication process.
2605 * This is a asynchronous failable constructor. See
2606 * g_dbus_connection_new_for_address_sync() for the synchronous
2612 g_dbus_connection_new_for_address (const gchar *address,
2613 GDBusConnectionFlags flags,
2614 GDBusAuthObserver *observer,
2615 GCancellable *cancellable,
2616 GAsyncReadyCallback callback,
2619 g_return_if_fail (address != NULL);
2620 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2627 "authentication-observer", observer,
2632 * g_dbus_connection_new_for_address_finish:
2633 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2634 * @error: Return location for error or %NULL.
2636 * Finishes an operation started with g_dbus_connection_new_for_address().
2638 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2643 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2647 GObject *source_object;
2649 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2650 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2652 source_object = g_async_result_get_source_object (res);
2653 g_assert (source_object != NULL);
2654 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2657 g_object_unref (source_object);
2659 return G_DBUS_CONNECTION (object);
2665 * g_dbus_connection_new_for_address_sync:
2666 * @address: A D-Bus address.
2667 * @flags: Flags describing how to make the connection.
2668 * @observer: A #GDBusAuthObserver or %NULL.
2669 * @cancellable: A #GCancellable or %NULL.
2670 * @error: Return location for error or %NULL.
2672 * Synchronously connects and sets up a D-Bus client connection for
2673 * exchanging D-Bus messages with an endpoint specified by @address
2674 * which must be in the D-Bus address format.
2676 * This constructor can only be used to initiate client-side
2677 * connections - use g_dbus_connection_new_sync() if you need to act
2678 * as the server. In particular, @flags cannot contain the
2679 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2680 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2682 * This is a synchronous failable constructor. See
2683 * g_dbus_connection_new_for_address() for the asynchronous version.
2685 * If @observer is not %NULL it may be used to control the
2686 * authentication process.
2688 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2693 g_dbus_connection_new_for_address_sync (const gchar *address,
2694 GDBusConnectionFlags flags,
2695 GDBusAuthObserver *observer,
2696 GCancellable *cancellable,
2699 g_return_val_if_fail (address != NULL, NULL);
2700 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2701 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2706 "authentication-observer", observer,
2710 /* ---------------------------------------------------------------------------------------------------- */
2713 * g_dbus_connection_set_exit_on_close:
2714 * @connection: A #GDBusConnection.
2715 * @exit_on_close: Whether the process should be terminated
2716 * when @connection is closed by the remote peer.
2718 * Sets whether the process should be terminated when @connection is
2719 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2722 * Note that this function should be used with care. Most modern UNIX
2723 * desktops tie the notion of a user session the session bus, and expect
2724 * all of a users applications to quit when their bus connection goes away.
2725 * If you are setting @exit_on_close to %FALSE for the shared session
2726 * bus connection, you should make sure that your application exits
2727 * when the user session ends.
2732 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2733 gboolean exit_on_close)
2735 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2736 connection->exit_on_close = exit_on_close;
2740 * g_dbus_connection_get_exit_on_close:
2741 * @connection: A #GDBusConnection.
2743 * Gets whether the process is terminated when @connection is
2744 * closed by the remote peer. See
2745 * #GDBusConnection:exit-on-close for more details.
2747 * Returns: Whether the process is terminated when @connection is
2748 * closed by the remote peer.
2753 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2755 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2756 return connection->exit_on_close;
2760 * g_dbus_connection_get_guid:
2761 * @connection: A #GDBusConnection.
2763 * The GUID of the peer performing the role of server when
2764 * authenticating. See #GDBusConnection:guid for more details.
2766 * Returns: The GUID. Do not free this string, it is owned by
2772 g_dbus_connection_get_guid (GDBusConnection *connection)
2774 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2775 return connection->guid;
2779 * g_dbus_connection_get_unique_name:
2780 * @connection: A #GDBusConnection.
2782 * Gets the unique name of @connection as assigned by the message
2783 * bus. This can also be used to figure out if @connection is a
2784 * message bus connection.
2786 * Returns: The unique name or %NULL if @connection is not a message
2787 * bus connection. Do not free this string, it is owned by
2793 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2795 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2796 return connection->bus_unique_name;
2800 * g_dbus_connection_get_peer_credentials:
2801 * @connection: A #GDBusConnection.
2803 * Gets the credentials of the authenticated peer. This will always
2804 * return %NULL unless @connection acted as a server
2805 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2806 * when set up and the client passed credentials as part of the
2807 * authentication process.
2809 * In a message bus setup, the message bus is always the server and
2810 * each application is a client. So this method will always return
2811 * %NULL for message bus clients.
2813 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
2814 * this object, it is owned by @connection.
2819 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2821 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2822 return connection->credentials;
2825 /* ---------------------------------------------------------------------------------------------------- */
2827 static guint _global_filter_id = 1;
2830 * g_dbus_connection_add_filter:
2831 * @connection: A #GDBusConnection.
2832 * @filter_function: A filter function.
2833 * @user_data: User data to pass to @filter_function.
2834 * @user_data_free_func: Function to free @user_data with when filter
2835 * is removed or %NULL.
2837 * Adds a message filter. Filters are handlers that are run on all
2838 * incoming and outgoing messages, prior to standard dispatch. Filters
2839 * are run in the order that they were added. The same handler can be
2840 * added as a filter more than once, in which case it will be run more
2841 * than once. Filters added during a filter callback won't be run on
2842 * the message being processed. Filter functions are allowed to modify
2843 * and even drop messages - see the #GDBusMessageFilterResult
2844 * enumeration for details.
2846 * Note that filters are run in a dedicated message handling thread so
2847 * they can't block and, generally, can't do anything but signal a
2848 * worker thread. Also note that filters are rarely needed - use API
2849 * such as g_dbus_connection_send_message_with_reply(),
2850 * g_dbus_connection_signal_subscribe() or
2851 * g_dbus_connection_call() instead.
2853 * If a filter consumes an incoming message the message is not
2854 * dispatched anywhere else - not even the standard dispatch machinery
2855 * (that API such as g_dbus_connection_signal_subscribe() and
2856 * g_dbus_connection_send_message_with_reply() relies on) will see the
2857 * message. Similary, if a filter consumes an outgoing message, the
2858 * message will not be sent to the other peer.
2860 * Returns: A filter identifier that can be used with
2861 * g_dbus_connection_remove_filter().
2866 g_dbus_connection_add_filter (GDBusConnection *connection,
2867 GDBusMessageFilterFunction filter_function,
2869 GDestroyNotify user_data_free_func)
2873 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2874 g_return_val_if_fail (filter_function != NULL, 0);
2876 CONNECTION_LOCK (connection);
2877 data = g_new0 (FilterData, 1);
2878 data->id = _global_filter_id++; /* TODO: overflow etc. */
2879 data->filter_function = filter_function;
2880 data->user_data = user_data;
2881 data->user_data_free_func = user_data_free_func;
2882 g_ptr_array_add (connection->filters, data);
2883 CONNECTION_UNLOCK (connection);
2888 /* only called from finalize(), removes all filters */
2890 purge_all_filters (GDBusConnection *connection)
2893 for (n = 0; n < connection->filters->len; n++)
2895 FilterData *data = connection->filters->pdata[n];
2896 if (data->user_data_free_func != NULL)
2897 data->user_data_free_func (data->user_data);
2903 * g_dbus_connection_remove_filter:
2904 * @connection: a #GDBusConnection
2905 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2912 g_dbus_connection_remove_filter (GDBusConnection *connection,
2916 FilterData *to_destroy;
2918 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2920 CONNECTION_LOCK (connection);
2922 for (n = 0; n < connection->filters->len; n++)
2924 FilterData *data = connection->filters->pdata[n];
2925 if (data->id == filter_id)
2927 g_ptr_array_remove_index (connection->filters, n);
2932 CONNECTION_UNLOCK (connection);
2934 /* do free without holding lock */
2935 if (to_destroy != NULL)
2937 if (to_destroy->user_data_free_func != NULL)
2938 to_destroy->user_data_free_func (to_destroy->user_data);
2939 g_free (to_destroy);
2943 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2947 /* ---------------------------------------------------------------------------------------------------- */
2953 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2954 gchar *interface_name;
2958 GArray *subscribers;
2963 GDBusSignalCallback callback;
2965 GDestroyNotify user_data_free_func;
2967 GMainContext *context;
2971 signal_data_free (SignalData *signal_data)
2973 g_free (signal_data->rule);
2974 g_free (signal_data->sender);
2975 g_free (signal_data->sender_unique_name);
2976 g_free (signal_data->interface_name);
2977 g_free (signal_data->member);
2978 g_free (signal_data->object_path);
2979 g_free (signal_data->arg0);
2980 g_array_free (signal_data->subscribers, TRUE);
2981 g_free (signal_data);
2985 args_to_rule (const gchar *sender,
2986 const gchar *interface_name,
2987 const gchar *member,
2988 const gchar *object_path,
2994 rule = g_string_new ("type='signal'");
2996 g_string_prepend_c (rule, '-');
2998 g_string_append_printf (rule, ",sender='%s'", sender);
2999 if (interface_name != NULL)
3000 g_string_append_printf (rule, ",interface='%s'", interface_name);
3002 g_string_append_printf (rule, ",member='%s'", member);
3003 if (object_path != NULL)
3004 g_string_append_printf (rule, ",path='%s'", object_path);
3006 g_string_append_printf (rule, ",arg0='%s'", arg0);
3008 return g_string_free (rule, FALSE);
3011 static guint _global_subscriber_id = 1;
3012 static guint _global_registration_id = 1;
3013 static guint _global_subtree_registration_id = 1;
3015 /* ---------------------------------------------------------------------------------------------------- */
3017 /* must hold lock when calling */
3019 add_match_rule (GDBusConnection *connection,
3020 const gchar *match_rule)
3023 GDBusMessage *message;
3025 if (match_rule[0] == '-')
3028 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3029 "/org/freedesktop/DBus", /* path */
3030 "org.freedesktop.DBus", /* interface */
3032 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3034 if (!g_dbus_connection_send_message_unlocked (connection,
3036 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3040 g_critical ("Error while sending AddMatch() message: %s", error->message);
3041 g_error_free (error);
3043 g_object_unref (message);
3046 /* ---------------------------------------------------------------------------------------------------- */
3048 /* must hold lock when calling */
3050 remove_match_rule (GDBusConnection *connection,
3051 const gchar *match_rule)
3054 GDBusMessage *message;
3056 if (match_rule[0] == '-')
3059 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3060 "/org/freedesktop/DBus", /* path */
3061 "org.freedesktop.DBus", /* interface */
3063 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3066 if (!g_dbus_connection_send_message_unlocked (connection,
3068 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3072 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3073 g_error_free (error);
3075 g_object_unref (message);
3078 /* ---------------------------------------------------------------------------------------------------- */
3081 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3083 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3084 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3085 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3086 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3087 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3090 /* ---------------------------------------------------------------------------------------------------- */
3093 * g_dbus_connection_signal_subscribe:
3094 * @connection: A #GDBusConnection.
3095 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
3096 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
3097 * @member: D-Bus signal name to match on or %NULL to match on all signals.
3098 * @object_path: Object path to match on or %NULL to match on all object paths.
3099 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
3100 * @flags: Flags describing how to subscribe to the signal (currently unused).
3101 * @callback: Callback to invoke when there is a signal matching the requested data.
3102 * @user_data: User data to pass to @callback.
3103 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
3105 * Subscribes to signals on @connection and invokes @callback with a
3106 * whenever the signal is received. Note that @callback
3107 * will be invoked in the <link
3108 * linkend="g-main-context-push-thread-default">thread-default main
3109 * loop</link> of the thread you are calling this method from.
3111 * If @connection is not a message bus connection, @sender must be
3114 * If @sender is a well-known name note that @callback is invoked with
3115 * the unique name for the owner of @sender, not the well-known name
3116 * as one would expect. This is because the message bus rewrites the
3117 * name. As such, to avoid certain race conditions, users should be
3118 * tracking the name owner of the well-known name and use that when
3119 * processing the received signal.
3121 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3126 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3127 const gchar *sender,
3128 const gchar *interface_name,
3129 const gchar *member,
3130 const gchar *object_path,
3132 GDBusSignalFlags flags,
3133 GDBusSignalCallback callback,
3135 GDestroyNotify user_data_free_func)
3138 SignalData *signal_data;
3139 SignalSubscriber subscriber;
3140 GPtrArray *signal_data_array;
3141 const gchar *sender_unique_name;
3143 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3144 * an OOM condition. We might want to change that but that would involve making
3145 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3146 * handle that. And there's really no sensible way of handling this short of retrying
3147 * to add the match rule... and then there's the little thing that, hey, maybe there's
3148 * a reason the bus in an OOM condition.
3150 * Doable, but not really sure it's worth it...
3153 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3154 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3155 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3156 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3157 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3158 g_return_val_if_fail (callback != NULL, 0);
3160 CONNECTION_LOCK (connection);
3162 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3163 * with a '-' character to prefix the rule (which will otherwise be
3166 * This allows us to hash the rule and do our lifecycle tracking in
3167 * the usual way, but the '-' prevents the match rule from ever
3168 * actually being send to the bus (either for add or remove).
3170 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3171 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3173 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3174 sender_unique_name = sender;
3176 sender_unique_name = "";
3178 subscriber.callback = callback;
3179 subscriber.user_data = user_data;
3180 subscriber.user_data_free_func = user_data_free_func;
3181 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3182 subscriber.context = g_main_context_get_thread_default ();
3183 if (subscriber.context != NULL)
3184 g_main_context_ref (subscriber.context);
3186 /* see if we've already have this rule */
3187 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3188 if (signal_data != NULL)
3190 g_array_append_val (signal_data->subscribers, subscriber);
3195 signal_data = g_new0 (SignalData, 1);
3196 signal_data->rule = rule;
3197 signal_data->sender = g_strdup (sender);
3198 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3199 signal_data->interface_name = g_strdup (interface_name);
3200 signal_data->member = g_strdup (member);
3201 signal_data->object_path = g_strdup (object_path);
3202 signal_data->arg0 = g_strdup (arg0);
3203 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3204 g_array_append_val (signal_data->subscribers, subscriber);
3206 g_hash_table_insert (connection->map_rule_to_signal_data,
3210 /* Add the match rule to the bus...
3212 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3213 * always send such messages to us.
3215 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3217 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3218 add_match_rule (connection, signal_data->rule);
3221 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3222 signal_data->sender_unique_name);
3223 if (signal_data_array == NULL)
3225 signal_data_array = g_ptr_array_new ();
3226 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3227 g_strdup (signal_data->sender_unique_name),
3230 g_ptr_array_add (signal_data_array, signal_data);
3233 g_hash_table_insert (connection->map_id_to_signal_data,
3234 GUINT_TO_POINTER (subscriber.id),
3237 CONNECTION_UNLOCK (connection);
3239 return subscriber.id;
3242 /* ---------------------------------------------------------------------------------------------------- */
3244 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3246 unsubscribe_id_internal (GDBusConnection *connection,
3247 guint subscription_id,
3248 GArray *out_removed_subscribers)
3250 SignalData *signal_data;
3251 GPtrArray *signal_data_array;
3254 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3255 GUINT_TO_POINTER (subscription_id));
3256 if (signal_data == NULL)
3258 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3262 for (n = 0; n < signal_data->subscribers->len; n++)
3264 SignalSubscriber *subscriber;
3266 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3267 if (subscriber->id != subscription_id)
3270 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3271 GUINT_TO_POINTER (subscription_id)));
3272 g_array_append_val (out_removed_subscribers, *subscriber);
3273 g_array_remove_index (signal_data->subscribers, n);
3275 if (signal_data->subscribers->len == 0)
3277 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3279 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3280 signal_data->sender_unique_name);
3281 g_warn_if_fail (signal_data_array != NULL);
3282 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3284 if (signal_data_array->len == 0)
3286 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3287 signal_data->sender_unique_name));
3290 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3291 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3293 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3294 if (!connection->closed && !connection->finalizing)
3295 remove_match_rule (connection, signal_data->rule);
3297 signal_data_free (signal_data);
3303 g_assert_not_reached ();
3310 * g_dbus_connection_signal_unsubscribe:
3311 * @connection: A #GDBusConnection.
3312 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3314 * Unsubscribes from signals.
3319 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3320 guint subscription_id)
3322 GArray *subscribers;
3325 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3327 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3329 CONNECTION_LOCK (connection);
3330 unsubscribe_id_internal (connection,
3333 CONNECTION_UNLOCK (connection);
3336 g_assert (subscribers->len == 0 || subscribers->len == 1);
3338 /* call GDestroyNotify without lock held */
3339 for (n = 0; n < subscribers->len; n++)
3341 SignalSubscriber *subscriber;
3342 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3343 call_destroy_notify (subscriber->context,
3344 subscriber->user_data_free_func,
3345 subscriber->user_data);
3346 if (subscriber->context != NULL)
3347 g_main_context_unref (subscriber->context);
3350 g_array_free (subscribers, TRUE);
3353 /* ---------------------------------------------------------------------------------------------------- */
3357 guint subscription_id;
3358 GDBusSignalCallback callback;
3360 GDBusMessage *message;
3361 GDBusConnection *connection;
3362 const gchar *sender;
3364 const gchar *interface;
3365 const gchar *member;
3368 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3372 emit_signal_instance_in_idle_cb (gpointer data)
3374 SignalInstance *signal_instance = data;
3375 GVariant *parameters;
3376 gboolean has_subscription;
3378 parameters = g_dbus_message_get_body (signal_instance->message);
3379 if (parameters == NULL)
3381 parameters = g_variant_new ("()");
3382 g_variant_ref_sink (parameters);
3386 g_variant_ref_sink (parameters);
3390 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3391 signal_instance->subscription_id,
3392 signal_instance->sender,
3393 signal_instance->path,
3394 signal_instance->interface,
3395 signal_instance->member,
3396 g_variant_print (parameters, TRUE));
3399 /* Careful here, don't do the callback if we no longer has the subscription */
3400 CONNECTION_LOCK (signal_instance->connection);
3401 has_subscription = FALSE;
3402 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3403 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3404 has_subscription = TRUE;
3405 CONNECTION_UNLOCK (signal_instance->connection);
3407 if (has_subscription)
3408 signal_instance->callback (signal_instance->connection,
3409 signal_instance->sender,
3410 signal_instance->path,
3411 signal_instance->interface,
3412 signal_instance->member,
3414 signal_instance->user_data);
3416 if (parameters != NULL)
3417 g_variant_unref (parameters);
3423 signal_instance_free (SignalInstance *signal_instance)
3425 g_object_unref (signal_instance->message);
3426 g_object_unref (signal_instance->connection);
3427 g_free (signal_instance);
3430 /* called in message handler thread WITH lock held */
3432 schedule_callbacks (GDBusConnection *connection,
3433 GPtrArray *signal_data_array,
3434 GDBusMessage *message,
3435 const gchar *sender)
3438 const gchar *interface;
3439 const gchar *member;
3448 interface = g_dbus_message_get_interface (message);
3449 member = g_dbus_message_get_member (message);
3450 path = g_dbus_message_get_path (message);
3451 arg0 = g_dbus_message_get_arg0 (message);
3454 g_print ("In schedule_callbacks:\n"
3456 " interface = `%s'\n"
3467 /* TODO: if this is slow, then we can change signal_data_array into
3468 * map_object_path_to_signal_data_array or something.
3470 for (n = 0; n < signal_data_array->len; n++)
3472 SignalData *signal_data = signal_data_array->pdata[n];
3474 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3477 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3480 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3483 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3486 for (m = 0; m < signal_data->subscribers->len; m++)
3488 SignalSubscriber *subscriber;
3489 GSource *idle_source;
3490 SignalInstance *signal_instance;
3492 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3494 signal_instance = g_new0 (SignalInstance, 1);
3495 signal_instance->subscription_id = subscriber->id;
3496 signal_instance->callback = subscriber->callback;
3497 signal_instance->user_data = subscriber->user_data;
3498 signal_instance->message = g_object_ref (message);
3499 signal_instance->connection = g_object_ref (connection);
3500 signal_instance->sender = sender;
3501 signal_instance->path = path;
3502 signal_instance->interface = interface;
3503 signal_instance->member = member;
3505 idle_source = g_idle_source_new ();
3506 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3507 g_source_set_callback (idle_source,
3508 emit_signal_instance_in_idle_cb,
3510 (GDestroyNotify) signal_instance_free);
3511 g_source_attach (idle_source, subscriber->context);
3512 g_source_unref (idle_source);
3517 /* called in message handler thread with lock held */
3519 distribute_signals (GDBusConnection *connection,
3520 GDBusMessage *message)
3522 GPtrArray *signal_data_array;
3523 const gchar *sender;
3525 sender = g_dbus_message_get_sender (message);
3527 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3529 _g_dbus_debug_print_lock ();
3530 g_print ("========================================================================\n"
3531 "GDBus-debug:Signal:\n"
3532 " <<<< RECEIVED SIGNAL %s.%s\n"
3534 " sent by name %s\n",
3535 g_dbus_message_get_interface (message),
3536 g_dbus_message_get_member (message),
3537 g_dbus_message_get_path (message),
3538 sender != NULL ? sender : "(none)");
3539 _g_dbus_debug_print_unlock ();
3542 /* collect subscribers that match on sender */
3545 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3546 if (signal_data_array != NULL)
3547 schedule_callbacks (connection, signal_data_array, message, sender);
3550 /* collect subscribers not matching on sender */
3551 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3552 if (signal_data_array != NULL)
3553 schedule_callbacks (connection, signal_data_array, message, sender);
3556 /* ---------------------------------------------------------------------------------------------------- */
3558 /* only called from finalize(), removes all subscriptions */
3560 purge_all_signal_subscriptions (GDBusConnection *connection)
3562 GHashTableIter iter;
3565 GArray *subscribers;
3568 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3569 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3570 while (g_hash_table_iter_next (&iter, &key, NULL))
3572 guint subscription_id = GPOINTER_TO_UINT (key);
3573 g_array_append_val (ids, subscription_id);
3576 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3577 for (n = 0; n < ids->len; n++)
3579 guint subscription_id = g_array_index (ids, guint, n);
3580 unsubscribe_id_internal (connection,
3584 g_array_free (ids, TRUE);
3586 /* call GDestroyNotify without lock held */
3587 for (n = 0; n < subscribers->len; n++)
3589 SignalSubscriber *subscriber;
3590 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3591 call_destroy_notify (subscriber->context,
3592 subscriber->user_data_free_func,
3593 subscriber->user_data);
3594 if (subscriber->context != NULL)
3595 g_main_context_unref (subscriber->context);
3598 g_array_free (subscribers, TRUE);
3601 /* ---------------------------------------------------------------------------------------------------- */
3603 static GDBusInterfaceVTable *
3604 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3606 /* Don't waste memory by copying padding - remember to update this
3607 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3609 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3613 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3618 /* ---------------------------------------------------------------------------------------------------- */
3620 static GDBusSubtreeVTable *
3621 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3623 /* Don't waste memory by copying padding - remember to update this
3624 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3626 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3630 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3635 /* ---------------------------------------------------------------------------------------------------- */
3637 struct ExportedObject
3640 GDBusConnection *connection;
3642 /* maps gchar* -> ExportedInterface* */
3643 GHashTable *map_if_name_to_ei;
3646 /* only called with lock held */
3648 exported_object_free (ExportedObject *eo)
3650 g_free (eo->object_path);
3651 g_hash_table_unref (eo->map_if_name_to_ei);
3660 gchar *interface_name;
3661 GDBusInterfaceVTable *vtable;
3662 GDBusInterfaceInfo *interface_info;
3664 GMainContext *context;
3666 GDestroyNotify user_data_free_func;
3667 } ExportedInterface;
3669 /* called with lock held */
3671 exported_interface_free (ExportedInterface *ei)
3673 g_dbus_interface_info_cache_release (ei->interface_info);
3674 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3676 call_destroy_notify (ei->context,
3677 ei->user_data_free_func,
3680 if (ei->context != NULL)
3681 g_main_context_unref (ei->context);
3683 g_free (ei->interface_name);
3684 _g_dbus_interface_vtable_free (ei->vtable);
3688 /* ---------------------------------------------------------------------------------------------------- */
3690 /* Convenience function to check if @registration_id (if not zero) or
3691 * @subtree_registration_id (if not zero) has been unregistered. If
3692 * so, returns %TRUE.
3694 * Caller must *not* hold lock.
3697 has_object_been_unregistered (GDBusConnection *connection,
3698 guint registration_id,
3699 guint subtree_registration_id)
3703 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3707 CONNECTION_LOCK (connection);
3708 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3709 GUINT_TO_POINTER (registration_id)) == NULL)
3713 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3714 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3718 CONNECTION_UNLOCK (connection);
3723 /* ---------------------------------------------------------------------------------------------------- */
3727 GDBusConnection *connection;
3728 GDBusMessage *message;
3730 const gchar *property_name;
3731 const GDBusInterfaceVTable *vtable;
3732 GDBusInterfaceInfo *interface_info;
3733 const GDBusPropertyInfo *property_info;
3734 guint registration_id;
3735 guint subtree_registration_id;
3739 property_data_free (PropertyData *data)
3741 g_object_unref (data->connection);
3742 g_object_unref (data->message);
3746 /* called in thread where object was registered - no locks held */
3748 invoke_get_property_in_idle_cb (gpointer _data)
3750 PropertyData *data = _data;
3753 GDBusMessage *reply;
3755 if (has_object_been_unregistered (data->connection,
3756 data->registration_id,
3757 data->subtree_registration_id))
3759 reply = g_dbus_message_new_method_error (data->message,
3760 "org.freedesktop.DBus.Error.UnknownMethod",
3761 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3762 g_dbus_message_get_path (data->message));
3763 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3764 g_object_unref (reply);
3769 value = data->vtable->get_property (data->connection,
3770 g_dbus_message_get_sender (data->message),
3771 g_dbus_message_get_path (data->message),
3772 data->interface_info->name,
3773 data->property_name,
3780 g_assert_no_error (error);
3782 if (g_variant_is_floating (value))
3783 g_variant_ref_sink (value);
3784 reply = g_dbus_message_new_method_reply (data->message);
3785 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3786 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3787 g_variant_unref (value);
3788 g_object_unref (reply);
3792 gchar *dbus_error_name;
3793 g_assert (error != NULL);
3794 dbus_error_name = g_dbus_error_encode_gerror (error);
3795 reply = g_dbus_message_new_method_error_literal (data->message,
3798 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3799 g_free (dbus_error_name);
3800 g_error_free (error);
3801 g_object_unref (reply);
3808 /* called in thread where object was registered - no locks held */
3810 invoke_set_property_in_idle_cb (gpointer _data)
3812 PropertyData *data = _data;
3814 GDBusMessage *reply;
3820 g_variant_get (g_dbus_message_get_body (data->message),
3826 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3827 * of the given value is wrong
3829 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3831 reply = g_dbus_message_new_method_error (data->message,
3832 "org.freedesktop.DBus.Error.InvalidArgs",
3833 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3834 data->property_info->name,
3835 data->property_info->signature,
3836 g_variant_get_type_string (value));
3840 if (!data->vtable->set_property (data->connection,
3841 g_dbus_message_get_sender (data->message),
3842 g_dbus_message_get_path (data->message),
3843 data->interface_info->name,
3844 data->property_name,
3849 gchar *dbus_error_name;
3850 g_assert (error != NULL);
3851 dbus_error_name = g_dbus_error_encode_gerror (error);
3852 reply = g_dbus_message_new_method_error_literal (data->message,
3855 g_free (dbus_error_name);
3856 g_error_free (error);
3860 reply = g_dbus_message_new_method_reply (data->message);
3864 g_assert (reply != NULL);
3865 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3866 g_object_unref (reply);
3867 g_variant_unref (value);
3872 /* called with lock held */
3874 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3875 GDBusMessage *message,
3876 guint registration_id,
3877 guint subtree_registration_id,
3879 GDBusInterfaceInfo *interface_info,
3880 const GDBusInterfaceVTable *vtable,
3881 GMainContext *main_context,
3885 const char *interface_name;
3886 const char *property_name;
3887 const GDBusPropertyInfo *property_info;
3888 GSource *idle_source;
3889 PropertyData *property_data;
3890 GDBusMessage *reply;
3895 g_variant_get (g_dbus_message_get_body (message),
3900 g_variant_get (g_dbus_message_get_body (message),
3909 if (vtable == NULL || vtable->get_property == NULL)
3914 if (vtable == NULL || vtable->set_property == NULL)
3918 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3920 property_info = NULL;
3922 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3923 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3924 if (property_info == NULL)
3926 reply = g_dbus_message_new_method_error (message,
3927 "org.freedesktop.DBus.Error.InvalidArgs",
3928 _("No such property `%s'"),
3930 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3931 g_object_unref (reply);
3936 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3938 reply = g_dbus_message_new_method_error (message,
3939 "org.freedesktop.DBus.Error.InvalidArgs",
3940 _("Property `%s' is not readable"),
3942 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3943 g_object_unref (reply);
3947 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3949 reply = g_dbus_message_new_method_error (message,
3950 "org.freedesktop.DBus.Error.InvalidArgs",
3951 _("Property `%s' is not writable"),
3953 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3954 g_object_unref (reply);
3959 /* ok, got the property info - call user code in an idle handler */
3960 property_data = g_new0 (PropertyData, 1);
3961 property_data->connection = g_object_ref (connection);
3962 property_data->message = g_object_ref (message);
3963 property_data->user_data = user_data;
3964 property_data->property_name = property_name;
3965 property_data->vtable = vtable;
3966 property_data->interface_info = interface_info;
3967 property_data->property_info = property_info;
3968 property_data->registration_id = registration_id;
3969 property_data->subtree_registration_id = subtree_registration_id;
3971 idle_source = g_idle_source_new ();
3972 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3973 g_source_set_callback (idle_source,
3974 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3976 (GDestroyNotify) property_data_free);
3977 g_source_attach (idle_source, main_context);
3978 g_source_unref (idle_source);
3986 /* called with lock held */
3988 handle_getset_property (GDBusConnection *connection,
3990 GDBusMessage *message,
3993 ExportedInterface *ei;
3995 const char *interface_name;
3996 const char *property_name;
4001 g_variant_get (g_dbus_message_get_body (message),
4006 g_variant_get (g_dbus_message_get_body (message),
4012 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4013 * no such interface registered
4015 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4018 GDBusMessage *reply;
4019 reply = g_dbus_message_new_method_error (message,
4020 "org.freedesktop.DBus.Error.InvalidArgs",
4021 _("No such interface `%s'"),
4023 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4024 g_object_unref (reply);
4029 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4042 /* ---------------------------------------------------------------------------------------------------- */
4046 GDBusConnection *connection;
4047 GDBusMessage *message;
4049 const GDBusInterfaceVTable *vtable;
4050 GDBusInterfaceInfo *interface_info;
4051 guint registration_id;
4052 guint subtree_registration_id;
4053 } PropertyGetAllData;
4056 property_get_all_data_free (PropertyData *data)
4058 g_object_unref (data->connection);
4059 g_object_unref (data->message);
4063 /* called in thread where object was registered - no locks held */
4065 invoke_get_all_properties_in_idle_cb (gpointer _data)
4067 PropertyGetAllData *data = _data;
4068 GVariantBuilder builder;
4069 GDBusMessage *reply;
4072 if (has_object_been_unregistered (data->connection,
4073 data->registration_id,
4074 data->subtree_registration_id))
4076 reply = g_dbus_message_new_method_error (data->message,
4077 "org.freedesktop.DBus.Error.UnknownMethod",
4078 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4079 g_dbus_message_get_path (data->message));
4080 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4081 g_object_unref (reply);
4085 /* TODO: Right now we never fail this call - we just omit values if
4086 * a get_property() call is failing.
4088 * We could fail the whole call if just a single get_property() call
4089 * returns an error. We need clarification in the D-Bus spec about this.
4091 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4092 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4093 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4095 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4098 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4101 value = data->vtable->get_property (data->connection,
4102 g_dbus_message_get_sender (data->message),
4103 g_dbus_message_get_path (data->message),
4104 data->interface_info->name,
4105 property_info->name,
4112 if (g_variant_is_floating (value))
4113 g_variant_ref_sink (value);
4114 g_variant_builder_add (&builder,
4116 property_info->name,
4118 g_variant_unref (value);
4120 g_variant_builder_close (&builder);
4122 reply = g_dbus_message_new_method_reply (data->message);
4123 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4124 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4125 g_object_unref (reply);
4131 /* called with lock held */
4133 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4134 GDBusMessage *message,
4135 guint registration_id,
4136 guint subtree_registration_id,
4137 GDBusInterfaceInfo *interface_info,
4138 const GDBusInterfaceVTable *vtable,
4139 GMainContext *main_context,
4143 const char *interface_name;
4144 GSource *idle_source;
4145 PropertyGetAllData *property_get_all_data;
4149 g_variant_get (g_dbus_message_get_body (message),
4153 if (vtable == NULL || vtable->get_property == NULL)
4156 /* ok, got the property info - call user in an idle handler */
4157 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4158 property_get_all_data->connection = g_object_ref (connection);
4159 property_get_all_data->message = g_object_ref (message);
4160 property_get_all_data->user_data = user_data;
4161 property_get_all_data->vtable = vtable;
4162 property_get_all_data->interface_info = interface_info;
4163 property_get_all_data->registration_id = registration_id;
4164 property_get_all_data->subtree_registration_id = subtree_registration_id;
4166 idle_source = g_idle_source_new ();
4167 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4168 g_source_set_callback (idle_source,
4169 invoke_get_all_properties_in_idle_cb,
4170 property_get_all_data,
4171 (GDestroyNotify) property_get_all_data_free);
4172 g_source_attach (idle_source, main_context);
4173 g_source_unref (idle_source);
4181 /* called with lock held */
4183 handle_get_all_properties (GDBusConnection *connection,
4185 GDBusMessage *message)
4187 ExportedInterface *ei;
4189 const char *interface_name;
4193 g_variant_get (g_dbus_message_get_body (message),
4197 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4198 * no such interface registered
4200 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4203 GDBusMessage *reply;
4204 reply = g_dbus_message_new_method_error (message,
4205 "org.freedesktop.DBus.Error.InvalidArgs",
4206 _("No such interface"),
4208 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4209 g_object_unref (reply);
4214 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4226 /* ---------------------------------------------------------------------------------------------------- */
4228 static const gchar introspect_header[] =
4229 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4230 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4231 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4234 static const gchar introspect_tail[] =
4237 static const gchar introspect_properties_interface[] =
4238 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4239 " <method name=\"Get\">\n"
4240 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4241 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4242 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4244 " <method name=\"GetAll\">\n"
4245 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4246 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4248 " <method name=\"Set\">\n"
4249 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4250 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4251 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4253 " <signal name=\"PropertiesChanged\">\n"
4254 " <arg type=\"s\" name=\"interface_name\"/>\n"
4255 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4256 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4260 static const gchar introspect_introspectable_interface[] =
4261 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4262 " <method name=\"Introspect\">\n"
4263 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4266 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4267 " <method name=\"Ping\"/>\n"
4268 " <method name=\"GetMachineId\">\n"
4269 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4274 introspect_append_header (GString *s)
4276 g_string_append (s, introspect_header);
4280 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4282 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4288 begin = object_path + path_len;
4289 end = strchr (begin, '/');
4291 s = g_strndup (begin, end - begin);
4293 s = g_strdup (begin);
4295 if (g_hash_table_lookup (set, s) == NULL)
4296 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4302 /* TODO: we want a nicer public interface for this */
4304 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4309 GHashTableIter hash_iter;
4310 const gchar *object_path;
4316 CONNECTION_ENSURE_LOCK (connection);
4318 path_len = strlen (path);
4322 set = g_hash_table_new (g_str_hash, g_str_equal);
4324 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4325 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4326 maybe_add_path (path, path_len, object_path, set);
4328 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4329 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4330 maybe_add_path (path, path_len, object_path, set);
4332 p = g_ptr_array_new ();
4333 keys = g_hash_table_get_keys (set);
4334 for (l = keys; l != NULL; l = l->next)
4335 g_ptr_array_add (p, l->data);
4336 g_hash_table_unref (set);
4339 g_ptr_array_add (p, NULL);
4340 ret = (gchar **) g_ptr_array_free (p, FALSE);
4345 g_dbus_connection_list_registered (GDBusConnection *connection,
4349 CONNECTION_LOCK (connection);
4350 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4351 CONNECTION_UNLOCK (connection);
4355 /* called in message handler thread with lock held */
4357 handle_introspect (GDBusConnection *connection,
4359 GDBusMessage *message)
4363 GDBusMessage *reply;
4364 GHashTableIter hash_iter;
4365 ExportedInterface *ei;
4368 /* first the header with the standard interfaces */
4369 s = g_string_sized_new (sizeof (introspect_header) +
4370 sizeof (introspect_properties_interface) +
4371 sizeof (introspect_introspectable_interface) +
4372 sizeof (introspect_tail));
4373 introspect_append_header (s);
4374 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4375 "org.freedesktop.DBus.Properties"))
4376 g_string_append (s, introspect_properties_interface);
4378 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4379 "org.freedesktop.DBus.Introspectable"))
4380 g_string_append (s, introspect_introspectable_interface);
4382 /* then include the registered interfaces */
4383 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4384 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4385 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4387 /* finally include nodes registered below us */
4388 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4389 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4390 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4391 g_strfreev (registered);
4392 g_string_append (s, introspect_tail);
4394 reply = g_dbus_message_new_method_reply (message);
4395 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4396 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4397 g_object_unref (reply);
4398 g_string_free (s, TRUE);
4403 /* called in thread where object was registered - no locks held */
4405 call_in_idle_cb (gpointer user_data)
4407 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4408 GDBusInterfaceVTable *vtable;
4409 guint registration_id;
4410 guint subtree_registration_id;
4412 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4413 g_assert (vtable != NULL && vtable->method_call != NULL);
4415 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4416 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4418 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4420 subtree_registration_id))
4422 GDBusMessage *reply;
4423 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4424 "org.freedesktop.DBus.Error.UnknownMethod",
4425 _("No such interface `%s' on object at path %s"),
4426 g_dbus_method_invocation_get_interface_name (invocation),
4427 g_dbus_method_invocation_get_object_path (invocation));
4428 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4429 g_object_unref (reply);
4433 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4434 g_dbus_method_invocation_get_sender (invocation),
4435 g_dbus_method_invocation_get_object_path (invocation),
4436 g_dbus_method_invocation_get_interface_name (invocation),
4437 g_dbus_method_invocation_get_method_name (invocation),
4438 g_dbus_method_invocation_get_parameters (invocation),
4439 g_object_ref (invocation),
4440 g_dbus_method_invocation_get_user_data (invocation));
4446 /* called in message handler thread with lock held */
4448 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4449 GDBusMessage *message,
4450 guint registration_id,
4451 guint subtree_registration_id,
4452 GDBusInterfaceInfo *interface_info,
4453 const GDBusInterfaceVTable *vtable,
4454 GMainContext *main_context,
4457 GDBusMethodInvocation *invocation;
4458 const GDBusMethodInfo *method_info;
4459 GDBusMessage *reply;
4460 GVariant *parameters;
4461 GSource *idle_source;
4463 GVariantType *in_type;
4467 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4468 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4470 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4471 * error to the caller
4473 if (method_info == NULL)
4475 reply = g_dbus_message_new_method_error (message,
4476 "org.freedesktop.DBus.Error.UnknownMethod",
4477 _("No such method `%s'"),
4478 g_dbus_message_get_member (message));
4479 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4480 g_object_unref (reply);
4485 parameters = g_dbus_message_get_body (message);
4486 if (parameters == NULL)
4488 parameters = g_variant_new ("()");
4489 g_variant_ref_sink (parameters);
4493 g_variant_ref (parameters);
4496 /* Check that the incoming args are of the right type - if they are not, return
4497 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4499 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4500 if (!g_variant_is_of_type (parameters, in_type))
4504 type_string = g_variant_type_dup_string (in_type);
4506 reply = g_dbus_message_new_method_error (message,
4507 "org.freedesktop.DBus.Error.InvalidArgs",
4508 _("Type of message, `%s', does not match expected type `%s'"),
4509 g_variant_get_type_string (parameters),
4511 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4512 g_variant_type_free (in_type);
4513 g_variant_unref (parameters);
4514 g_object_unref (reply);
4515 g_free (type_string);
4519 g_variant_type_free (in_type);
4521 /* schedule the call in idle */
4522 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4523 g_dbus_message_get_path (message),
4524 g_dbus_message_get_interface (message),
4525 g_dbus_message_get_member (message),
4531 g_variant_unref (parameters);
4533 /* TODO: would be nicer with a real MethodData like we already
4534 * have PropertyData and PropertyGetAllData... */
4535 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4536 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4537 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4539 idle_source = g_idle_source_new ();
4540 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4541 g_source_set_callback (idle_source,
4545 g_source_attach (idle_source, main_context);
4546 g_source_unref (idle_source);
4554 /* ---------------------------------------------------------------------------------------------------- */
4556 /* called in message handler thread with lock held */
4558 obj_message_func (GDBusConnection *connection,
4560 GDBusMessage *message)
4562 const gchar *interface_name;
4563 const gchar *member;
4564 const gchar *signature;
4569 interface_name = g_dbus_message_get_interface (message);
4570 member = g_dbus_message_get_member (message);
4571 signature = g_dbus_message_get_signature (message);
4573 /* see if we have an interface for handling this call */
4574 if (interface_name != NULL)
4576 ExportedInterface *ei;
4577 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4580 /* we do - invoke the handler in idle in the right thread */
4582 /* handle no vtable or handler being present */
4583 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4586 handled = validate_and_maybe_schedule_method_call (connection,
4598 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4599 g_strcmp0 (member, "Introspect") == 0 &&
4600 g_strcmp0 (signature, "") == 0)
4602 handled = handle_introspect (connection, eo, message);
4605 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4606 g_strcmp0 (member, "Get") == 0 &&
4607 g_strcmp0 (signature, "ss") == 0)
4609 handled = handle_getset_property (connection, eo, message, TRUE);
4612 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4613 g_strcmp0 (member, "Set") == 0 &&
4614 g_strcmp0 (signature, "ssv") == 0)
4616 handled = handle_getset_property (connection, eo, message, FALSE);
4619 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4620 g_strcmp0 (member, "GetAll") == 0 &&
4621 g_strcmp0 (signature, "s") == 0)
4623 handled = handle_get_all_properties (connection, eo, message);
4632 * g_dbus_connection_register_object:
4633 * @connection: A #GDBusConnection.
4634 * @object_path: The object path to register at.
4635 * @interface_info: Introspection data for the interface.
4636 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4637 * @user_data: Data to pass to functions in @vtable.
4638 * @user_data_free_func: Function to call when the object path is unregistered.
4639 * @error: Return location for error or %NULL.
4641 * Registers callbacks for exported objects at @object_path with the
4642 * D-Bus interface that is described in @interface_info.
4644 * Calls to functions in @vtable (and @user_data_free_func) will
4645 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4646 * loop</link> of the thread you are calling this method from.
4648 * Note that all #GVariant values passed to functions in @vtable will match
4649 * the signature given in @interface_info - if a remote caller passes
4650 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4651 * is returned to the remote caller.
4653 * Additionally, if the remote caller attempts to invoke methods or
4654 * access properties not mentioned in @interface_info the
4655 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4656 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4657 * are returned to the caller.
4659 * It is considered a programming error if the
4660 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4661 * #GVariant of incorrect type.
4663 * If an existing callback is already registered at @object_path and
4664 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4666 * GDBus automatically implements the standard D-Bus interfaces
4667 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4668 * and org.freedesktop.Peer, so you don't have to implement those for
4669 * the objects you export. You <emphasis>can</emphasis> implement
4670 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4671 * and setting of properties asynchronously.
4673 * Note that the reference count on @interface_info will be
4674 * incremented by 1 (unless allocated statically, e.g. if the
4675 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4676 * as the object is exported. Also note that @vtable will be copied.
4678 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4680 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4681 * that can be used with g_dbus_connection_unregister_object() .
4686 g_dbus_connection_register_object (GDBusConnection *connection,
4687 const gchar *object_path,
4688 GDBusInterfaceInfo *interface_info,
4689 const GDBusInterfaceVTable *vtable,
4691 GDestroyNotify user_data_free_func,
4695 ExportedInterface *ei;
4698 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4699 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4700 g_return_val_if_fail (interface_info != NULL, 0);
4701 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4702 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4706 CONNECTION_LOCK (connection);
4708 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4711 eo = g_new0 (ExportedObject, 1);
4712 eo->object_path = g_strdup (object_path);
4713 eo->connection = connection;
4714 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4717 (GDestroyNotify) exported_interface_free);
4718 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4721 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4727 _("An object is already exported for the interface %s at %s"),
4728 interface_info->name,
4733 ei = g_new0 (ExportedInterface, 1);
4734 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4736 ei->user_data = user_data;
4737 ei->user_data_free_func = user_data_free_func;
4738 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4739 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4740 g_dbus_interface_info_cache_build (ei->interface_info);
4741 ei->interface_name = g_strdup (interface_info->name);
4742 ei->context = g_main_context_get_thread_default ();
4743 if (ei->context != NULL)
4744 g_main_context_ref (ei->context);
4746 g_hash_table_insert (eo->map_if_name_to_ei,
4747 (gpointer) ei->interface_name,
4749 g_hash_table_insert (connection->map_id_to_ei,
4750 GUINT_TO_POINTER (ei->id),
4756 CONNECTION_UNLOCK (connection);
4762 * g_dbus_connection_unregister_object:
4763 * @connection: A #GDBusConnection.
4764 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4766 * Unregisters an object.
4768 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4773 g_dbus_connection_unregister_object (GDBusConnection *connection,
4774 guint registration_id)
4776 ExportedInterface *ei;
4780 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4784 CONNECTION_LOCK (connection);
4786 ei = g_hash_table_lookup (connection->map_id_to_ei,
4787 GUINT_TO_POINTER (registration_id));
4793 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4794 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4795 /* unregister object path if we have no more exported interfaces */
4796 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4797 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4803 CONNECTION_UNLOCK (connection);
4808 /* ---------------------------------------------------------------------------------------------------- */
4811 * g_dbus_connection_emit_signal:
4812 * @connection: A #GDBusConnection.
4813 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4814 * @object_path: Path of remote object.
4815 * @interface_name: D-Bus interface to emit a signal on.
4816 * @signal_name: The name of the signal to emit.
4817 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4818 * @error: Return location for error or %NULL.
4822 * If the parameters GVariant is floating, it is consumed.
4824 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4826 * Returns: %TRUE unless @error is set.
4831 g_dbus_connection_emit_signal (GDBusConnection *connection,
4832 const gchar *destination_bus_name,
4833 const gchar *object_path,
4834 const gchar *interface_name,
4835 const gchar *signal_name,
4836 GVariant *parameters,
4839 GDBusMessage *message;
4845 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4846 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4847 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4848 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4849 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4850 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4852 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4854 _g_dbus_debug_print_lock ();
4855 g_print ("========================================================================\n"
4856 "GDBus-debug:Emission:\n"
4857 " >>>> SIGNAL EMISSION %s.%s()\n"
4859 " destination %s\n",
4860 interface_name, signal_name,
4862 destination_bus_name != NULL ? destination_bus_name : "(none)");
4863 _g_dbus_debug_print_unlock ();
4866 message = g_dbus_message_new_signal (object_path,
4870 if (destination_bus_name != NULL)
4871 g_dbus_message_set_header (message,
4872 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4873 g_variant_new_string (destination_bus_name));
4875 if (parameters != NULL)
4876 g_dbus_message_set_body (message, parameters);
4878 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4879 g_object_unref (message);
4885 add_call_flags (GDBusMessage *message,
4886 GDBusCallFlags flags)
4888 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4889 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4893 decode_method_reply (GDBusMessage *reply,
4894 const gchar *method_name,
4895 const GVariantType *reply_type,
4901 switch (g_dbus_message_get_message_type (reply))
4903 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4904 result = g_dbus_message_get_body (reply);
4907 result = g_variant_new ("()");
4908 g_variant_ref_sink (result);
4912 g_variant_ref (result);
4915 if (!g_variant_is_of_type (result, reply_type))
4917 gchar *type_string = g_variant_type_dup_string (reply_type);
4921 G_IO_ERROR_INVALID_ARGUMENT,
4922 _("Method `%s' returned type `%s', but expected `%s'"),
4923 method_name, g_variant_get_type_string (result), type_string);
4925 g_variant_unref (result);
4926 g_free (type_string);
4931 case G_DBUS_MESSAGE_TYPE_ERROR:
4932 g_dbus_message_to_gerror (reply, error);
4936 g_assert_not_reached ();
4946 GSimpleAsyncResult *simple;
4947 GVariantType *reply_type;
4948 gchar *method_name; /* for error message */
4953 g_dbus_connection_call_done (GObject *source,
4954 GAsyncResult *result,
4957 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4958 CallState *state = user_data;
4960 GDBusMessage *reply;
4964 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4968 if (G_UNLIKELY (_g_dbus_debug_call ()))
4970 _g_dbus_debug_print_lock ();
4971 g_print ("========================================================================\n"
4972 "GDBus-debug:Call:\n"
4973 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4979 g_print ("SUCCESS\n");
4983 g_print ("FAILED: %s\n",
4986 _g_dbus_debug_print_unlock ();
4992 value = decode_method_reply (reply, state->method_name,
4993 state->reply_type, &error);
4994 g_object_unref (reply);
5000 g_simple_async_result_take_error (state->simple, error);
5002 g_simple_async_result_set_op_res_gpointer (state->simple, value,
5003 (GDestroyNotify) g_variant_unref);
5005 g_simple_async_result_complete (state->simple);
5006 g_variant_type_free (state->reply_type);
5007 g_object_unref (state->simple);
5008 g_free (state->method_name);
5010 g_slice_free (CallState, state);
5014 * g_dbus_connection_call:
5015 * @connection: A #GDBusConnection.
5016 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
5017 * @object_path: Path of remote object.
5018 * @interface_name: D-Bus interface to invoke method on.
5019 * @method_name: The name of the method to invoke.
5020 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5021 * @reply_type: The expected type of the reply, or %NULL.
5022 * @flags: Flags from the #GDBusCallFlags enumeration.
5023 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5024 * timeout or %G_MAXINT for no timeout.
5025 * @cancellable: A #GCancellable or %NULL.
5026 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
5027 * care about the result of the method invocation.
5028 * @user_data: The data to pass to @callback.
5030 * Asynchronously invokes the @method_name method on the
5031 * @interface_name D-Bus interface on the remote object at
5032 * @object_path owned by @bus_name.
5034 * If @connection is closed then the operation will fail with
5035 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5036 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5037 * not compatible with the D-Bus protocol, the operation fails with
5038 * %G_IO_ERROR_INVALID_ARGUMENT.
5040 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5041 * error will be raised if it does not match. Said another way, if you give a @reply_type
5042 * then any non-%NULL return value will be of this type.
5044 * If the @parameters #GVariant is floating, it is consumed. This allows
5045 * convenient 'inline' use of g_variant_new(), e.g.:
5047 * g_dbus_connection_call (connection,
5048 * "org.freedesktop.StringThings",
5049 * "/org/freedesktop/StringThings",
5050 * "org.freedesktop.StringThings",
5052 * g_variant_new ("(ss)",
5056 * G_DBUS_CALL_FLAGS_NONE,
5059 * (GAsyncReadyCallback) two_strings_done,
5063 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5064 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5065 * of the thread you are calling this method from. You can then call
5066 * g_dbus_connection_call_finish() to get the result of the operation.
5067 * See g_dbus_connection_call_sync() for the synchronous version of this
5073 g_dbus_connection_call (GDBusConnection *connection,
5074 const gchar *bus_name,
5075 const gchar *object_path,
5076 const gchar *interface_name,
5077 const gchar *method_name,
5078 GVariant *parameters,
5079 const GVariantType *reply_type,
5080 GDBusCallFlags flags,
5082 GCancellable *cancellable,
5083 GAsyncReadyCallback callback,
5086 GDBusMessage *message;
5089 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5090 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5091 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5092 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5093 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5094 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5095 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5097 state = g_slice_new (CallState);
5098 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5099 callback, user_data,
5100 g_dbus_connection_call);
5101 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5103 if (reply_type == NULL)
5104 reply_type = G_VARIANT_TYPE_ANY;
5106 state->reply_type = g_variant_type_copy (reply_type);
5108 message = g_dbus_message_new_method_call (bus_name,
5112 add_call_flags (message, flags);
5113 if (parameters != NULL)
5114 g_dbus_message_set_body (message, parameters);
5116 g_dbus_connection_send_message_with_reply (connection,
5118 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5122 g_dbus_connection_call_done,
5125 if (G_UNLIKELY (_g_dbus_debug_call ()))
5127 _g_dbus_debug_print_lock ();
5128 g_print ("========================================================================\n"
5129 "GDBus-debug:Call:\n"
5130 " >>>> ASYNC %s.%s()\n"
5132 " owned by name %s (serial %d)\n",
5136 bus_name != NULL ? bus_name : "(none)",
5138 _g_dbus_debug_print_unlock ();
5141 if (message != NULL)
5142 g_object_unref (message);
5146 * g_dbus_connection_call_finish:
5147 * @connection: A #GDBusConnection.
5148 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5149 * @error: Return location for error or %NULL.
5151 * Finishes an operation started with g_dbus_connection_call().
5153 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5154 * return values. Free with g_variant_unref().
5159 g_dbus_connection_call_finish (GDBusConnection *connection,
5163 GSimpleAsyncResult *simple;
5165 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5166 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5167 g_dbus_connection_call), NULL);
5168 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5170 simple = G_SIMPLE_ASYNC_RESULT (res);
5172 if (g_simple_async_result_propagate_error (simple, error))
5175 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
5178 /* ---------------------------------------------------------------------------------------------------- */
5181 * g_dbus_connection_call_sync:
5182 * @connection: A #GDBusConnection.
5183 * @bus_name: A unique or well-known bus name.
5184 * @object_path: Path of remote object.
5185 * @interface_name: D-Bus interface to invoke method on.
5186 * @method_name: The name of the method to invoke.
5187 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5188 * @reply_type: The expected type of the reply, or %NULL.
5189 * @flags: Flags from the #GDBusCallFlags enumeration.
5190 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5191 * timeout or %G_MAXINT for no timeout.
5192 * @cancellable: A #GCancellable or %NULL.
5193 * @error: Return location for error or %NULL.
5195 * Synchronously invokes the @method_name method on the
5196 * @interface_name D-Bus interface on the remote object at
5197 * @object_path owned by @bus_name.
5199 * If @connection is closed then the operation will fail with
5200 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5201 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5202 * contains a value not compatible with the D-Bus protocol, the operation
5203 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5205 * If @reply_type is non-%NULL then the reply will be checked for having
5206 * this type and an error will be raised if it does not match. Said
5207 * another way, if you give a @reply_type then any non-%NULL return
5208 * value will be of this type.
5210 * If the @parameters #GVariant is floating, it is consumed.
5211 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5213 * g_dbus_connection_call_sync (connection,
5214 * "org.freedesktop.StringThings",
5215 * "/org/freedesktop/StringThings",
5216 * "org.freedesktop.StringThings",
5218 * g_variant_new ("(ss)",
5222 * G_DBUS_CALL_FLAGS_NONE,
5228 * The calling thread is blocked until a reply is received. See
5229 * g_dbus_connection_call() for the asynchronous version of
5232 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5233 * return values. Free with g_variant_unref().
5238 g_dbus_connection_call_sync (GDBusConnection *connection,
5239 const gchar *bus_name,
5240 const gchar *object_path,
5241 const gchar *interface_name,
5242 const gchar *method_name,
5243 GVariant *parameters,
5244 const GVariantType *reply_type,
5245 GDBusCallFlags flags,
5247 GCancellable *cancellable,
5250 GDBusMessage *message;
5251 GDBusMessage *reply;
5253 GError *local_error;
5259 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5260 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5261 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5262 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5263 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5264 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5265 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5267 if (reply_type == NULL)
5268 reply_type = G_VARIANT_TYPE_ANY;
5270 message = g_dbus_message_new_method_call (bus_name,
5274 add_call_flags (message, flags);
5275 if (parameters != NULL)
5276 g_dbus_message_set_body (message, parameters);
5278 if (G_UNLIKELY (_g_dbus_debug_call ()))
5280 _g_dbus_debug_print_lock ();
5281 g_print ("========================================================================\n"
5282 "GDBus-debug:Call:\n"
5283 " >>>> SYNC %s.%s()\n"
5285 " owned by name %s\n",
5289 bus_name != NULL ? bus_name : "(none)");
5290 _g_dbus_debug_print_unlock ();
5294 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5296 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5298 NULL, /* volatile guint32 *out_serial */
5302 if (G_UNLIKELY (_g_dbus_debug_call ()))
5304 _g_dbus_debug_print_lock ();
5305 g_print ("========================================================================\n"
5306 "GDBus-debug:Call:\n"
5307 " <<<< SYNC COMPLETE %s.%s()\n"
5313 g_print ("SUCCESS\n");
5317 g_print ("FAILED: %s\n",
5318 local_error->message);
5320 _g_dbus_debug_print_unlock ();
5326 *error = local_error;
5328 g_error_free (local_error);
5332 result = decode_method_reply (reply, method_name, reply_type, error);
5335 if (message != NULL)
5336 g_object_unref (message);
5338 g_object_unref (reply);
5343 /* ---------------------------------------------------------------------------------------------------- */
5345 struct ExportedSubtree
5349 GDBusConnection *connection;
5350 GDBusSubtreeVTable *vtable;
5351 GDBusSubtreeFlags flags;
5353 GMainContext *context;
5355 GDestroyNotify user_data_free_func;
5359 exported_subtree_free (ExportedSubtree *es)
5361 call_destroy_notify (es->context,
5362 es->user_data_free_func,
5365 if (es->context != NULL)
5366 g_main_context_unref (es->context);
5368 _g_dbus_subtree_vtable_free (es->vtable);
5369 g_free (es->object_path);
5373 /* called without lock held */
5375 handle_subtree_introspect (GDBusConnection *connection,
5376 ExportedSubtree *es,
5377 GDBusMessage *message)
5381 GDBusMessage *reply;
5384 const gchar *sender;
5385 const gchar *requested_object_path;
5386 const gchar *requested_node;
5387 GDBusInterfaceInfo **interfaces;
5389 gchar **subnode_paths;
5390 gboolean has_properties_interface;
5391 gboolean has_introspectable_interface;
5395 requested_object_path = g_dbus_message_get_path (message);
5396 sender = g_dbus_message_get_sender (message);
5397 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5399 s = g_string_new (NULL);
5400 introspect_append_header (s);
5402 /* Strictly we don't need the children in dynamic mode, but we avoid the
5403 * conditionals to preserve code clarity
5405 children = es->vtable->enumerate (es->connection,
5412 requested_node = strrchr (requested_object_path, '/') + 1;
5414 /* Assert existence of object if we are not dynamic */
5415 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5416 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5421 requested_node = NULL;
5424 interfaces = es->vtable->introspect (es->connection,
5429 if (interfaces != NULL)
5431 has_properties_interface = FALSE;
5432 has_introspectable_interface = FALSE;
5434 for (n = 0; interfaces[n] != NULL; n++)
5436 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5437 has_properties_interface = TRUE;
5438 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5439 has_introspectable_interface = TRUE;
5441 if (!has_properties_interface)
5442 g_string_append (s, introspect_properties_interface);
5443 if (!has_introspectable_interface)
5444 g_string_append (s, introspect_introspectable_interface);
5446 for (n = 0; interfaces[n] != NULL; n++)
5448 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5449 g_dbus_interface_info_unref (interfaces[n]);
5451 g_free (interfaces);
5454 /* then include <node> entries from the Subtree for the root */
5457 for (n = 0; children != NULL && children[n] != NULL; n++)
5458 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5461 /* finally include nodes registered below us */
5462 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5463 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5464 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5465 g_strfreev (subnode_paths);
5467 g_string_append (s, "</node>\n");
5469 reply = g_dbus_message_new_method_reply (message);
5470 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5471 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5472 g_object_unref (reply);
5477 g_string_free (s, TRUE);
5478 g_strfreev (children);
5482 /* called without lock held */
5484 handle_subtree_method_invocation (GDBusConnection *connection,
5485 ExportedSubtree *es,
5486 GDBusMessage *message)
5489 const gchar *sender;
5490 const gchar *interface_name;
5491 const gchar *member;
5492 const gchar *signature;
5493 const gchar *requested_object_path;
5494 const gchar *requested_node;
5496 GDBusInterfaceInfo *interface_info;
5497 const GDBusInterfaceVTable *interface_vtable;
5498 gpointer interface_user_data;
5500 GDBusInterfaceInfo **interfaces;
5501 gboolean is_property_get;
5502 gboolean is_property_set;
5503 gboolean is_property_get_all;
5508 requested_object_path = g_dbus_message_get_path (message);
5509 sender = g_dbus_message_get_sender (message);
5510 interface_name = g_dbus_message_get_interface (message);
5511 member = g_dbus_message_get_member (message);
5512 signature = g_dbus_message_get_signature (message);
5513 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5515 is_property_get = FALSE;
5516 is_property_set = FALSE;
5517 is_property_get_all = FALSE;
5518 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5520 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5521 is_property_get = TRUE;
5522 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5523 is_property_set = TRUE;
5524 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5525 is_property_get_all = TRUE;
5530 requested_node = strrchr (requested_object_path, '/') + 1;
5532 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5534 /* We don't want to dispatch to unenumerated
5535 * nodes, so ensure that the child exists.
5540 children = es->vtable->enumerate (es->connection,
5545 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5546 g_strfreev (children);
5554 requested_node = NULL;
5557 /* get introspection data for the node */
5558 interfaces = es->vtable->introspect (es->connection,
5560 requested_object_path,
5564 if (interfaces == NULL)
5567 interface_info = NULL;
5568 for (n = 0; interfaces[n] != NULL; n++)
5570 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5571 interface_info = interfaces[n];
5574 /* dispatch the call if the user wants to handle it */
5575 if (interface_info != NULL)
5577 /* figure out where to dispatch the method call */
5578 interface_user_data = NULL;
5579 interface_vtable = es->vtable->dispatch (es->connection,
5584 &interface_user_data,
5586 if (interface_vtable == NULL)
5589 CONNECTION_LOCK (connection);
5590 handled = validate_and_maybe_schedule_method_call (es->connection,
5597 interface_user_data);
5598 CONNECTION_UNLOCK (connection);
5600 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5601 else if (is_property_get || is_property_set || is_property_get_all)
5603 if (is_property_get)
5604 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5605 else if (is_property_set)
5606 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5607 else if (is_property_get_all)
5608 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5610 g_assert_not_reached ();
5612 /* see if the object supports this interface at all */
5613 for (n = 0; interfaces[n] != NULL; n++)
5615 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5616 interface_info = interfaces[n];
5619 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5620 * claims it won't support the interface
5622 if (interface_info == NULL)
5624 GDBusMessage *reply;
5625 reply = g_dbus_message_new_method_error (message,
5626 "org.freedesktop.DBus.Error.InvalidArgs",
5627 _("No such interface `%s'"),
5629 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5630 g_object_unref (reply);
5635 /* figure out where to dispatch the property get/set/getall calls */
5636 interface_user_data = NULL;
5637 interface_vtable = es->vtable->dispatch (es->connection,
5642 &interface_user_data,
5644 if (interface_vtable == NULL)
5646 g_warning ("The subtree introspection function indicates that '%s' "
5647 "is a valid interface name, but calling the dispatch "
5648 "function on that interface gave us NULL", interface_name);
5652 if (is_property_get || is_property_set)
5654 CONNECTION_LOCK (connection);
5655 handled = validate_and_maybe_schedule_property_getset (es->connection,
5663 interface_user_data);
5664 CONNECTION_UNLOCK (connection);
5666 else if (is_property_get_all)
5668 CONNECTION_LOCK (connection);
5669 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5676 interface_user_data);
5677 CONNECTION_UNLOCK (connection);
5682 if (interfaces != NULL)
5684 for (n = 0; interfaces[n] != NULL; n++)
5685 g_dbus_interface_info_unref (interfaces[n]);
5686 g_free (interfaces);
5694 GDBusMessage *message;
5695 ExportedSubtree *es;
5696 } SubtreeDeferredData;
5699 subtree_deferred_data_free (SubtreeDeferredData *data)
5701 g_object_unref (data->message);
5705 /* called without lock held in the thread where the caller registered the subtree */
5707 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5709 SubtreeDeferredData *data = _data;
5714 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5715 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5716 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5717 handled = handle_subtree_introspect (data->es->connection,
5721 handled = handle_subtree_method_invocation (data->es->connection,
5727 CONNECTION_LOCK (data->es->connection);
5728 handled = handle_generic_unlocked (data->es->connection, data->message);
5729 CONNECTION_UNLOCK (data->es->connection);
5732 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5735 GDBusMessage *reply;
5736 reply = g_dbus_message_new_method_error (data->message,
5737 "org.freedesktop.DBus.Error.UnknownMethod",
5738 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5739 g_dbus_message_get_member (data->message),
5740 g_dbus_message_get_interface (data->message),
5741 g_dbus_message_get_signature (data->message));
5742 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5743 g_object_unref (reply);
5749 /* called in message handler thread with lock held */
5751 subtree_message_func (GDBusConnection *connection,
5752 ExportedSubtree *es,
5753 GDBusMessage *message)
5755 GSource *idle_source;
5756 SubtreeDeferredData *data;
5758 data = g_new0 (SubtreeDeferredData, 1);
5759 data->message = g_object_ref (message);
5762 /* defer this call to an idle handler in the right thread */
5763 idle_source = g_idle_source_new ();
5764 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5765 g_source_set_callback (idle_source,
5766 process_subtree_vtable_message_in_idle_cb,
5768 (GDestroyNotify) subtree_deferred_data_free);
5769 g_source_attach (idle_source, es->context);
5770 g_source_unref (idle_source);
5772 /* since we own the entire subtree, handlers for objects not in the subtree have been
5773 * tried already by libdbus-1 - so we just need to ensure that we're always going
5774 * to reply to the message
5780 * g_dbus_connection_register_subtree:
5781 * @connection: A #GDBusConnection.
5782 * @object_path: The object path to register the subtree at.
5783 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5784 * @flags: Flags used to fine tune the behavior of the subtree.
5785 * @user_data: Data to pass to functions in @vtable.
5786 * @user_data_free_func: Function to call when the subtree is unregistered.
5787 * @error: Return location for error or %NULL.
5789 * Registers a whole subtree of <quote>dynamic</quote> objects.
5791 * The @enumerate and @introspection functions in @vtable are used to
5792 * convey, to remote callers, what nodes exist in the subtree rooted
5795 * When handling remote calls into any node in the subtree, first the
5796 * @enumerate function is used to check if the node exists. If the node exists
5797 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5798 * the @introspection function is used to check if the node supports the
5799 * requested method. If so, the @dispatch function is used to determine
5800 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5801 * #gpointer will be used to call into the interface vtable for processing
5804 * All calls into user-provided code will be invoked in the <link
5805 * linkend="g-main-context-push-thread-default">thread-default main
5806 * loop</link> of the thread you are calling this method from.
5808 * If an existing subtree is already registered at @object_path or
5809 * then @error is set to #G_IO_ERROR_EXISTS.
5811 * Note that it is valid to register regular objects (using
5812 * g_dbus_connection_register_object()) in a subtree registered with
5813 * g_dbus_connection_register_subtree() - if so, the subtree handler
5814 * is tried as the last resort. One way to think about a subtree
5815 * handler is to consider it a <quote>fallback handler</quote>
5816 * for object paths not registered via g_dbus_connection_register_object()
5817 * or other bindings.
5819 * Note that @vtable will be copied so you cannot change it after
5822 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5824 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5825 * that can be used with g_dbus_connection_unregister_subtree() .
5830 g_dbus_connection_register_subtree (GDBusConnection *connection,
5831 const gchar *object_path,
5832 const GDBusSubtreeVTable *vtable,
5833 GDBusSubtreeFlags flags,
5835 GDestroyNotify user_data_free_func,
5839 ExportedSubtree *es;
5841 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5842 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5843 g_return_val_if_fail (vtable != NULL, 0);
5844 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5848 CONNECTION_LOCK (connection);
5850 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5856 _("A subtree is already exported for %s"),
5861 es = g_new0 (ExportedSubtree, 1);
5862 es->object_path = g_strdup (object_path);
5863 es->connection = connection;
5865 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5867 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5868 es->user_data = user_data;
5869 es->user_data_free_func = user_data_free_func;
5870 es->context = g_main_context_get_thread_default ();
5871 if (es->context != NULL)
5872 g_main_context_ref (es->context);
5874 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5875 g_hash_table_insert (connection->map_id_to_es,
5876 GUINT_TO_POINTER (es->id),
5882 CONNECTION_UNLOCK (connection);
5887 /* ---------------------------------------------------------------------------------------------------- */
5890 * g_dbus_connection_unregister_subtree:
5891 * @connection: A #GDBusConnection.
5892 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5894 * Unregisters a subtree.
5896 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5901 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5902 guint registration_id)
5904 ExportedSubtree *es;
5907 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5911 CONNECTION_LOCK (connection);
5913 es = g_hash_table_lookup (connection->map_id_to_es,
5914 GUINT_TO_POINTER (registration_id));
5918 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5919 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5924 CONNECTION_UNLOCK (connection);
5929 /* ---------------------------------------------------------------------------------------------------- */
5931 /* must be called with lock held */
5933 handle_generic_ping_unlocked (GDBusConnection *connection,
5934 const gchar *object_path,
5935 GDBusMessage *message)
5937 GDBusMessage *reply;
5938 reply = g_dbus_message_new_method_reply (message);
5939 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5940 g_object_unref (reply);
5943 /* must be called with lock held */
5945 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5946 const gchar *object_path,
5947 GDBusMessage *message)
5949 GDBusMessage *reply;
5952 if (connection->machine_id == NULL)
5957 connection->machine_id = _g_dbus_get_machine_id (&error);
5958 if (connection->machine_id == NULL)
5960 reply = g_dbus_message_new_method_error_literal (message,
5961 "org.freedesktop.DBus.Error.Failed",
5963 g_error_free (error);
5969 reply = g_dbus_message_new_method_reply (message);
5970 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5972 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5973 g_object_unref (reply);
5976 /* must be called with lock held */
5978 handle_generic_introspect_unlocked (GDBusConnection *connection,
5979 const gchar *object_path,
5980 GDBusMessage *message)
5985 GDBusMessage *reply;
5987 /* first the header */
5988 s = g_string_new (NULL);
5989 introspect_append_header (s);
5991 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5992 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5993 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5994 g_strfreev (registered);
5995 g_string_append (s, "</node>\n");
5997 reply = g_dbus_message_new_method_reply (message);
5998 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5999 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6000 g_object_unref (reply);
6001 g_string_free (s, TRUE);
6004 /* must be called with lock held */
6006 handle_generic_unlocked (GDBusConnection *connection,
6007 GDBusMessage *message)
6010 const gchar *interface_name;
6011 const gchar *member;
6012 const gchar *signature;
6015 CONNECTION_ENSURE_LOCK (connection);
6019 interface_name = g_dbus_message_get_interface (message);
6020 member = g_dbus_message_get_member (message);
6021 signature = g_dbus_message_get_signature (message);
6022 path = g_dbus_message_get_path (message);
6024 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6025 g_strcmp0 (member, "Introspect") == 0 &&
6026 g_strcmp0 (signature, "") == 0)
6028 handle_generic_introspect_unlocked (connection, path, message);
6031 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6032 g_strcmp0 (member, "Ping") == 0 &&
6033 g_strcmp0 (signature, "") == 0)
6035 handle_generic_ping_unlocked (connection, path, message);
6038 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6039 g_strcmp0 (member, "GetMachineId") == 0 &&
6040 g_strcmp0 (signature, "") == 0)
6042 handle_generic_get_machine_id_unlocked (connection, path, message);
6049 /* ---------------------------------------------------------------------------------------------------- */
6051 /* called in message handler thread with lock held */
6053 distribute_method_call (GDBusConnection *connection,
6054 GDBusMessage *message)
6056 GDBusMessage *reply;
6058 ExportedSubtree *es;
6059 const gchar *object_path;
6060 const gchar *interface_name;
6061 const gchar *member;
6063 gchar *subtree_path;
6066 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6068 interface_name = g_dbus_message_get_interface (message);
6069 member = g_dbus_message_get_member (message);
6070 path = g_dbus_message_get_path (message);
6071 subtree_path = g_strdup (path);
6072 needle = strrchr (subtree_path, '/');
6073 if (needle != NULL && needle != subtree_path)
6079 g_free (subtree_path);
6080 subtree_path = NULL;
6084 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6086 _g_dbus_debug_print_lock ();
6087 g_print ("========================================================================\n"
6088 "GDBus-debug:Incoming:\n"
6089 " <<<< METHOD INVOCATION %s.%s()\n"
6091 " invoked by name %s\n"
6093 interface_name, member,
6095 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6096 g_dbus_message_get_serial (message));
6097 _g_dbus_debug_print_unlock ();
6100 object_path = g_dbus_message_get_path (message);
6101 g_assert (object_path != NULL);
6103 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6106 if (obj_message_func (connection, eo, message))
6110 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6113 if (subtree_message_func (connection, es, message))
6117 if (subtree_path != NULL)
6119 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6122 if (subtree_message_func (connection, es, message))
6127 if (handle_generic_unlocked (connection, message))
6130 /* if we end up here, the message has not been not handled - so return an error saying this */
6131 reply = g_dbus_message_new_method_error (message,
6132 "org.freedesktop.DBus.Error.UnknownMethod",
6133 _("No such interface `%s' on object at path %s"),
6136 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6137 g_object_unref (reply);
6140 g_free (subtree_path);
6143 /* ---------------------------------------------------------------------------------------------------- */
6145 static GDBusConnection **
6146 message_bus_get_singleton (GBusType bus_type,
6149 GDBusConnection **ret;
6150 const gchar *starter_bus;
6156 case G_BUS_TYPE_SESSION:
6157 ret = &the_session_bus;
6160 case G_BUS_TYPE_SYSTEM:
6161 ret = &the_system_bus;
6164 case G_BUS_TYPE_STARTER:
6165 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6166 if (g_strcmp0 (starter_bus, "session") == 0)
6168 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6171 else if (g_strcmp0 (starter_bus, "system") == 0)
6173 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6178 if (starter_bus != NULL)
6182 G_IO_ERROR_INVALID_ARGUMENT,
6183 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6184 " - unknown value `%s'"),
6189 g_set_error_literal (error,
6191 G_IO_ERROR_INVALID_ARGUMENT,
6192 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6193 "variable is not set"));
6199 g_assert_not_reached ();
6207 static GDBusConnection *
6208 get_uninitialized_connection (GBusType bus_type,
6209 GCancellable *cancellable,
6212 GDBusConnection **singleton;
6213 GDBusConnection *ret;
6217 G_LOCK (message_bus_lock);
6218 singleton = message_bus_get_singleton (bus_type, error);
6219 if (singleton == NULL)
6222 if (*singleton == NULL)
6225 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6226 if (address == NULL)
6228 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6230 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6231 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6232 "exit-on-close", TRUE,
6238 ret = g_object_ref (*singleton);
6241 g_assert (ret != NULL);
6244 G_UNLOCK (message_bus_lock);
6250 * @bus_type: A #GBusType.
6251 * @cancellable: A #GCancellable or %NULL.
6252 * @error: Return location for error or %NULL.
6254 * Synchronously connects to the message bus specified by @bus_type.
6255 * Note that the returned object may shared with other callers,
6256 * e.g. if two separate parts of a process calls this function with
6257 * the same @bus_type, they will share the same object.
6259 * This is a synchronous failable function. See g_bus_get() and
6260 * g_bus_get_finish() for the asynchronous version.
6262 * The returned object is a singleton, that is, shared with other
6263 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6264 * event that you need a private message bus connection, use
6265 * g_dbus_address_get_for_bus_sync() and
6266 * g_dbus_connection_new_for_address().
6268 * Note that the returned #GDBusConnection object will (usually) have
6269 * the #GDBusConnection:exit-on-close property set to %TRUE.
6271 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6276 g_bus_get_sync (GBusType bus_type,
6277 GCancellable *cancellable,
6280 GDBusConnection *connection;
6282 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6284 connection = get_uninitialized_connection (bus_type, cancellable, error);
6285 if (connection == NULL)
6288 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6290 g_object_unref (connection);
6299 bus_get_async_initable_cb (GObject *source_object,
6303 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6307 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6311 g_assert (error != NULL);
6312 g_simple_async_result_take_error (simple, error);
6313 g_object_unref (source_object);
6317 g_simple_async_result_set_op_res_gpointer (simple,
6321 g_simple_async_result_complete_in_idle (simple);
6322 g_object_unref (simple);
6327 * @bus_type: A #GBusType.
6328 * @cancellable: A #GCancellable or %NULL.
6329 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6330 * @user_data: The data to pass to @callback.
6332 * Asynchronously connects to the message bus specified by @bus_type.
6334 * When the operation is finished, @callback will be invoked. You can
6335 * then call g_bus_get_finish() to get the result of the operation.
6337 * This is a asynchronous failable function. See g_bus_get_sync() for
6338 * the synchronous version.
6343 g_bus_get (GBusType bus_type,
6344 GCancellable *cancellable,
6345 GAsyncReadyCallback callback,
6348 GDBusConnection *connection;
6349 GSimpleAsyncResult *simple;
6352 simple = g_simple_async_result_new (NULL,
6358 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6359 if (connection == NULL)
6361 g_assert (error != NULL);
6362 g_simple_async_result_take_error (simple, error);
6363 g_simple_async_result_complete_in_idle (simple);
6364 g_object_unref (simple);
6368 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6371 bus_get_async_initable_cb,
6378 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6379 * @error: Return location for error or %NULL.
6381 * Finishes an operation started with g_bus_get().
6383 * The returned object is a singleton, that is, shared with other
6384 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6385 * event that you need a private message bus connection, use
6386 * g_dbus_address_get_for_bus() and
6387 * g_dbus_connection_new_for_address().
6389 * Note that the returned #GDBusConnection object will (usually) have
6390 * the #GDBusConnection:exit-on-close property set to %TRUE.
6392 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6397 g_bus_get_finish (GAsyncResult *res,
6400 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6402 GDBusConnection *ret;
6404 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6406 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6410 if (g_simple_async_result_propagate_error (simple, error))
6413 object = g_simple_async_result_get_op_res_gpointer (simple);
6414 g_assert (object != NULL);
6415 ret = g_object_ref (G_DBUS_CONNECTION (object));
6421 /* ---------------------------------------------------------------------------------------------------- */