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)
99 #include <sys/types.h>
104 #include "gdbusauth.h"
105 #include "gdbusutils.h"
106 #include "gdbusaddress.h"
107 #include "gdbusmessage.h"
108 #include "gdbusconnection.h"
109 #include "gdbuserror.h"
110 #include "gioenumtypes.h"
111 #include "gdbusintrospection.h"
112 #include "gdbusmethodinvocation.h"
113 #include "gdbusprivate.h"
114 #include "gdbusauthobserver.h"
115 #include "gio-marshal.h"
116 #include "ginitable.h"
117 #include "gasyncinitable.h"
118 #include "giostream.h"
119 #include "gasyncresult.h"
120 #include "gsimpleasyncresult.h"
123 #include "gunixconnection.h"
124 #include "gunixfdmessage.h"
127 #include "glibintl.h"
130 * SECTION:gdbusconnection
131 * @short_description: D-Bus Connections
132 * @include: gio/gio.h
134 * The #GDBusConnection type is used for D-Bus connections to remote
135 * peers such as a message buses. It is a low-level API that offers a
136 * lot of flexibility. For instance, it lets you establish a connection
137 * over any transport that can by represented as an #GIOStream.
139 * This class is rarely used directly in D-Bus clients. If you are writing
140 * an D-Bus client, it is often easier to use the g_bus_own_name(),
141 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
143 * <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>
145 * <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>
147 * <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>
149 * <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>
152 /* ---------------------------------------------------------------------------------------------------- */
154 typedef struct _GDBusConnectionClass GDBusConnectionClass;
157 * GDBusConnectionClass:
158 * @closed: Signal class handler for the #GDBusConnection::closed signal.
160 * Class structure for #GDBusConnection.
164 struct _GDBusConnectionClass
167 GObjectClass parent_class;
171 void (*closed) (GDBusConnection *connection,
172 gboolean remote_peer_vanished,
176 G_LOCK_DEFINE_STATIC (message_bus_lock);
178 static GDBusConnection *the_session_bus = NULL;
179 static GDBusConnection *the_system_bus = NULL;
181 /* ---------------------------------------------------------------------------------------------------- */
185 GDestroyNotify callback;
187 GMainContext *context;
188 } CallDestroyNotifyData;
191 call_destroy_notify_data_in_idle (gpointer user_data)
193 CallDestroyNotifyData *data = user_data;
194 data->callback (data->user_data);
199 call_destroy_notify_data_free (CallDestroyNotifyData *data)
201 if (data->context != NULL)
202 g_main_context_unref (data->context);
207 * call_destroy_notify: <internal>
208 * @context: A #GMainContext or %NULL.
209 * @callback: A #GDestroyNotify or %NULL.
210 * @user_data: Data to pass to @callback.
212 * Schedules @callback to run in @context.
215 call_destroy_notify (GMainContext *context,
216 GDestroyNotify callback,
219 if (callback == NULL)
222 if (context == g_main_context_get_thread_default ())
224 callback (user_data);
228 GSource *idle_source;
229 CallDestroyNotifyData *data;
231 data = g_new0 (CallDestroyNotifyData, 1);
232 data->callback = callback;
233 data->user_data = user_data;
234 data->context = context;
235 if (data->context != NULL)
236 g_main_context_ref (data->context);
238 idle_source = g_idle_source_new ();
239 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
240 g_source_set_callback (idle_source,
241 call_destroy_notify_data_in_idle,
243 (GDestroyNotify) call_destroy_notify_data_free);
244 g_source_attach (idle_source, data->context);
245 g_source_unref (idle_source);
252 /* ---------------------------------------------------------------------------------------------------- */
255 _g_strv_has_string (const gchar* const *haystack,
260 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
262 if (g_strcmp0 (haystack[n], needle) == 0)
268 /* ---------------------------------------------------------------------------------------------------- */
271 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
273 // TODO: for some reason this doesn't work on Windows
274 #define CONNECTION_ENSURE_LOCK(obj) do { \
275 if (G_UNLIKELY (g_mutex_trylock((obj)->lock))) \
277 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
278 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
283 #define CONNECTION_LOCK(obj) do { \
284 g_mutex_lock ((obj)->lock); \
287 #define CONNECTION_UNLOCK(obj) do { \
288 g_mutex_unlock ((obj)->lock); \
294 * The #GDBusConnection structure contains only private data and
295 * should only be accessed using the provided API.
299 struct _GDBusConnection
302 GObject parent_instance;
304 /* ------------------------------------------------------------------------ */
305 /* -- General object state ------------------------------------------------ */
306 /* ------------------------------------------------------------------------ */
308 /* object-wide lock */
311 /* A lock used in the init() method of the GInitable interface - see comments
312 * in initable_init() for why a separate lock is needed
316 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
317 * someone calls org.freedesktop.DBus.GetMachineId()
321 /* The underlying stream used for communication */
324 /* The object used for authentication (if any) */
327 /* Set to TRUE if the connection has been closed */
330 /* Last serial used */
333 /* The object used to send/receive message */
336 /* If connected to a message bus, this contains the unique name assigned to
337 * us by the bus (e.g. ":1.42")
339 gchar *bus_unique_name;
341 /* The GUID returned by the other side if we authenticed as a client or
342 * the GUID to use if authenticating as a server
346 /* set to TRUE exactly when initable_init() has finished running */
347 gboolean is_initialized;
349 /* If the connection could not be established during initable_init(), this GError will set */
350 GError *initialization_error;
352 /* The result of g_main_context_get_thread_default() when the object
353 * was created (the GObject _init() function) - this is used for delivery
354 * of the :closed GObject signal.
356 GMainContext *main_context_at_construction;
358 /* construct properties */
360 GDBusConnectionFlags flags;
362 /* Map used for managing method replies */
363 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
365 /* Maps used for managing signal subscription */
366 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
367 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
368 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
370 /* Maps used for managing exported objects and subtrees */
371 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
372 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
373 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
374 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
376 /* Structure used for message filters */
379 /* Whether to exit on close */
380 gboolean exit_on_close;
382 /* Capabilities negotiated during authentication */
383 GDBusCapabilityFlags capabilities;
385 GDBusAuthObserver *authentication_observer;
386 GCredentials *credentials;
388 /* set to TRUE when finalizing */
392 typedef struct ExportedObject ExportedObject;
393 static void exported_object_free (ExportedObject *eo);
395 typedef struct ExportedSubtree ExportedSubtree;
396 static void exported_subtree_free (ExportedSubtree *es);
414 PROP_CAPABILITY_FLAGS,
415 PROP_AUTHENTICATION_OBSERVER,
418 static void distribute_signals (GDBusConnection *connection,
419 GDBusMessage *message);
421 static void distribute_method_call (GDBusConnection *connection,
422 GDBusMessage *message);
424 static gboolean handle_generic_unlocked (GDBusConnection *connection,
425 GDBusMessage *message);
428 static void purge_all_signal_subscriptions (GDBusConnection *connection);
429 static void purge_all_filters (GDBusConnection *connection);
431 #define _G_ENSURE_LOCK(name) do { \
432 if (G_UNLIKELY (G_TRYLOCK(name))) \
434 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
435 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
439 static guint signals[LAST_SIGNAL] = { 0 };
441 static void initable_iface_init (GInitableIface *initable_iface);
442 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
444 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
445 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
446 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
449 static GHashTable *alive_connections = NULL;
452 g_dbus_connection_dispose (GObject *object)
454 GDBusConnection *connection = G_DBUS_CONNECTION (object);
456 G_LOCK (message_bus_lock);
457 if (connection == the_session_bus)
459 the_session_bus = NULL;
461 else if (connection == the_system_bus)
463 the_system_bus = NULL;
465 CONNECTION_LOCK (connection);
466 if (connection->worker != NULL)
468 _g_dbus_worker_stop (connection->worker);
469 connection->worker = NULL;
470 if (alive_connections != NULL)
471 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
475 if (alive_connections != NULL)
476 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
478 CONNECTION_UNLOCK (connection);
479 G_UNLOCK (message_bus_lock);
481 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
482 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
486 g_dbus_connection_finalize (GObject *object)
488 GDBusConnection *connection = G_DBUS_CONNECTION (object);
490 connection->finalizing = TRUE;
492 purge_all_signal_subscriptions (connection);
494 purge_all_filters (connection);
495 g_ptr_array_unref (connection->filters);
497 if (connection->authentication_observer != NULL)
498 g_object_unref (connection->authentication_observer);
500 if (connection->auth != NULL)
501 g_object_unref (connection->auth);
503 if (connection->credentials)
504 g_object_unref (connection->credentials);
506 if (connection->stream != NULL)
508 /* We don't really care if closing the stream succeeds or not */
509 g_io_stream_close_async (connection->stream,
511 NULL, /* GCancellable */
512 NULL, /* GAsyncReadyCallback */
513 NULL); /* userdata */
514 g_object_unref (connection->stream);
515 connection->stream = NULL;
518 g_free (connection->address);
520 g_free (connection->guid);
521 g_free (connection->bus_unique_name);
523 if (connection->initialization_error != NULL)
524 g_error_free (connection->initialization_error);
526 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
528 g_hash_table_unref (connection->map_rule_to_signal_data);
529 g_hash_table_unref (connection->map_id_to_signal_data);
530 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
532 g_hash_table_unref (connection->map_id_to_ei);
533 g_hash_table_unref (connection->map_object_path_to_eo);
534 g_hash_table_unref (connection->map_id_to_es);
535 g_hash_table_unref (connection->map_object_path_to_es);
537 if (connection->main_context_at_construction != NULL)
538 g_main_context_unref (connection->main_context_at_construction);
540 g_free (connection->machine_id);
542 g_mutex_free (connection->init_lock);
543 g_mutex_free (connection->lock);
545 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
549 g_dbus_connection_get_property (GObject *object,
554 GDBusConnection *connection = G_DBUS_CONNECTION (object);
559 g_value_set_object (value, g_dbus_connection_get_stream (connection));
563 g_value_set_string (value, g_dbus_connection_get_guid (connection));
566 case PROP_UNIQUE_NAME:
567 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
571 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
574 case PROP_EXIT_ON_CLOSE:
575 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
578 case PROP_CAPABILITY_FLAGS:
579 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
583 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
589 g_dbus_connection_set_property (GObject *object,
594 GDBusConnection *connection = G_DBUS_CONNECTION (object);
599 connection->stream = g_value_dup_object (value);
603 connection->guid = g_value_dup_string (value);
607 connection->address = g_value_dup_string (value);
611 connection->flags = g_value_get_flags (value);
614 case PROP_EXIT_ON_CLOSE:
615 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
618 case PROP_AUTHENTICATION_OBSERVER:
619 connection->authentication_observer = g_value_dup_object (value);
623 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
629 g_dbus_connection_real_closed (GDBusConnection *connection,
630 gboolean remote_peer_vanished,
633 if (remote_peer_vanished && connection->exit_on_close)
637 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
640 g_quark_to_string (error->domain), error->code);
644 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
651 g_dbus_connection_class_init (GDBusConnectionClass *klass)
653 GObjectClass *gobject_class;
655 gobject_class = G_OBJECT_CLASS (klass);
657 gobject_class->finalize = g_dbus_connection_finalize;
658 gobject_class->dispose = g_dbus_connection_dispose;
659 gobject_class->set_property = g_dbus_connection_set_property;
660 gobject_class->get_property = g_dbus_connection_get_property;
662 klass->closed = g_dbus_connection_real_closed;
665 * GDBusConnection:stream:
667 * The underlying #GIOStream used for I/O.
671 g_object_class_install_property (gobject_class,
673 g_param_spec_object ("stream",
675 P_("The underlying streams used for I/O"),
679 G_PARAM_CONSTRUCT_ONLY |
680 G_PARAM_STATIC_NAME |
681 G_PARAM_STATIC_BLURB |
682 G_PARAM_STATIC_NICK));
685 * GDBusConnection:address:
687 * A D-Bus address specifying potential endpoints that can be used
688 * when establishing the connection.
692 g_object_class_install_property (gobject_class,
694 g_param_spec_string ("address",
696 P_("D-Bus address specifying potential socket endpoints"),
699 G_PARAM_CONSTRUCT_ONLY |
700 G_PARAM_STATIC_NAME |
701 G_PARAM_STATIC_BLURB |
702 G_PARAM_STATIC_NICK));
705 * GDBusConnection:flags:
707 * Flags from the #GDBusConnectionFlags enumeration.
711 g_object_class_install_property (gobject_class,
713 g_param_spec_flags ("flags",
716 G_TYPE_DBUS_CONNECTION_FLAGS,
717 G_DBUS_CONNECTION_FLAGS_NONE,
719 G_PARAM_CONSTRUCT_ONLY |
720 G_PARAM_STATIC_NAME |
721 G_PARAM_STATIC_BLURB |
722 G_PARAM_STATIC_NICK));
725 * GDBusConnection:guid:
727 * The GUID of the peer performing the role of server when
730 * If you are constructing a #GDBusConnection and pass
731 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
732 * #GDBusConnection:flags property then you MUST also set this
733 * property to a valid guid.
735 * If you are constructing a #GDBusConnection and pass
736 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
737 * #GDBusConnection:flags property you will be able to read the GUID
738 * of the other peer here after the connection has been successfully
743 g_object_class_install_property (gobject_class,
745 g_param_spec_string ("guid",
747 P_("GUID of the server peer"),
751 G_PARAM_CONSTRUCT_ONLY |
752 G_PARAM_STATIC_NAME |
753 G_PARAM_STATIC_BLURB |
754 G_PARAM_STATIC_NICK));
757 * GDBusConnection:unique-name:
759 * The unique name as assigned by the message bus or %NULL if the
760 * connection is not open or not a message bus connection.
764 g_object_class_install_property (gobject_class,
766 g_param_spec_string ("unique-name",
768 P_("Unique name of bus connection"),
771 G_PARAM_STATIC_NAME |
772 G_PARAM_STATIC_BLURB |
773 G_PARAM_STATIC_NICK));
776 * GDBusConnection:closed:
778 * A boolean specifying whether the connection has been closed.
782 g_object_class_install_property (gobject_class,
784 g_param_spec_boolean ("closed",
786 P_("Whether the connection is closed"),
789 G_PARAM_STATIC_NAME |
790 G_PARAM_STATIC_BLURB |
791 G_PARAM_STATIC_NICK));
794 * GDBusConnection:exit-on-close:
796 * A boolean specifying whether the process will be terminated (by
797 * calling <literal>raise(SIGTERM)</literal>) if the connection
798 * is closed by the remote peer.
802 g_object_class_install_property (gobject_class,
804 g_param_spec_boolean ("exit-on-close",
806 P_("Whether the process is terminated when the connection is closed"),
810 G_PARAM_STATIC_NAME |
811 G_PARAM_STATIC_BLURB |
812 G_PARAM_STATIC_NICK));
815 * GDBusConnection:capabilities:
817 * Flags from the #GDBusCapabilityFlags enumeration
818 * representing connection features negotiated with the other peer.
822 g_object_class_install_property (gobject_class,
823 PROP_CAPABILITY_FLAGS,
824 g_param_spec_flags ("capabilities",
827 G_TYPE_DBUS_CAPABILITY_FLAGS,
828 G_DBUS_CAPABILITY_FLAGS_NONE,
830 G_PARAM_STATIC_NAME |
831 G_PARAM_STATIC_BLURB |
832 G_PARAM_STATIC_NICK));
835 * GDBusConnection:authentication-observer:
837 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
841 g_object_class_install_property (gobject_class,
842 PROP_AUTHENTICATION_OBSERVER,
843 g_param_spec_object ("authentication-observer",
844 P_("Authentication Observer"),
845 P_("Object used to assist in the authentication process"),
846 G_TYPE_DBUS_AUTH_OBSERVER,
848 G_PARAM_CONSTRUCT_ONLY |
849 G_PARAM_STATIC_NAME |
850 G_PARAM_STATIC_BLURB |
851 G_PARAM_STATIC_NICK));
854 * GDBusConnection::closed:
855 * @connection: The #GDBusConnection emitting the signal.
856 * @remote_peer_vanished: %TRUE if @connection is closed because the
857 * remote peer closed its end of the connection.
858 * @error: A #GError with more details about the event or %NULL.
860 * Emitted when the connection is closed.
862 * The cause of this event can be
865 * If g_dbus_connection_close() is called. In this case
866 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
869 * If the remote peer closes the connection. In this case
870 * @remote_peer_vanished is set to %TRUE and @error is set.
873 * If the remote peer sends invalid or malformed data. In this
874 * case @remote_peer_vanished is set to %FALSE and @error
879 * Upon receiving this signal, you should give up your reference to
880 * @connection. You are guaranteed that this signal is emitted only
885 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
886 G_TYPE_DBUS_CONNECTION,
888 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
891 _gio_marshal_VOID__BOOLEAN_BOXED,
899 g_dbus_connection_init (GDBusConnection *connection)
901 connection->lock = g_mutex_new ();
902 connection->init_lock = g_mutex_new ();
904 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
906 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
908 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
910 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
913 (GDestroyNotify) g_ptr_array_unref);
915 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
918 (GDestroyNotify) exported_object_free);
920 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
923 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
926 (GDestroyNotify) exported_subtree_free);
928 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
931 connection->main_context_at_construction = g_main_context_get_thread_default ();
932 if (connection->main_context_at_construction != NULL)
933 g_main_context_ref (connection->main_context_at_construction);
935 connection->filters = g_ptr_array_new ();
939 * g_dbus_connection_get_stream:
940 * @connection: a #GDBusConnection
942 * Gets the underlying stream used for IO.
944 * Returns: the stream used for IO
949 g_dbus_connection_get_stream (GDBusConnection *connection)
951 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
952 return connection->stream;
956 * g_dbus_connection_start_message_processing:
957 * @connection: A #GDBusConnection.
959 * If @connection was created with
960 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
961 * starts processing messages. Does nothing on if @connection wasn't
962 * created with this flag or if the method has already been called.
967 g_dbus_connection_start_message_processing (GDBusConnection *connection)
969 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
970 _g_dbus_worker_unfreeze (connection->worker);
974 * g_dbus_connection_is_closed:
975 * @connection: A #GDBusConnection.
977 * Gets whether @connection is closed.
979 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
984 g_dbus_connection_is_closed (GDBusConnection *connection)
986 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
987 return connection->closed;
991 * g_dbus_connection_get_capabilities:
992 * @connection: A #GDBusConnection.
994 * Gets the capabilities negotiated with the remote peer
996 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1000 GDBusCapabilityFlags
1001 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1003 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1004 return connection->capabilities;
1007 /* ---------------------------------------------------------------------------------------------------- */
1010 flush_in_thread_func (GSimpleAsyncResult *res,
1012 GCancellable *cancellable)
1017 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1021 g_simple_async_result_set_from_error (res, error);
1022 g_error_free (error);
1027 * g_dbus_connection_flush:
1028 * @connection: A #GDBusConnection.
1029 * @cancellable: A #GCancellable or %NULL.
1030 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1031 * care about the result.
1032 * @user_data: The data to pass to @callback.
1034 * Asynchronously flushes @connection, that is, writes all queued
1035 * outgoing message to the transport and then flushes the transport
1036 * (using g_output_stream_flush_async()). This is useful in programs
1037 * that wants to emit a D-Bus signal and then exit
1038 * immediately. Without flushing the connection, there is no guarantee
1039 * that the message has been sent to the networking buffers in the OS
1042 * This is an asynchronous method. When the operation is finished,
1043 * @callback will be invoked in the <link
1044 * linkend="g-main-context-push-thread-default">thread-default main
1045 * loop</link> of the thread you are calling this method from. You can
1046 * then call g_dbus_connection_flush_finish() to get the result of the
1047 * operation. See g_dbus_connection_flush_sync() for the synchronous
1053 g_dbus_connection_flush (GDBusConnection *connection,
1054 GCancellable *cancellable,
1055 GAsyncReadyCallback callback,
1058 GSimpleAsyncResult *simple;
1060 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1062 simple = g_simple_async_result_new (G_OBJECT (connection),
1065 g_dbus_connection_flush);
1066 g_simple_async_result_run_in_thread (simple,
1067 flush_in_thread_func,
1070 g_object_unref (simple);
1074 * g_dbus_connection_flush_finish:
1075 * @connection: A #GDBusConnection.
1076 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1077 * @error: Return location for error or %NULL.
1079 * Finishes an operation started with g_dbus_connection_flush().
1081 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1086 g_dbus_connection_flush_finish (GDBusConnection *connection,
1090 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1095 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1096 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1097 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1099 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1101 if (g_simple_async_result_propagate_error (simple, error))
1111 * g_dbus_connection_flush_sync:
1112 * @connection: A #GDBusConnection.
1113 * @cancellable: A #GCancellable or %NULL.
1114 * @error: Return location for error or %NULL.
1116 * Synchronously flushes @connection. The calling thread is blocked
1117 * until this is done. See g_dbus_connection_flush() for the
1118 * asynchronous version of this method and more details about what it
1121 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1126 g_dbus_connection_flush_sync (GDBusConnection *connection,
1127 GCancellable *cancellable,
1132 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1133 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1137 if (connection->closed)
1139 g_set_error_literal (error,
1142 _("The connection is closed"));
1146 ret = _g_dbus_worker_flush_sync (connection->worker,
1154 /* ---------------------------------------------------------------------------------------------------- */
1158 GDBusConnection *connection;
1160 gboolean remote_peer_vanished;
1164 emit_closed_data_free (EmitClosedData *data)
1166 g_object_unref (data->connection);
1167 if (data->error != NULL)
1168 g_error_free (data->error);
1173 emit_closed_in_idle (gpointer user_data)
1175 EmitClosedData *data = user_data;
1178 g_object_notify (G_OBJECT (data->connection), "closed");
1179 g_signal_emit (data->connection,
1180 signals[CLOSED_SIGNAL],
1182 data->remote_peer_vanished,
1188 /* Can be called from any thread, must hold lock */
1190 set_closed_unlocked (GDBusConnection *connection,
1191 gboolean remote_peer_vanished,
1194 GSource *idle_source;
1195 EmitClosedData *data;
1197 CONNECTION_ENSURE_LOCK (connection);
1199 g_assert (!connection->closed);
1201 connection->closed = TRUE;
1203 data = g_new0 (EmitClosedData, 1);
1204 data->connection = g_object_ref (connection);
1205 data->remote_peer_vanished = remote_peer_vanished;
1206 data->error = error != NULL ? g_error_copy (error) : NULL;
1208 idle_source = g_idle_source_new ();
1209 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1210 g_source_set_callback (idle_source,
1211 emit_closed_in_idle,
1213 (GDestroyNotify) emit_closed_data_free);
1214 g_source_attach (idle_source, connection->main_context_at_construction);
1215 g_source_unref (idle_source);
1218 /* ---------------------------------------------------------------------------------------------------- */
1221 close_in_thread_func (GSimpleAsyncResult *res,
1223 GCancellable *cancellable)
1228 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1232 g_simple_async_result_set_from_error (res, error);
1233 g_error_free (error);
1238 * g_dbus_connection_close:
1239 * @connection: A #GDBusConnection.
1240 * @cancellable: A #GCancellable or %NULL.
1241 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1242 * care about the result.
1243 * @user_data: The data to pass to @callback.
1245 * Closes @connection. Note that this never causes the process to
1246 * exit (this might only happen if the other end of a shared message
1247 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1249 * Once the connection is closed, operations such as sending a message
1250 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1251 * will not automatically flush the connection so queued messages may
1252 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1254 * If @connection is already closed, this method fails with
1255 * %G_IO_ERROR_CLOSED.
1257 * When @connection has been closed, the #GDBusConnection::closed
1258 * signal is emitted in the <link
1259 * linkend="g-main-context-push-thread-default">thread-default main
1260 * loop</link> of the thread that @connection was constructed in.
1262 * This is an asynchronous method. When the operation is finished,
1263 * @callback will be invoked in the <link
1264 * linkend="g-main-context-push-thread-default">thread-default main
1265 * loop</link> of the thread you are calling this method from. You can
1266 * then call g_dbus_connection_close_finish() to get the result of the
1267 * operation. See g_dbus_connection_close_sync() for the synchronous
1273 g_dbus_connection_close (GDBusConnection *connection,
1274 GCancellable *cancellable,
1275 GAsyncReadyCallback callback,
1278 GSimpleAsyncResult *simple;
1280 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1282 simple = g_simple_async_result_new (G_OBJECT (connection),
1285 g_dbus_connection_close);
1286 g_simple_async_result_run_in_thread (simple,
1287 close_in_thread_func,
1290 g_object_unref (simple);
1294 * g_dbus_connection_close_finish:
1295 * @connection: A #GDBusConnection.
1296 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1297 * @error: Return location for error or %NULL.
1299 * Finishes an operation started with g_dbus_connection_close().
1301 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1306 g_dbus_connection_close_finish (GDBusConnection *connection,
1310 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1315 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1316 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1317 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1319 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1321 if (g_simple_async_result_propagate_error (simple, error))
1331 * g_dbus_connection_close_sync:
1332 * @connection: A #GDBusConnection.
1333 * @cancellable: A #GCancellable or %NULL.
1334 * @error: Return location for error or %NULL.
1336 * Synchronously closees @connection. The calling thread is blocked
1337 * until this is done. See g_dbus_connection_close() for the
1338 * asynchronous version of this method and more details about what it
1341 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1346 g_dbus_connection_close_sync (GDBusConnection *connection,
1347 GCancellable *cancellable,
1352 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1353 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1357 CONNECTION_LOCK (connection);
1358 if (!connection->closed)
1360 ret = g_io_stream_close (connection->stream,
1364 set_closed_unlocked (connection, FALSE, NULL);
1368 g_set_error_literal (error,
1371 _("The connection is closed"));
1373 CONNECTION_UNLOCK (connection);
1378 /* ---------------------------------------------------------------------------------------------------- */
1381 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1382 GDBusMessage *message,
1383 GDBusSendMessageFlags flags,
1384 volatile guint32 *out_serial,
1389 guint32 serial_to_use;
1392 CONNECTION_ENSURE_LOCK (connection);
1394 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1395 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1397 /* TODO: check all necessary headers are present */
1402 if (out_serial != NULL)
1405 if (connection->closed)
1407 g_set_error_literal (error,
1410 _("The connection is closed"));
1414 blob = g_dbus_message_to_blob (message,
1416 connection->capabilities,
1421 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1422 serial_to_use = g_dbus_message_get_serial (message);
1424 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1429 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1432 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1435 g_assert_not_reached ();
1440 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1441 blob_size, serial_to_use, connection);
1442 g_printerr ("----\n");
1443 hexdump (blob, blob_size);
1444 g_printerr ("----\n");
1447 /* TODO: use connection->auth to encode the blob */
1449 if (out_serial != NULL)
1450 *out_serial = serial_to_use;
1452 g_dbus_message_set_serial (message, serial_to_use);
1454 g_dbus_message_lock (message);
1455 _g_dbus_worker_send_message (connection->worker,
1459 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1470 * g_dbus_connection_send_message:
1471 * @connection: A #GDBusConnection.
1472 * @message: A #GDBusMessage
1473 * @flags: Flags affecting how the message is sent.
1474 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1475 * @error: Return location for error or %NULL.
1477 * Asynchronously sends @message to the peer represented by @connection.
1479 * Unless @flags contain the
1480 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1481 * will be assigned by @connection and set on @message via
1482 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1483 * serial number used will be written to this location prior to
1484 * submitting the message to the underlying transport.
1486 * If @connection is closed then the operation will fail with
1487 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1488 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1490 * See <xref linkend="gdbus-server"/> and <xref
1491 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1492 * low-level API to send and receive UNIX file descriptors.
1494 * Note that @message must be unlocked, unless @flags contain the
1495 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1497 * Returns: %TRUE if the message was well-formed and queued for
1498 * transmission, %FALSE if @error is set.
1503 g_dbus_connection_send_message (GDBusConnection *connection,
1504 GDBusMessage *message,
1505 GDBusSendMessageFlags flags,
1506 volatile guint32 *out_serial,
1511 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1512 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1513 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1514 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1516 CONNECTION_LOCK (connection);
1517 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1518 CONNECTION_UNLOCK (connection);
1522 /* ---------------------------------------------------------------------------------------------------- */
1526 volatile gint ref_count;
1527 GDBusConnection *connection;
1529 GSimpleAsyncResult *simple;
1531 GMainContext *main_context;
1533 GCancellable *cancellable;
1535 gulong cancellable_handler_id;
1537 GSource *timeout_source;
1542 static SendMessageData *
1543 send_message_data_ref (SendMessageData *data)
1545 g_atomic_int_inc (&data->ref_count);
1550 send_message_data_unref (SendMessageData *data)
1552 if (g_atomic_int_dec_and_test (&data->ref_count))
1554 g_assert (data->timeout_source == NULL);
1555 g_assert (data->simple == NULL);
1556 g_assert (data->cancellable_handler_id == 0);
1557 g_object_unref (data->connection);
1558 if (data->cancellable != NULL)
1559 g_object_unref (data->cancellable);
1560 if (data->main_context != NULL)
1561 g_main_context_unref (data->main_context);
1566 /* ---------------------------------------------------------------------------------------------------- */
1568 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1570 send_message_with_reply_deliver (SendMessageData *data)
1572 CONNECTION_ENSURE_LOCK (data->connection);
1574 g_assert (!data->delivered);
1576 data->delivered = TRUE;
1578 g_simple_async_result_complete_in_idle (data->simple);
1579 g_object_unref (data->simple);
1580 data->simple = NULL;
1582 if (data->timeout_source != NULL)
1584 g_source_destroy (data->timeout_source);
1585 data->timeout_source = NULL;
1587 if (data->cancellable_handler_id > 0)
1589 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1590 data->cancellable_handler_id = 0;
1593 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1594 GUINT_TO_POINTER (data->serial)));
1596 send_message_data_unref (data);
1599 /* ---------------------------------------------------------------------------------------------------- */
1601 /* must hold lock */
1603 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1604 GDBusMessage *reply)
1606 if (data->delivered)
1609 g_simple_async_result_set_op_res_gpointer (data->simple,
1610 g_object_ref (reply),
1613 send_message_with_reply_deliver (data);
1619 /* ---------------------------------------------------------------------------------------------------- */
1622 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1624 SendMessageData *data = user_data;
1626 CONNECTION_LOCK (data->connection);
1627 if (data->delivered)
1630 g_simple_async_result_set_error (data->simple,
1632 G_IO_ERROR_CANCELLED,
1633 _("Operation was cancelled"));
1635 send_message_with_reply_deliver (data);
1638 CONNECTION_UNLOCK (data->connection);
1642 /* Can be called from any thread with or without lock held */
1644 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1647 SendMessageData *data = user_data;
1648 GSource *idle_source;
1650 /* postpone cancellation to idle handler since we may be called directly
1651 * via g_cancellable_connect() (e.g. holding lock)
1653 idle_source = g_idle_source_new ();
1654 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1655 g_source_set_callback (idle_source,
1656 send_message_with_reply_cancelled_idle_cb,
1657 send_message_data_ref (data),
1658 (GDestroyNotify) send_message_data_unref);
1659 g_source_attach (idle_source, data->main_context);
1660 g_source_unref (idle_source);
1663 /* ---------------------------------------------------------------------------------------------------- */
1666 send_message_with_reply_timeout_cb (gpointer user_data)
1668 SendMessageData *data = user_data;
1670 CONNECTION_LOCK (data->connection);
1671 if (data->delivered)
1674 g_simple_async_result_set_error (data->simple,
1676 G_IO_ERROR_TIMED_OUT,
1677 _("Timeout was reached"));
1679 send_message_with_reply_deliver (data);
1682 CONNECTION_UNLOCK (data->connection);
1687 /* ---------------------------------------------------------------------------------------------------- */
1690 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1691 GDBusMessage *message,
1692 GDBusSendMessageFlags flags,
1694 volatile guint32 *out_serial,
1695 GCancellable *cancellable,
1696 GAsyncReadyCallback callback,
1699 GSimpleAsyncResult *simple;
1700 SendMessageData *data;
1702 volatile guint32 serial;
1706 if (out_serial == NULL)
1707 out_serial = &serial;
1709 if (timeout_msec == -1)
1710 timeout_msec = 25 * 1000;
1712 simple = g_simple_async_result_new (G_OBJECT (connection),
1715 g_dbus_connection_send_message_with_reply);
1717 if (g_cancellable_is_cancelled (cancellable))
1719 g_simple_async_result_set_error (simple,
1721 G_IO_ERROR_CANCELLED,
1722 _("Operation was cancelled"));
1723 g_simple_async_result_complete_in_idle (simple);
1724 g_object_unref (simple);
1728 if (connection->closed)
1730 g_simple_async_result_set_error (simple,
1733 _("The connection is closed"));
1734 g_simple_async_result_complete_in_idle (simple);
1735 g_object_unref (simple);
1740 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1742 g_simple_async_result_set_from_error (simple, error);
1743 g_simple_async_result_complete_in_idle (simple);
1744 g_object_unref (simple);
1748 data = g_new0 (SendMessageData, 1);
1749 data->ref_count = 1;
1750 data->connection = g_object_ref (connection);
1751 data->simple = simple;
1752 data->serial = *out_serial;
1753 data->main_context = g_main_context_get_thread_default ();
1754 if (data->main_context != NULL)
1755 g_main_context_ref (data->main_context);
1757 if (cancellable != NULL)
1759 data->cancellable = g_object_ref (cancellable);
1760 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1761 G_CALLBACK (send_message_with_reply_cancelled_cb),
1762 send_message_data_ref (data),
1763 (GDestroyNotify) send_message_data_unref);
1764 g_object_set_data_full (G_OBJECT (simple),
1766 g_object_ref (cancellable),
1767 (GDestroyNotify) g_object_unref);
1770 data->timeout_source = g_timeout_source_new (timeout_msec);
1771 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1772 g_source_set_callback (data->timeout_source,
1773 send_message_with_reply_timeout_cb,
1774 send_message_data_ref (data),
1775 (GDestroyNotify) send_message_data_unref);
1776 g_source_attach (data->timeout_source, data->main_context);
1777 g_source_unref (data->timeout_source);
1779 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1780 GUINT_TO_POINTER (*out_serial),
1788 * g_dbus_connection_send_message_with_reply:
1789 * @connection: A #GDBusConnection.
1790 * @message: A #GDBusMessage.
1791 * @flags: Flags affecting how the message is sent.
1792 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1793 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1794 * @cancellable: A #GCancellable or %NULL.
1795 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1796 * care about the result.
1797 * @user_data: The data to pass to @callback.
1799 * Asynchronously sends @message to the peer represented by @connection.
1801 * Unless @flags contain the
1802 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1803 * will be assigned by @connection and set on @message via
1804 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1805 * serial number used will be written to this location prior to
1806 * submitting the message to the underlying transport.
1808 * If @connection is closed then the operation will fail with
1809 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1810 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1811 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1813 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1814 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1815 * of the thread you are calling this method from. You can then call
1816 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1817 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1819 * Note that @message must be unlocked, unless @flags contain the
1820 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1822 * See <xref linkend="gdbus-server"/> and <xref
1823 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1824 * low-level API to send and receive UNIX file descriptors.
1829 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1830 GDBusMessage *message,
1831 GDBusSendMessageFlags flags,
1833 volatile guint32 *out_serial,
1834 GCancellable *cancellable,
1835 GAsyncReadyCallback callback,
1838 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1839 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1840 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1841 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1843 CONNECTION_LOCK (connection);
1844 g_dbus_connection_send_message_with_reply_unlocked (connection,
1852 CONNECTION_UNLOCK (connection);
1856 * g_dbus_connection_send_message_with_reply_finish:
1857 * @connection: a #GDBusConnection
1858 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1859 * @error: Return location for error or %NULL.
1861 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1863 * Note that @error is only set if a local in-process error
1864 * occured. That is to say that the returned #GDBusMessage object may
1865 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1866 * g_dbus_message_to_gerror() to transcode this to a #GError.
1868 * See <xref linkend="gdbus-server"/> and <xref
1869 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1870 * low-level API to send and receive UNIX file descriptors.
1872 * Returns: A locked #GDBusMessage or %NULL if @error is set.
1877 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1881 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1882 GDBusMessage *reply;
1883 GCancellable *cancellable;
1885 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1886 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1890 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1892 if (g_simple_async_result_propagate_error (simple, error))
1895 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1896 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1897 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1899 g_object_unref (reply);
1901 g_set_error_literal (error,
1903 G_IO_ERROR_CANCELLED,
1904 _("Operation was cancelled"));
1910 /* ---------------------------------------------------------------------------------------------------- */
1915 GMainContext *context;
1917 } SendMessageSyncData;
1920 send_message_with_reply_sync_cb (GDBusConnection *connection,
1924 SendMessageSyncData *data = user_data;
1925 data->res = g_object_ref (res);
1926 g_main_loop_quit (data->loop);
1930 * g_dbus_connection_send_message_with_reply_sync:
1931 * @connection: A #GDBusConnection.
1932 * @message: A #GDBusMessage.
1933 * @flags: Flags affecting how the message is sent.
1934 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1935 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1936 * @cancellable: A #GCancellable or %NULL.
1937 * @error: Return location for error or %NULL.
1939 * Synchronously sends @message to the peer represented by @connection
1940 * and blocks the calling thread until a reply is received or the
1941 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1942 * for the asynchronous version of this method.
1944 * Unless @flags contain the
1945 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1946 * will be assigned by @connection and set on @message via
1947 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1948 * serial number used will be written to this location prior to
1949 * submitting the message to the underlying transport.
1951 * If @connection is closed then the operation will fail with
1952 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1953 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1954 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1956 * Note that @error is only set if a local in-process error
1957 * occured. That is to say that the returned #GDBusMessage object may
1958 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1959 * g_dbus_message_to_gerror() to transcode this to a #GError.
1961 * See <xref linkend="gdbus-server"/> and <xref
1962 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1963 * low-level API to send and receive UNIX file descriptors.
1965 * Note that @message must be unlocked, unless @flags contain the
1966 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1968 * Returns: A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
1973 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1974 GDBusMessage *message,
1975 GDBusSendMessageFlags flags,
1977 volatile guint32 *out_serial,
1978 GCancellable *cancellable,
1981 SendMessageSyncData *data;
1982 GDBusMessage *reply;
1984 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1985 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1986 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1987 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1988 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1990 data = g_new0 (SendMessageSyncData, 1);
1991 data->context = g_main_context_new ();
1992 data->loop = g_main_loop_new (data->context, FALSE);
1994 g_main_context_push_thread_default (data->context);
1996 g_dbus_connection_send_message_with_reply (connection,
2002 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2004 g_main_loop_run (data->loop);
2005 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2009 g_main_context_pop_thread_default (data->context);
2011 g_main_context_unref (data->context);
2012 g_main_loop_unref (data->loop);
2013 g_object_unref (data->res);
2019 /* ---------------------------------------------------------------------------------------------------- */
2023 GDBusMessageFilterFunction func;
2030 GDBusMessageFilterFunction filter_function;
2032 GDestroyNotify user_data_free_func;
2035 /* Called in worker's thread - we must not block */
2037 on_worker_message_received (GDBusWorker *worker,
2038 GDBusMessage *message,
2041 GDBusConnection *connection;
2042 FilterCallback *filters;
2043 gboolean consumed_by_filter;
2044 gboolean altered_by_filter;
2049 G_LOCK (message_bus_lock);
2050 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2053 G_UNLOCK (message_bus_lock);
2056 connection = G_DBUS_CONNECTION (user_data);
2057 g_object_ref (connection);
2058 G_UNLOCK (message_bus_lock);
2060 //g_debug ("in on_worker_message_received");
2062 g_object_ref (message);
2063 g_dbus_message_lock (message);
2065 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2067 /* First collect the set of callback functions */
2068 CONNECTION_LOCK (connection);
2069 num_filters = connection->filters->len;
2070 filters = g_new0 (FilterCallback, num_filters);
2071 for (n = 0; n < num_filters; n++)
2073 FilterData *data = connection->filters->pdata[n];
2074 filters[n].func = data->filter_function;
2075 filters[n].user_data = data->user_data;
2077 CONNECTION_UNLOCK (connection);
2079 /* then call the filters in order (without holding the lock) */
2080 consumed_by_filter = FALSE;
2081 altered_by_filter = FALSE;
2082 for (n = 0; n < num_filters; n++)
2084 message = filters[n].func (connection,
2087 filters[n].user_data);
2088 if (message == NULL)
2090 g_dbus_message_lock (message);
2093 /* Standard dispatch unless the filter ate the message - no need to
2094 * do anything if the message was altered
2096 if (message != NULL)
2098 GDBusMessageType message_type;
2100 message_type = g_dbus_message_get_message_type (message);
2101 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2103 guint32 reply_serial;
2104 SendMessageData *send_message_data;
2106 reply_serial = g_dbus_message_get_reply_serial (message);
2107 CONNECTION_LOCK (connection);
2108 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2109 GUINT_TO_POINTER (reply_serial));
2110 if (send_message_data != NULL)
2112 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2113 send_message_data_deliver_reply_unlocked (send_message_data, message);
2117 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2119 CONNECTION_UNLOCK (connection);
2121 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2123 CONNECTION_LOCK (connection);
2124 distribute_signals (connection, message);
2125 CONNECTION_UNLOCK (connection);
2127 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2129 CONNECTION_LOCK (connection);
2130 distribute_method_call (connection, message);
2131 CONNECTION_UNLOCK (connection);
2135 if (message != NULL)
2136 g_object_unref (message);
2137 g_object_unref (connection);
2141 /* Called in worker's thread */
2142 static GDBusMessage *
2143 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2144 GDBusMessage *message,
2147 GDBusConnection *connection;
2148 FilterCallback *filters;
2153 G_LOCK (message_bus_lock);
2154 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2157 G_UNLOCK (message_bus_lock);
2160 connection = G_DBUS_CONNECTION (user_data);
2161 g_object_ref (connection);
2162 G_UNLOCK (message_bus_lock);
2164 //g_debug ("in on_worker_message_about_to_be_sent");
2166 /* First collect the set of callback functions */
2167 CONNECTION_LOCK (connection);
2168 num_filters = connection->filters->len;
2169 filters = g_new0 (FilterCallback, num_filters);
2170 for (n = 0; n < num_filters; n++)
2172 FilterData *data = connection->filters->pdata[n];
2173 filters[n].func = data->filter_function;
2174 filters[n].user_data = data->user_data;
2176 CONNECTION_UNLOCK (connection);
2178 /* then call the filters in order (without holding the lock) */
2179 for (n = 0; n < num_filters; n++)
2181 g_dbus_message_lock (message);
2182 message = filters[n].func (connection,
2185 filters[n].user_data);
2186 if (message == NULL)
2190 g_object_unref (connection);
2196 /* Called in worker's thread - we must not block */
2198 on_worker_closed (GDBusWorker *worker,
2199 gboolean remote_peer_vanished,
2203 GDBusConnection *connection;
2206 G_LOCK (message_bus_lock);
2207 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2210 G_UNLOCK (message_bus_lock);
2213 connection = G_DBUS_CONNECTION (user_data);
2214 g_object_ref (connection);
2215 G_UNLOCK (message_bus_lock);
2217 //g_debug ("in on_worker_closed: %s", error->message);
2219 CONNECTION_LOCK (connection);
2220 if (!connection->closed)
2221 set_closed_unlocked (connection, remote_peer_vanished, error);
2222 CONNECTION_UNLOCK (connection);
2224 g_object_unref (connection);
2227 /* ---------------------------------------------------------------------------------------------------- */
2229 /* Determines the biggest set of capabilities we can support on this connection */
2230 static GDBusCapabilityFlags
2231 get_offered_capabilities_max (GDBusConnection *connection)
2233 GDBusCapabilityFlags ret;
2234 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2236 if (G_IS_UNIX_CONNECTION (connection->stream))
2237 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2243 initable_init (GInitable *initable,
2244 GCancellable *cancellable,
2247 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2250 /* This method needs to be idempotent to work with the singleton
2251 * pattern. See the docs for g_initable_init(). We implement this by
2254 * Unfortunately we can't use the main lock since the on_worker_*()
2255 * callbacks above needs the lock during initialization (for message
2256 * bus connections we do a synchronous Hello() call on the bus).
2258 g_mutex_lock (connection->init_lock);
2262 if (connection->is_initialized)
2264 if (connection->stream != NULL)
2267 g_assert (connection->initialization_error != NULL);
2270 g_assert (connection->initialization_error == NULL);
2272 /* The user can pass multiple (but mutally exclusive) construct
2275 * - stream (of type GIOStream)
2276 * - address (of type gchar*)
2278 * At the end of the day we end up with a non-NULL GIOStream
2279 * object in connection->stream.
2281 if (connection->address != NULL)
2283 g_assert (connection->stream == NULL);
2285 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2286 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2288 g_set_error_literal (error,
2290 G_IO_ERROR_INVALID_ARGUMENT,
2291 _("Unsupported flags encountered when constructing a client-side connection"));
2295 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2296 NULL, /* TODO: out_guid */
2298 &connection->initialization_error);
2299 if (connection->stream == NULL)
2302 else if (connection->stream != NULL)
2308 g_assert_not_reached ();
2311 /* Authenticate the connection */
2312 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2314 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2315 g_assert (connection->guid != NULL);
2316 connection->auth = _g_dbus_auth_new (connection->stream);
2317 if (!_g_dbus_auth_run_server (connection->auth,
2318 connection->authentication_observer,
2320 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2321 get_offered_capabilities_max (connection),
2322 &connection->capabilities,
2323 &connection->credentials,
2325 &connection->initialization_error))
2328 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2330 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2331 g_assert (connection->guid == NULL);
2332 connection->auth = _g_dbus_auth_new (connection->stream);
2333 connection->guid = _g_dbus_auth_run_client (connection->auth,
2334 get_offered_capabilities_max (connection),
2335 &connection->capabilities,
2337 &connection->initialization_error);
2338 if (connection->guid == NULL)
2342 if (connection->authentication_observer != NULL)
2344 g_object_unref (connection->authentication_observer);
2345 connection->authentication_observer = NULL;
2348 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2350 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2355 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
2359 if (G_IS_SOCKET_CONNECTION (connection->stream))
2361 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2365 G_LOCK (message_bus_lock);
2366 if (alive_connections == NULL)
2367 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2368 g_hash_table_insert (alive_connections, connection, connection);
2369 G_UNLOCK (message_bus_lock);
2371 connection->worker = _g_dbus_worker_new (connection->stream,
2372 connection->capabilities,
2373 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2374 on_worker_message_received,
2375 on_worker_message_about_to_be_sent,
2379 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2380 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2382 GVariant *hello_result;
2384 /* we could lift this restriction by adding code in gdbusprivate.c */
2385 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2387 g_set_error_literal (&connection->initialization_error,
2390 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2394 hello_result = g_dbus_connection_call_sync (connection,
2395 "org.freedesktop.DBus", /* name */
2396 "/org/freedesktop/DBus", /* path */
2397 "org.freedesktop.DBus", /* interface */
2399 NULL, /* parameters */
2400 G_VARIANT_TYPE ("(s)"),
2401 G_DBUS_CALL_FLAGS_NONE,
2403 NULL, /* TODO: cancellable */
2404 &connection->initialization_error);
2405 if (hello_result == NULL)
2408 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2409 g_variant_unref (hello_result);
2410 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2413 connection->is_initialized = TRUE;
2419 g_assert (connection->initialization_error != NULL);
2420 g_propagate_error (error, g_error_copy (connection->initialization_error));
2423 g_mutex_unlock (connection->init_lock);
2429 initable_iface_init (GInitableIface *initable_iface)
2431 initable_iface->init = initable_init;
2434 /* ---------------------------------------------------------------------------------------------------- */
2437 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2442 /* ---------------------------------------------------------------------------------------------------- */
2445 * g_dbus_connection_new:
2446 * @stream: A #GIOStream.
2447 * @guid: The GUID to use if a authenticating as a server or %NULL.
2448 * @flags: Flags describing how to make the connection.
2449 * @observer: A #GDBusAuthObserver or %NULL.
2450 * @cancellable: A #GCancellable or %NULL.
2451 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2452 * @user_data: The data to pass to @callback.
2454 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2455 * with the end represented by @stream.
2457 * If @observer is not %NULL it may be used to control the
2458 * authentication process.
2460 * When the operation is finished, @callback will be invoked. You can
2461 * then call g_dbus_connection_new_finish() to get the result of the
2464 * This is a asynchronous failable constructor. See
2465 * g_dbus_connection_new_sync() for the synchronous
2471 g_dbus_connection_new (GIOStream *stream,
2473 GDBusConnectionFlags flags,
2474 GDBusAuthObserver *observer,
2475 GCancellable *cancellable,
2476 GAsyncReadyCallback callback,
2479 g_return_if_fail (G_IS_IO_STREAM (stream));
2480 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2488 "authentication-observer", observer,
2493 * g_dbus_connection_new_finish:
2494 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2495 * @error: Return location for error or %NULL.
2497 * Finishes an operation started with g_dbus_connection_new().
2499 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2504 g_dbus_connection_new_finish (GAsyncResult *res,
2508 GObject *source_object;
2510 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2511 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2513 source_object = g_async_result_get_source_object (res);
2514 g_assert (source_object != NULL);
2515 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2518 g_object_unref (source_object);
2520 return G_DBUS_CONNECTION (object);
2526 * g_dbus_connection_new_sync:
2527 * @stream: A #GIOStream.
2528 * @guid: The GUID to use if a authenticating as a server or %NULL.
2529 * @flags: Flags describing how to make the connection.
2530 * @observer: A #GDBusAuthObserver or %NULL.
2531 * @cancellable: A #GCancellable or %NULL.
2532 * @error: Return location for error or %NULL.
2534 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2535 * with the end represented by @stream.
2537 * If @observer is not %NULL it may be used to control the
2538 * authentication process.
2540 * This is a synchronous failable constructor. See
2541 * g_dbus_connection_new() for the asynchronous version.
2543 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2548 g_dbus_connection_new_sync (GIOStream *stream,
2550 GDBusConnectionFlags flags,
2551 GDBusAuthObserver *observer,
2552 GCancellable *cancellable,
2555 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2556 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2557 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2563 "authentication-observer", observer,
2567 /* ---------------------------------------------------------------------------------------------------- */
2570 * g_dbus_connection_new_for_address:
2571 * @address: A D-Bus address.
2572 * @flags: Flags describing how to make the connection.
2573 * @observer: A #GDBusAuthObserver or %NULL.
2574 * @cancellable: A #GCancellable or %NULL.
2575 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2576 * @user_data: The data to pass to @callback.
2578 * Asynchronously connects and sets up a D-Bus client connection for
2579 * exchanging D-Bus messages with an endpoint specified by @address
2580 * which must be in the D-Bus address format.
2582 * This constructor can only be used to initiate client-side
2583 * connections - use g_dbus_connection_new() if you need to act as the
2584 * server. In particular, @flags cannot contain the
2585 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2586 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2588 * When the operation is finished, @callback will be invoked. You can
2589 * then call g_dbus_connection_new_finish() to get the result of the
2592 * If @observer is not %NULL it may be used to control the
2593 * authentication process.
2595 * This is a asynchronous failable constructor. See
2596 * g_dbus_connection_new_for_address_sync() for the synchronous
2602 g_dbus_connection_new_for_address (const gchar *address,
2603 GDBusConnectionFlags flags,
2604 GDBusAuthObserver *observer,
2605 GCancellable *cancellable,
2606 GAsyncReadyCallback callback,
2609 g_return_if_fail (address != NULL);
2610 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2617 "authentication-observer", observer,
2622 * g_dbus_connection_new_for_address_finish:
2623 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2624 * @error: Return location for error or %NULL.
2626 * Finishes an operation started with g_dbus_connection_new_for_address().
2628 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2633 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2637 GObject *source_object;
2639 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2640 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2642 source_object = g_async_result_get_source_object (res);
2643 g_assert (source_object != NULL);
2644 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2647 g_object_unref (source_object);
2649 return G_DBUS_CONNECTION (object);
2655 * g_dbus_connection_new_for_address_sync:
2656 * @address: A D-Bus address.
2657 * @flags: Flags describing how to make the connection.
2658 * @observer: A #GDBusAuthObserver or %NULL.
2659 * @cancellable: A #GCancellable or %NULL.
2660 * @error: Return location for error or %NULL.
2662 * Synchronously connects and sets up a D-Bus client connection for
2663 * exchanging D-Bus messages with an endpoint specified by @address
2664 * which must be in the D-Bus address format.
2666 * This constructor can only be used to initiate client-side
2667 * connections - use g_dbus_connection_new_sync() if you need to act
2668 * as the server. In particular, @flags cannot contain the
2669 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2670 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2672 * This is a synchronous failable constructor. See
2673 * g_dbus_connection_new_for_address() for the asynchronous version.
2675 * If @observer is not %NULL it may be used to control the
2676 * authentication process.
2678 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2683 g_dbus_connection_new_for_address_sync (const gchar *address,
2684 GDBusConnectionFlags flags,
2685 GDBusAuthObserver *observer,
2686 GCancellable *cancellable,
2689 g_return_val_if_fail (address != NULL, NULL);
2690 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2691 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2696 "authentication-observer", observer,
2700 /* ---------------------------------------------------------------------------------------------------- */
2703 * g_dbus_connection_set_exit_on_close:
2704 * @connection: A #GDBusConnection.
2705 * @exit_on_close: Whether the process should be terminated
2706 * when @connection is closed by the remote peer.
2708 * Sets whether the process should be terminated when @connection is
2709 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2715 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2716 gboolean exit_on_close)
2718 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2719 connection->exit_on_close = exit_on_close;
2723 * g_dbus_connection_get_exit_on_close:
2724 * @connection: A #GDBusConnection.
2726 * Gets whether the process is terminated when @connection is
2727 * closed by the remote peer. See
2728 * #GDBusConnection:exit-on-close for more details.
2730 * Returns: Whether the process is terminated when @connection is
2731 * closed by the remote peer.
2736 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2738 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2739 return connection->exit_on_close;
2743 * g_dbus_connection_get_guid:
2744 * @connection: A #GDBusConnection.
2746 * The GUID of the peer performing the role of server when
2747 * authenticating. See #GDBusConnection:guid for more details.
2749 * Returns: The GUID. Do not free this string, it is owned by
2755 g_dbus_connection_get_guid (GDBusConnection *connection)
2757 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2758 return connection->guid;
2762 * g_dbus_connection_get_unique_name:
2763 * @connection: A #GDBusConnection.
2765 * Gets the unique name of @connection as assigned by the message
2766 * bus. This can also be used to figure out if @connection is a
2767 * message bus connection.
2769 * Returns: The unique name or %NULL if @connection is not a message
2770 * bus connection. Do not free this string, it is owned by
2776 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2778 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2779 return connection->bus_unique_name;
2783 * g_dbus_connection_get_peer_credentials:
2784 * @connection: A #GDBusConnection.
2786 * Gets the credentials of the authenticated peer. This will always
2787 * return %NULL unless @connection acted as a server
2788 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2789 * when set up and the client passed credentials as part of the
2790 * authentication process.
2792 * In a message bus setup, the message bus is always the server and
2793 * each application is a client. So this method will always return
2794 * %NULL for message bus clients.
2796 * Returns: A #GCredentials or %NULL if not available. Do not free
2797 * this object, it is owned by @connection.
2802 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2804 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2805 return connection->credentials;
2808 /* ---------------------------------------------------------------------------------------------------- */
2810 static guint _global_filter_id = 1;
2813 * g_dbus_connection_add_filter:
2814 * @connection: A #GDBusConnection.
2815 * @filter_function: A filter function.
2816 * @user_data: User data to pass to @filter_function.
2817 * @user_data_free_func: Function to free @user_data with when filter
2818 * is removed or %NULL.
2820 * Adds a message filter. Filters are handlers that are run on all
2821 * incoming and outgoing messages, prior to standard dispatch. Filters
2822 * are run in the order that they were added. The same handler can be
2823 * added as a filter more than once, in which case it will be run more
2824 * than once. Filters added during a filter callback won't be run on
2825 * the message being processed. Filter functions are allowed to modify
2826 * and even drop messages - see the #GDBusMessageFilterResult
2827 * enumeration for details.
2829 * Note that filters are run in a dedicated message handling thread so
2830 * they can't block and, generally, can't do anything but signal a
2831 * worker thread. Also note that filters are rarely needed - use API
2832 * such as g_dbus_connection_send_message_with_reply(),
2833 * g_dbus_connection_signal_subscribe() or
2834 * g_dbus_connection_call() instead.
2836 * If a filter consumes an incoming message the message is not
2837 * dispatched anywhere else - not even the standard dispatch machinery
2838 * (that API such as g_dbus_connection_signal_subscribe() and
2839 * g_dbus_connection_send_message_with_reply() relies on) will see the
2840 * message. Similary, if a filter consumes an outgoing message, the
2841 * message will not be sent to the other peer.
2843 * Returns: A filter identifier that can be used with
2844 * g_dbus_connection_remove_filter().
2849 g_dbus_connection_add_filter (GDBusConnection *connection,
2850 GDBusMessageFilterFunction filter_function,
2852 GDestroyNotify user_data_free_func)
2856 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2857 g_return_val_if_fail (filter_function != NULL, 0);
2859 CONNECTION_LOCK (connection);
2860 data = g_new0 (FilterData, 1);
2861 data->id = _global_filter_id++; /* TODO: overflow etc. */
2862 data->filter_function = filter_function;
2863 data->user_data = user_data;
2864 data->user_data_free_func = user_data_free_func;
2865 g_ptr_array_add (connection->filters, data);
2866 CONNECTION_UNLOCK (connection);
2871 /* only called from finalize(), removes all filters */
2873 purge_all_filters (GDBusConnection *connection)
2876 for (n = 0; n < connection->filters->len; n++)
2878 FilterData *data = connection->filters->pdata[n];
2879 if (data->user_data_free_func != NULL)
2880 data->user_data_free_func (data->user_data);
2886 * g_dbus_connection_remove_filter:
2887 * @connection: a #GDBusConnection
2888 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2895 g_dbus_connection_remove_filter (GDBusConnection *connection,
2899 FilterData *to_destroy;
2901 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2903 CONNECTION_LOCK (connection);
2905 for (n = 0; n < connection->filters->len; n++)
2907 FilterData *data = connection->filters->pdata[n];
2908 if (data->id == filter_id)
2910 g_ptr_array_remove_index (connection->filters, n);
2915 CONNECTION_UNLOCK (connection);
2917 /* do free without holding lock */
2918 if (to_destroy != NULL)
2920 if (to_destroy->user_data_free_func != NULL)
2921 to_destroy->user_data_free_func (to_destroy->user_data);
2922 g_free (to_destroy);
2926 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2930 /* ---------------------------------------------------------------------------------------------------- */
2936 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2937 gchar *interface_name;
2941 GArray *subscribers;
2946 GDBusSignalCallback callback;
2948 GDestroyNotify user_data_free_func;
2950 GMainContext *context;
2954 signal_data_free (SignalData *signal_data)
2956 g_free (signal_data->rule);
2957 g_free (signal_data->sender);
2958 g_free (signal_data->sender_unique_name);
2959 g_free (signal_data->interface_name);
2960 g_free (signal_data->member);
2961 g_free (signal_data->object_path);
2962 g_free (signal_data->arg0);
2963 g_array_free (signal_data->subscribers, TRUE);
2964 g_free (signal_data);
2968 args_to_rule (const gchar *sender,
2969 const gchar *interface_name,
2970 const gchar *member,
2971 const gchar *object_path,
2976 rule = g_string_new ("type='signal'");
2978 g_string_append_printf (rule, ",sender='%s'", sender);
2979 if (interface_name != NULL)
2980 g_string_append_printf (rule, ",interface='%s'", interface_name);
2982 g_string_append_printf (rule, ",member='%s'", member);
2983 if (object_path != NULL)
2984 g_string_append_printf (rule, ",path='%s'", object_path);
2986 g_string_append_printf (rule, ",arg0='%s'", arg0);
2988 return g_string_free (rule, FALSE);
2991 static guint _global_subscriber_id = 1;
2992 static guint _global_registration_id = 1;
2993 static guint _global_subtree_registration_id = 1;
2995 /* ---------------------------------------------------------------------------------------------------- */
2997 /* must hold lock when calling */
2999 add_match_rule (GDBusConnection *connection,
3000 const gchar *match_rule)
3003 GDBusMessage *message;
3005 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3006 "/org/freedesktop/DBus", /* path */
3007 "org.freedesktop.DBus", /* interface */
3009 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3011 if (!g_dbus_connection_send_message_unlocked (connection,
3013 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3017 g_critical ("Error while sending AddMatch() message: %s", error->message);
3018 g_error_free (error);
3020 g_object_unref (message);
3023 /* ---------------------------------------------------------------------------------------------------- */
3025 /* must hold lock when calling */
3027 remove_match_rule (GDBusConnection *connection,
3028 const gchar *match_rule)
3031 GDBusMessage *message;
3033 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3034 "/org/freedesktop/DBus", /* path */
3035 "org.freedesktop.DBus", /* interface */
3037 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3040 if (!g_dbus_connection_send_message_unlocked (connection,
3042 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3046 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3047 g_error_free (error);
3049 g_object_unref (message);
3052 /* ---------------------------------------------------------------------------------------------------- */
3055 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3057 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3058 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3059 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3060 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3061 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3064 /* ---------------------------------------------------------------------------------------------------- */
3067 * g_dbus_connection_signal_subscribe:
3068 * @connection: A #GDBusConnection.
3069 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
3070 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
3071 * @member: D-Bus signal name to match on or %NULL to match on all signals.
3072 * @object_path: Object path to match on or %NULL to match on all object paths.
3073 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
3074 * @flags: Flags describing how to subscribe to the signal (currently unused).
3075 * @callback: Callback to invoke when there is a signal matching the requested data.
3076 * @user_data: User data to pass to @callback.
3077 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
3079 * Subscribes to signals on @connection and invokes @callback with a
3080 * whenever the signal is received. Note that @callback
3081 * will be invoked in the <link
3082 * linkend="g-main-context-push-thread-default">thread-default main
3083 * loop</link> of the thread you are calling this method from.
3085 * If @connection is not a message bus connection, @sender must be
3088 * If @sender is a well-known name note that @callback is invoked with
3089 * the unique name for the owner of @sender, not the well-known name
3090 * as one would expect. This is because the message bus rewrites the
3091 * name. As such, to avoid certain race conditions, users should be
3092 * tracking the name owner of the well-known name and use that when
3093 * processing the received signal.
3095 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3100 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3101 const gchar *sender,
3102 const gchar *interface_name,
3103 const gchar *member,
3104 const gchar *object_path,
3106 GDBusSignalFlags flags,
3107 GDBusSignalCallback callback,
3109 GDestroyNotify user_data_free_func)
3112 SignalData *signal_data;
3113 SignalSubscriber subscriber;
3114 GPtrArray *signal_data_array;
3115 const gchar *sender_unique_name;
3117 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3118 * an OOM condition. We might want to change that but that would involve making
3119 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3120 * handle that. And there's really no sensible way of handling this short of retrying
3121 * to add the match rule... and then there's the little thing that, hey, maybe there's
3122 * a reason the bus in an OOM condition.
3124 * Doable, but not really sure it's worth it...
3127 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3128 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3129 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3130 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3131 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3132 g_return_val_if_fail (callback != NULL, 0);
3134 CONNECTION_LOCK (connection);
3136 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
3138 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3139 sender_unique_name = sender;
3141 sender_unique_name = "";
3143 subscriber.callback = callback;
3144 subscriber.user_data = user_data;
3145 subscriber.user_data_free_func = user_data_free_func;
3146 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3147 subscriber.context = g_main_context_get_thread_default ();
3148 if (subscriber.context != NULL)
3149 g_main_context_ref (subscriber.context);
3151 /* see if we've already have this rule */
3152 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3153 if (signal_data != NULL)
3155 g_array_append_val (signal_data->subscribers, subscriber);
3160 signal_data = g_new0 (SignalData, 1);
3161 signal_data->rule = rule;
3162 signal_data->sender = g_strdup (sender);
3163 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3164 signal_data->interface_name = g_strdup (interface_name);
3165 signal_data->member = g_strdup (member);
3166 signal_data->object_path = g_strdup (object_path);
3167 signal_data->arg0 = g_strdup (arg0);
3168 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3169 g_array_append_val (signal_data->subscribers, subscriber);
3171 g_hash_table_insert (connection->map_rule_to_signal_data,
3175 /* Add the match rule to the bus...
3177 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3178 * always send such messages to us.
3180 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3182 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3183 add_match_rule (connection, signal_data->rule);
3186 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3187 signal_data->sender_unique_name);
3188 if (signal_data_array == NULL)
3190 signal_data_array = g_ptr_array_new ();
3191 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3192 g_strdup (signal_data->sender_unique_name),
3195 g_ptr_array_add (signal_data_array, signal_data);
3198 g_hash_table_insert (connection->map_id_to_signal_data,
3199 GUINT_TO_POINTER (subscriber.id),
3202 CONNECTION_UNLOCK (connection);
3204 return subscriber.id;
3207 /* ---------------------------------------------------------------------------------------------------- */
3209 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3211 unsubscribe_id_internal (GDBusConnection *connection,
3212 guint subscription_id,
3213 GArray *out_removed_subscribers)
3215 SignalData *signal_data;
3216 GPtrArray *signal_data_array;
3219 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3220 GUINT_TO_POINTER (subscription_id));
3221 if (signal_data == NULL)
3223 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3227 for (n = 0; n < signal_data->subscribers->len; n++)
3229 SignalSubscriber *subscriber;
3231 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3232 if (subscriber->id != subscription_id)
3235 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3236 GUINT_TO_POINTER (subscription_id)));
3237 g_array_append_val (out_removed_subscribers, *subscriber);
3238 g_array_remove_index (signal_data->subscribers, n);
3240 if (signal_data->subscribers->len == 0)
3242 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3244 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3245 signal_data->sender_unique_name);
3246 g_warn_if_fail (signal_data_array != NULL);
3247 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3249 if (signal_data_array->len == 0)
3251 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3252 signal_data->sender_unique_name));
3255 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3256 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3258 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3259 if (!connection->closed && !connection->finalizing)
3260 remove_match_rule (connection, signal_data->rule);
3262 signal_data_free (signal_data);
3268 g_assert_not_reached ();
3275 * g_dbus_connection_signal_unsubscribe:
3276 * @connection: A #GDBusConnection.
3277 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3279 * Unsubscribes from signals.
3284 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3285 guint subscription_id)
3287 GArray *subscribers;
3290 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3292 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3294 CONNECTION_LOCK (connection);
3295 unsubscribe_id_internal (connection,
3298 CONNECTION_UNLOCK (connection);
3301 g_assert (subscribers->len == 0 || subscribers->len == 1);
3303 /* call GDestroyNotify without lock held */
3304 for (n = 0; n < subscribers->len; n++)
3306 SignalSubscriber *subscriber;
3307 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3308 call_destroy_notify (subscriber->context,
3309 subscriber->user_data_free_func,
3310 subscriber->user_data);
3311 if (subscriber->context != NULL)
3312 g_main_context_unref (subscriber->context);
3315 g_array_free (subscribers, TRUE);
3318 /* ---------------------------------------------------------------------------------------------------- */
3322 guint subscription_id;
3323 GDBusSignalCallback callback;
3325 GDBusMessage *message;
3326 GDBusConnection *connection;
3327 const gchar *sender;
3329 const gchar *interface;
3330 const gchar *member;
3333 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3337 emit_signal_instance_in_idle_cb (gpointer data)
3339 SignalInstance *signal_instance = data;
3340 GVariant *parameters;
3341 gboolean has_subscription;
3343 parameters = g_dbus_message_get_body (signal_instance->message);
3344 if (parameters == NULL)
3346 parameters = g_variant_new ("()");
3347 g_variant_ref_sink (parameters);
3351 g_variant_ref_sink (parameters);
3355 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3356 signal_instance->subscription_id,
3357 signal_instance->sender,
3358 signal_instance->path,
3359 signal_instance->interface,
3360 signal_instance->member,
3361 g_variant_print (parameters, TRUE));
3364 /* Careful here, don't do the callback if we no longer has the subscription */
3365 CONNECTION_LOCK (signal_instance->connection);
3366 has_subscription = FALSE;
3367 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3368 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3369 has_subscription = TRUE;
3370 CONNECTION_UNLOCK (signal_instance->connection);
3372 if (has_subscription)
3373 signal_instance->callback (signal_instance->connection,
3374 signal_instance->sender,
3375 signal_instance->path,
3376 signal_instance->interface,
3377 signal_instance->member,
3379 signal_instance->user_data);
3381 if (parameters != NULL)
3382 g_variant_unref (parameters);
3388 signal_instance_free (SignalInstance *signal_instance)
3390 g_object_unref (signal_instance->message);
3391 g_object_unref (signal_instance->connection);
3392 g_free (signal_instance);
3395 /* called in message handler thread WITH lock held */
3397 schedule_callbacks (GDBusConnection *connection,
3398 GPtrArray *signal_data_array,
3399 GDBusMessage *message,
3400 const gchar *sender)
3403 const gchar *interface;
3404 const gchar *member;
3413 interface = g_dbus_message_get_interface (message);
3414 member = g_dbus_message_get_member (message);
3415 path = g_dbus_message_get_path (message);
3416 arg0 = g_dbus_message_get_arg0 (message);
3419 g_print ("In schedule_callbacks:\n"
3421 " interface = `%s'\n"
3432 /* TODO: if this is slow, then we can change signal_data_array into
3433 * map_object_path_to_signal_data_array or something.
3435 for (n = 0; n < signal_data_array->len; n++)
3437 SignalData *signal_data = signal_data_array->pdata[n];
3439 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3442 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3445 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3448 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3451 for (m = 0; m < signal_data->subscribers->len; m++)
3453 SignalSubscriber *subscriber;
3454 GSource *idle_source;
3455 SignalInstance *signal_instance;
3457 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3459 signal_instance = g_new0 (SignalInstance, 1);
3460 signal_instance->subscription_id = subscriber->id;
3461 signal_instance->callback = subscriber->callback;
3462 signal_instance->user_data = subscriber->user_data;
3463 signal_instance->message = g_object_ref (message);
3464 signal_instance->connection = g_object_ref (connection);
3465 signal_instance->sender = sender;
3466 signal_instance->path = path;
3467 signal_instance->interface = interface;
3468 signal_instance->member = member;
3470 idle_source = g_idle_source_new ();
3471 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3472 g_source_set_callback (idle_source,
3473 emit_signal_instance_in_idle_cb,
3475 (GDestroyNotify) signal_instance_free);
3476 g_source_attach (idle_source, subscriber->context);
3477 g_source_unref (idle_source);
3482 /* called in message handler thread with lock held */
3484 distribute_signals (GDBusConnection *connection,
3485 GDBusMessage *message)
3487 GPtrArray *signal_data_array;
3488 const gchar *sender;
3490 sender = g_dbus_message_get_sender (message);
3492 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3494 _g_dbus_debug_print_lock ();
3495 g_print ("========================================================================\n"
3496 "GDBus-debug:Signal:\n"
3497 " <<<< RECEIVED SIGNAL %s.%s\n"
3499 " sent by name %s\n",
3500 g_dbus_message_get_interface (message),
3501 g_dbus_message_get_member (message),
3502 g_dbus_message_get_path (message),
3503 sender != NULL ? sender : "(none)");
3504 _g_dbus_debug_print_unlock ();
3507 /* collect subscribers that match on sender */
3510 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3511 if (signal_data_array != NULL)
3512 schedule_callbacks (connection, signal_data_array, message, sender);
3515 /* collect subscribers not matching on sender */
3516 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3517 if (signal_data_array != NULL)
3518 schedule_callbacks (connection, signal_data_array, message, sender);
3521 /* ---------------------------------------------------------------------------------------------------- */
3523 /* only called from finalize(), removes all subscriptions */
3525 purge_all_signal_subscriptions (GDBusConnection *connection)
3527 GHashTableIter iter;
3530 GArray *subscribers;
3533 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3534 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3535 while (g_hash_table_iter_next (&iter, &key, NULL))
3537 guint subscription_id = GPOINTER_TO_UINT (key);
3538 g_array_append_val (ids, subscription_id);
3541 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3542 for (n = 0; n < ids->len; n++)
3544 guint subscription_id = g_array_index (ids, guint, n);
3545 unsubscribe_id_internal (connection,
3549 g_array_free (ids, TRUE);
3551 /* call GDestroyNotify without lock held */
3552 for (n = 0; n < subscribers->len; n++)
3554 SignalSubscriber *subscriber;
3555 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3556 call_destroy_notify (subscriber->context,
3557 subscriber->user_data_free_func,
3558 subscriber->user_data);
3559 if (subscriber->context != NULL)
3560 g_main_context_unref (subscriber->context);
3563 g_array_free (subscribers, TRUE);
3566 /* ---------------------------------------------------------------------------------------------------- */
3568 static GDBusInterfaceVTable *
3569 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3571 /* Don't waste memory by copying padding - remember to update this
3572 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3574 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3578 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3583 /* ---------------------------------------------------------------------------------------------------- */
3585 static GDBusSubtreeVTable *
3586 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3588 /* Don't waste memory by copying padding - remember to update this
3589 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3591 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3595 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3600 /* ---------------------------------------------------------------------------------------------------- */
3602 struct ExportedObject
3605 GDBusConnection *connection;
3607 /* maps gchar* -> ExportedInterface* */
3608 GHashTable *map_if_name_to_ei;
3611 /* only called with lock held */
3613 exported_object_free (ExportedObject *eo)
3615 g_free (eo->object_path);
3616 g_hash_table_unref (eo->map_if_name_to_ei);
3625 gchar *interface_name;
3626 GDBusInterfaceVTable *vtable;
3627 GDBusInterfaceInfo *interface_info;
3629 GMainContext *context;
3631 GDestroyNotify user_data_free_func;
3632 } ExportedInterface;
3634 /* called with lock held */
3636 exported_interface_free (ExportedInterface *ei)
3638 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3640 call_destroy_notify (ei->context,
3641 ei->user_data_free_func,
3644 if (ei->context != NULL)
3645 g_main_context_unref (ei->context);
3647 g_free (ei->interface_name);
3648 _g_dbus_interface_vtable_free (ei->vtable);
3652 /* ---------------------------------------------------------------------------------------------------- */
3654 /* Convenience function to check if @registration_id (if not zero) or
3655 * @subtree_registration_id (if not zero) has been unregistered. If
3656 * so, returns %TRUE.
3658 * Caller must *not* hold lock.
3661 has_object_been_unregistered (GDBusConnection *connection,
3662 guint registration_id,
3663 guint subtree_registration_id)
3667 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3671 CONNECTION_LOCK (connection);
3672 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3673 GUINT_TO_POINTER (registration_id)) == NULL)
3677 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3678 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3682 CONNECTION_UNLOCK (connection);
3687 /* ---------------------------------------------------------------------------------------------------- */
3691 GDBusConnection *connection;
3692 GDBusMessage *message;
3694 const gchar *property_name;
3695 const GDBusInterfaceVTable *vtable;
3696 GDBusInterfaceInfo *interface_info;
3697 const GDBusPropertyInfo *property_info;
3698 guint registration_id;
3699 guint subtree_registration_id;
3703 property_data_free (PropertyData *data)
3705 g_object_unref (data->connection);
3706 g_object_unref (data->message);
3710 /* called in thread where object was registered - no locks held */
3712 invoke_get_property_in_idle_cb (gpointer _data)
3714 PropertyData *data = _data;
3717 GDBusMessage *reply;
3719 if (has_object_been_unregistered (data->connection,
3720 data->registration_id,
3721 data->subtree_registration_id))
3723 reply = g_dbus_message_new_method_error (data->message,
3724 "org.freedesktop.DBus.Error.UnknownMethod",
3725 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3726 g_dbus_message_get_path (data->message));
3727 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3728 g_object_unref (reply);
3733 value = data->vtable->get_property (data->connection,
3734 g_dbus_message_get_sender (data->message),
3735 g_dbus_message_get_path (data->message),
3736 data->interface_info->name,
3737 data->property_name,
3744 g_assert_no_error (error);
3746 if (g_variant_is_floating (value))
3747 g_variant_ref_sink (value);
3748 reply = g_dbus_message_new_method_reply (data->message);
3749 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3750 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3751 g_variant_unref (value);
3752 g_object_unref (reply);
3756 gchar *dbus_error_name;
3757 g_assert (error != NULL);
3758 dbus_error_name = g_dbus_error_encode_gerror (error);
3759 reply = g_dbus_message_new_method_error_literal (data->message,
3762 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3763 g_free (dbus_error_name);
3764 g_error_free (error);
3765 g_object_unref (reply);
3772 /* called in thread where object was registered - no locks held */
3774 invoke_set_property_in_idle_cb (gpointer _data)
3776 PropertyData *data = _data;
3778 GDBusMessage *reply;
3784 g_variant_get (g_dbus_message_get_body (data->message),
3790 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3791 * of the given value is wrong
3793 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3795 reply = g_dbus_message_new_method_error (data->message,
3796 "org.freedesktop.DBus.Error.InvalidArgs",
3797 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3798 data->property_info->name,
3799 data->property_info->signature,
3800 g_variant_get_type_string (value));
3804 if (!data->vtable->set_property (data->connection,
3805 g_dbus_message_get_sender (data->message),
3806 g_dbus_message_get_path (data->message),
3807 data->interface_info->name,
3808 data->property_name,
3813 gchar *dbus_error_name;
3814 g_assert (error != NULL);
3815 dbus_error_name = g_dbus_error_encode_gerror (error);
3816 reply = g_dbus_message_new_method_error_literal (data->message,
3819 g_free (dbus_error_name);
3820 g_error_free (error);
3824 reply = g_dbus_message_new_method_reply (data->message);
3828 g_assert (reply != NULL);
3829 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3830 g_object_unref (reply);
3831 g_variant_unref (value);
3836 /* called with lock held */
3838 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3839 GDBusMessage *message,
3840 guint registration_id,
3841 guint subtree_registration_id,
3843 GDBusInterfaceInfo *interface_info,
3844 const GDBusInterfaceVTable *vtable,
3845 GMainContext *main_context,
3849 const char *interface_name;
3850 const char *property_name;
3851 const GDBusPropertyInfo *property_info;
3852 GSource *idle_source;
3853 PropertyData *property_data;
3854 GDBusMessage *reply;
3859 g_variant_get (g_dbus_message_get_body (message),
3864 g_variant_get (g_dbus_message_get_body (message),
3873 if (vtable == NULL || vtable->get_property == NULL)
3878 if (vtable == NULL || vtable->set_property == NULL)
3882 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3884 property_info = NULL;
3886 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3887 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3888 if (property_info == NULL)
3890 reply = g_dbus_message_new_method_error (message,
3891 "org.freedesktop.DBus.Error.InvalidArgs",
3892 _("No such property `%s'"),
3894 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3895 g_object_unref (reply);
3900 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3902 reply = g_dbus_message_new_method_error (message,
3903 "org.freedesktop.DBus.Error.InvalidArgs",
3904 _("Property `%s' is not readable"),
3906 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3907 g_object_unref (reply);
3911 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3913 reply = g_dbus_message_new_method_error (message,
3914 "org.freedesktop.DBus.Error.InvalidArgs",
3915 _("Property `%s' is not writable"),
3917 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3918 g_object_unref (reply);
3923 /* ok, got the property info - call user code in an idle handler */
3924 property_data = g_new0 (PropertyData, 1);
3925 property_data->connection = g_object_ref (connection);
3926 property_data->message = g_object_ref (message);
3927 property_data->user_data = user_data;
3928 property_data->property_name = property_name;
3929 property_data->vtable = vtable;
3930 property_data->interface_info = interface_info;
3931 property_data->property_info = property_info;
3932 property_data->registration_id = registration_id;
3933 property_data->subtree_registration_id = subtree_registration_id;
3935 idle_source = g_idle_source_new ();
3936 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3937 g_source_set_callback (idle_source,
3938 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3940 (GDestroyNotify) property_data_free);
3941 g_source_attach (idle_source, main_context);
3942 g_source_unref (idle_source);
3950 /* called with lock held */
3952 handle_getset_property (GDBusConnection *connection,
3954 GDBusMessage *message,
3957 ExportedInterface *ei;
3959 const char *interface_name;
3960 const char *property_name;
3965 g_variant_get (g_dbus_message_get_body (message),
3970 g_variant_get (g_dbus_message_get_body (message),
3976 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3977 * no such interface registered
3979 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3982 GDBusMessage *reply;
3983 reply = g_dbus_message_new_method_error (message,
3984 "org.freedesktop.DBus.Error.InvalidArgs",
3985 _("No such interface `%s'"),
3987 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3988 g_object_unref (reply);
3993 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4006 /* ---------------------------------------------------------------------------------------------------- */
4010 GDBusConnection *connection;
4011 GDBusMessage *message;
4013 const GDBusInterfaceVTable *vtable;
4014 GDBusInterfaceInfo *interface_info;
4015 guint registration_id;
4016 guint subtree_registration_id;
4017 } PropertyGetAllData;
4020 property_get_all_data_free (PropertyData *data)
4022 g_object_unref (data->connection);
4023 g_object_unref (data->message);
4027 /* called in thread where object was registered - no locks held */
4029 invoke_get_all_properties_in_idle_cb (gpointer _data)
4031 PropertyGetAllData *data = _data;
4032 GVariantBuilder builder;
4034 GDBusMessage *reply;
4037 if (has_object_been_unregistered (data->connection,
4038 data->registration_id,
4039 data->subtree_registration_id))
4041 reply = g_dbus_message_new_method_error (data->message,
4042 "org.freedesktop.DBus.Error.UnknownMethod",
4043 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4044 g_dbus_message_get_path (data->message));
4045 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4046 g_object_unref (reply);
4052 /* TODO: Right now we never fail this call - we just omit values if
4053 * a get_property() call is failing.
4055 * We could fail the whole call if just a single get_property() call
4056 * returns an error. We need clarification in the D-Bus spec about this.
4058 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4059 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4060 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4062 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4065 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4068 value = data->vtable->get_property (data->connection,
4069 g_dbus_message_get_sender (data->message),
4070 g_dbus_message_get_path (data->message),
4071 data->interface_info->name,
4072 property_info->name,
4079 if (g_variant_is_floating (value))
4080 g_variant_ref_sink (value);
4081 g_variant_builder_add (&builder,
4083 property_info->name,
4085 g_variant_unref (value);
4087 g_variant_builder_close (&builder);
4089 reply = g_dbus_message_new_method_reply (data->message);
4090 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4091 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4092 g_object_unref (reply);
4098 /* called with lock held */
4100 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4101 GDBusMessage *message,
4102 guint registration_id,
4103 guint subtree_registration_id,
4104 GDBusInterfaceInfo *interface_info,
4105 const GDBusInterfaceVTable *vtable,
4106 GMainContext *main_context,
4110 const char *interface_name;
4111 GSource *idle_source;
4112 PropertyGetAllData *property_get_all_data;
4116 g_variant_get (g_dbus_message_get_body (message),
4120 if (vtable == NULL || vtable->get_property == NULL)
4123 /* ok, got the property info - call user in an idle handler */
4124 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4125 property_get_all_data->connection = g_object_ref (connection);
4126 property_get_all_data->message = g_object_ref (message);
4127 property_get_all_data->user_data = user_data;
4128 property_get_all_data->vtable = vtable;
4129 property_get_all_data->interface_info = interface_info;
4130 property_get_all_data->registration_id = registration_id;
4131 property_get_all_data->subtree_registration_id = subtree_registration_id;
4133 idle_source = g_idle_source_new ();
4134 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4135 g_source_set_callback (idle_source,
4136 invoke_get_all_properties_in_idle_cb,
4137 property_get_all_data,
4138 (GDestroyNotify) property_get_all_data_free);
4139 g_source_attach (idle_source, main_context);
4140 g_source_unref (idle_source);
4148 /* called with lock held */
4150 handle_get_all_properties (GDBusConnection *connection,
4152 GDBusMessage *message)
4154 ExportedInterface *ei;
4156 const char *interface_name;
4160 g_variant_get (g_dbus_message_get_body (message),
4164 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4165 * no such interface registered
4167 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4170 GDBusMessage *reply;
4171 reply = g_dbus_message_new_method_error (message,
4172 "org.freedesktop.DBus.Error.InvalidArgs",
4173 _("No such interface"),
4175 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4176 g_object_unref (reply);
4181 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4193 /* ---------------------------------------------------------------------------------------------------- */
4195 static const gchar introspect_header[] =
4196 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4197 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4198 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4201 static const gchar introspect_tail[] =
4204 static const gchar introspect_standard_interfaces[] =
4205 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4206 " <method name=\"Get\">\n"
4207 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4208 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4209 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4211 " <method name=\"GetAll\">\n"
4212 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4213 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4215 " <method name=\"Set\">\n"
4216 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4217 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4218 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4220 " <signal name=\"PropertiesChanged\">\n"
4221 " <arg type=\"s\" name=\"interface_name\"/>\n"
4222 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4223 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4226 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4227 " <method name=\"Introspect\">\n"
4228 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4231 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4232 " <method name=\"Ping\"/>\n"
4233 " <method name=\"GetMachineId\">\n"
4234 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4239 introspect_append_header (GString *s)
4241 g_string_append (s, introspect_header);
4245 introspect_append_standard_interfaces (GString *s)
4247 g_string_append (s, introspect_standard_interfaces);
4251 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4253 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4259 begin = object_path + path_len;
4260 end = strchr (begin, '/');
4262 s = g_strndup (begin, end - begin);
4264 s = g_strdup (begin);
4266 if (g_hash_table_lookup (set, s) == NULL)
4267 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4273 /* TODO: we want a nicer public interface for this */
4275 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4280 GHashTableIter hash_iter;
4281 const gchar *object_path;
4287 CONNECTION_ENSURE_LOCK (connection);
4289 path_len = strlen (path);
4293 set = g_hash_table_new (g_str_hash, g_str_equal);
4295 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4296 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4297 maybe_add_path (path, path_len, object_path, set);
4299 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4300 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4301 maybe_add_path (path, path_len, object_path, set);
4303 p = g_ptr_array_new ();
4304 keys = g_hash_table_get_keys (set);
4305 for (l = keys; l != NULL; l = l->next)
4306 g_ptr_array_add (p, l->data);
4307 g_hash_table_unref (set);
4310 g_ptr_array_add (p, NULL);
4311 ret = (gchar **) g_ptr_array_free (p, FALSE);
4316 g_dbus_connection_list_registered (GDBusConnection *connection,
4320 CONNECTION_LOCK (connection);
4321 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4322 CONNECTION_UNLOCK (connection);
4326 /* called in message handler thread with lock held */
4328 handle_introspect (GDBusConnection *connection,
4330 GDBusMessage *message)
4334 GDBusMessage *reply;
4335 GHashTableIter hash_iter;
4336 ExportedInterface *ei;
4339 /* first the header with the standard interfaces */
4340 s = g_string_sized_new (sizeof (introspect_header) +
4341 sizeof (introspect_standard_interfaces) +
4342 sizeof (introspect_tail));
4343 introspect_append_header (s);
4344 introspect_append_standard_interfaces (s);
4346 /* then include the registered interfaces */
4347 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4348 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4349 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4351 /* finally include nodes registered below us */
4352 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4353 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4354 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4355 g_strfreev (registered);
4356 g_string_append (s, introspect_tail);
4358 reply = g_dbus_message_new_method_reply (message);
4359 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4360 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4361 g_object_unref (reply);
4362 g_string_free (s, TRUE);
4367 /* called in thread where object was registered - no locks held */
4369 call_in_idle_cb (gpointer user_data)
4371 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4372 GDBusInterfaceVTable *vtable;
4373 guint registration_id;
4374 guint subtree_registration_id;
4376 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4377 g_assert (vtable != NULL && vtable->method_call != NULL);
4379 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4380 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4382 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4384 subtree_registration_id))
4386 GDBusMessage *reply;
4387 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4388 "org.freedesktop.DBus.Error.UnknownMethod",
4389 _("No such interface `%s' on object at path %s"),
4390 g_dbus_method_invocation_get_interface_name (invocation),
4391 g_dbus_method_invocation_get_object_path (invocation));
4392 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4393 g_object_unref (reply);
4397 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4398 g_dbus_method_invocation_get_sender (invocation),
4399 g_dbus_method_invocation_get_object_path (invocation),
4400 g_dbus_method_invocation_get_interface_name (invocation),
4401 g_dbus_method_invocation_get_method_name (invocation),
4402 g_dbus_method_invocation_get_parameters (invocation),
4403 g_object_ref (invocation),
4404 g_dbus_method_invocation_get_user_data (invocation));
4410 /* called in message handler thread with lock held */
4412 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4413 GDBusMessage *message,
4414 guint registration_id,
4415 guint subtree_registration_id,
4416 GDBusInterfaceInfo *interface_info,
4417 const GDBusInterfaceVTable *vtable,
4418 GMainContext *main_context,
4421 GDBusMethodInvocation *invocation;
4422 const GDBusMethodInfo *method_info;
4423 GDBusMessage *reply;
4424 GVariant *parameters;
4425 GSource *idle_source;
4427 GVariantType *in_type;
4431 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4432 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4434 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4435 * error to the caller
4437 if (method_info == NULL)
4439 reply = g_dbus_message_new_method_error (message,
4440 "org.freedesktop.DBus.Error.UnknownMethod",
4441 _("No such method `%s'"),
4442 g_dbus_message_get_member (message));
4443 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4444 g_object_unref (reply);
4449 parameters = g_dbus_message_get_body (message);
4450 if (parameters == NULL)
4452 parameters = g_variant_new ("()");
4453 g_variant_ref_sink (parameters);
4457 g_variant_ref (parameters);
4460 /* Check that the incoming args are of the right type - if they are not, return
4461 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4463 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4464 if (!g_variant_is_of_type (parameters, in_type))
4468 type_string = g_variant_type_dup_string (in_type);
4470 reply = g_dbus_message_new_method_error (message,
4471 "org.freedesktop.DBus.Error.InvalidArgs",
4472 _("Type of message, `%s', does not match expected type `%s'"),
4473 g_variant_get_type_string (parameters),
4475 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4476 g_variant_type_free (in_type);
4477 g_variant_unref (parameters);
4478 g_object_unref (reply);
4479 g_free (type_string);
4483 g_variant_type_free (in_type);
4485 /* schedule the call in idle */
4486 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4487 g_dbus_message_get_path (message),
4488 g_dbus_message_get_interface (message),
4489 g_dbus_message_get_member (message),
4495 g_variant_unref (parameters);
4497 /* TODO: would be nicer with a real MethodData like we already
4498 * have PropertyData and PropertyGetAllData... */
4499 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4500 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4501 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4503 idle_source = g_idle_source_new ();
4504 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4505 g_source_set_callback (idle_source,
4509 g_source_attach (idle_source, main_context);
4510 g_source_unref (idle_source);
4518 /* ---------------------------------------------------------------------------------------------------- */
4520 /* called in message handler thread with lock held */
4522 obj_message_func (GDBusConnection *connection,
4524 GDBusMessage *message)
4526 const gchar *interface_name;
4527 const gchar *member;
4528 const gchar *signature;
4533 interface_name = g_dbus_message_get_interface (message);
4534 member = g_dbus_message_get_member (message);
4535 signature = g_dbus_message_get_signature (message);
4537 /* see if we have an interface for handling this call */
4538 if (interface_name != NULL)
4540 ExportedInterface *ei;
4541 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4544 /* we do - invoke the handler in idle in the right thread */
4546 /* handle no vtable or handler being present */
4547 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4550 handled = validate_and_maybe_schedule_method_call (connection,
4562 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4563 g_strcmp0 (member, "Introspect") == 0 &&
4564 g_strcmp0 (signature, "") == 0)
4566 handled = handle_introspect (connection, eo, message);
4569 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4570 g_strcmp0 (member, "Get") == 0 &&
4571 g_strcmp0 (signature, "ss") == 0)
4573 handled = handle_getset_property (connection, eo, message, TRUE);
4576 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4577 g_strcmp0 (member, "Set") == 0 &&
4578 g_strcmp0 (signature, "ssv") == 0)
4580 handled = handle_getset_property (connection, eo, message, FALSE);
4583 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4584 g_strcmp0 (member, "GetAll") == 0 &&
4585 g_strcmp0 (signature, "s") == 0)
4587 handled = handle_get_all_properties (connection, eo, message);
4596 * g_dbus_connection_register_object:
4597 * @connection: A #GDBusConnection.
4598 * @object_path: The object path to register at.
4599 * @interface_info: Introspection data for the interface.
4600 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4601 * @user_data: Data to pass to functions in @vtable.
4602 * @user_data_free_func: Function to call when the object path is unregistered.
4603 * @error: Return location for error or %NULL.
4605 * Registers callbacks for exported objects at @object_path with the
4606 * D-Bus interface that is described in @interface_info.
4608 * Calls to functions in @vtable (and @user_data_free_func) will
4609 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4610 * loop</link> of the thread you are calling this method from.
4612 * Note that all #GVariant values passed to functions in @vtable will match
4613 * the signature given in @interface_info - if a remote caller passes
4614 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4615 * is returned to the remote caller.
4617 * Additionally, if the remote caller attempts to invoke methods or
4618 * access properties not mentioned in @interface_info the
4619 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4620 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4621 * are returned to the caller.
4623 * It is considered a programming error if the
4624 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4625 * #GVariant of incorrect type.
4627 * If an existing callback is already registered at @object_path and
4628 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4630 * GDBus automatically implements the standard D-Bus interfaces
4631 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4632 * and org.freedesktop.Peer, so you don't have to implement those for
4633 * the objects you export. You <emphasis>can</emphasis> implement
4634 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4635 * and setting of properties asynchronously.
4637 * Note that the reference count on @interface_info will be
4638 * incremented by 1 (unless allocated statically, e.g. if the
4639 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4640 * as the object is exported. Also note that @vtable will be copied.
4642 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4644 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4645 * that can be used with g_dbus_connection_unregister_object() .
4650 g_dbus_connection_register_object (GDBusConnection *connection,
4651 const gchar *object_path,
4652 GDBusInterfaceInfo *interface_info,
4653 const GDBusInterfaceVTable *vtable,
4655 GDestroyNotify user_data_free_func,
4659 ExportedInterface *ei;
4662 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4663 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4664 g_return_val_if_fail (interface_info != NULL, 0);
4665 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4666 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4670 CONNECTION_LOCK (connection);
4672 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4675 eo = g_new0 (ExportedObject, 1);
4676 eo->object_path = g_strdup (object_path);
4677 eo->connection = connection;
4678 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4681 (GDestroyNotify) exported_interface_free);
4682 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4685 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4691 _("An object is already exported for the interface %s at %s"),
4692 interface_info->name,
4697 ei = g_new0 (ExportedInterface, 1);
4698 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4700 ei->user_data = user_data;
4701 ei->user_data_free_func = user_data_free_func;
4702 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4703 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4704 ei->interface_name = g_strdup (interface_info->name);
4705 ei->context = g_main_context_get_thread_default ();
4706 if (ei->context != NULL)
4707 g_main_context_ref (ei->context);
4709 g_hash_table_insert (eo->map_if_name_to_ei,
4710 (gpointer) ei->interface_name,
4712 g_hash_table_insert (connection->map_id_to_ei,
4713 GUINT_TO_POINTER (ei->id),
4719 CONNECTION_UNLOCK (connection);
4725 * g_dbus_connection_unregister_object:
4726 * @connection: A #GDBusConnection.
4727 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4729 * Unregisters an object.
4731 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4736 g_dbus_connection_unregister_object (GDBusConnection *connection,
4737 guint registration_id)
4739 ExportedInterface *ei;
4743 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4747 CONNECTION_LOCK (connection);
4749 ei = g_hash_table_lookup (connection->map_id_to_ei,
4750 GUINT_TO_POINTER (registration_id));
4756 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4757 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4758 /* unregister object path if we have no more exported interfaces */
4759 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4760 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4766 CONNECTION_UNLOCK (connection);
4771 /* ---------------------------------------------------------------------------------------------------- */
4774 * g_dbus_connection_emit_signal:
4775 * @connection: A #GDBusConnection.
4776 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4777 * @object_path: Path of remote object.
4778 * @interface_name: D-Bus interface to emit a signal on.
4779 * @signal_name: The name of the signal to emit.
4780 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4781 * @error: Return location for error or %NULL.
4785 * If the parameters GVariant is floating, it is consumed.
4787 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4789 * Returns: %TRUE unless @error is set.
4794 g_dbus_connection_emit_signal (GDBusConnection *connection,
4795 const gchar *destination_bus_name,
4796 const gchar *object_path,
4797 const gchar *interface_name,
4798 const gchar *signal_name,
4799 GVariant *parameters,
4802 GDBusMessage *message;
4808 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4809 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4810 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4811 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4812 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4813 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4815 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4817 _g_dbus_debug_print_lock ();
4818 g_print ("========================================================================\n"
4819 "GDBus-debug:Emission:\n"
4820 " >>>> SIGNAL EMISSION %s.%s()\n"
4822 " destination %s\n",
4823 interface_name, signal_name,
4825 destination_bus_name != NULL ? destination_bus_name : "(none)");
4826 _g_dbus_debug_print_unlock ();
4829 message = g_dbus_message_new_signal (object_path,
4833 if (destination_bus_name != NULL)
4834 g_dbus_message_set_header (message,
4835 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4836 g_variant_new_string (destination_bus_name));
4838 if (parameters != NULL)
4839 g_dbus_message_set_body (message, parameters);
4841 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4842 g_object_unref (message);
4848 add_call_flags (GDBusMessage *message,
4849 GDBusCallFlags flags)
4851 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4852 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4856 decode_method_reply (GDBusMessage *reply,
4857 const gchar *method_name,
4858 const GVariantType *reply_type,
4864 switch (g_dbus_message_get_message_type (reply))
4866 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4867 result = g_dbus_message_get_body (reply);
4870 result = g_variant_new ("()");
4871 g_variant_ref_sink (result);
4875 g_variant_ref (result);
4878 if (!g_variant_is_of_type (result, reply_type))
4880 gchar *type_string = g_variant_type_dup_string (reply_type);
4884 G_IO_ERROR_INVALID_ARGUMENT,
4885 _("Method `%s' returned type `%s', but expected `%s'"),
4886 method_name, g_variant_get_type_string (result), type_string);
4888 g_variant_unref (result);
4889 g_free (type_string);
4894 case G_DBUS_MESSAGE_TYPE_ERROR:
4895 g_dbus_message_to_gerror (reply, error);
4899 g_assert_not_reached ();
4909 GSimpleAsyncResult *simple;
4910 GVariantType *reply_type;
4911 gchar *method_name; /* for error message */
4916 g_dbus_connection_call_done (GObject *source,
4917 GAsyncResult *result,
4920 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4921 CallState *state = user_data;
4923 GDBusMessage *reply;
4927 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4931 if (G_UNLIKELY (_g_dbus_debug_call ()))
4933 _g_dbus_debug_print_lock ();
4934 g_print ("========================================================================\n"
4935 "GDBus-debug:Call:\n"
4936 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4942 g_print ("SUCCESS\n");
4946 g_print ("FAILED: %s\n",
4949 _g_dbus_debug_print_unlock ();
4955 value = decode_method_reply (reply, state->method_name,
4956 state->reply_type, &error);
4957 g_object_unref (reply);
4964 g_simple_async_result_set_from_error (state->simple, error);
4965 g_error_free (error);
4968 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4969 (GDestroyNotify) g_variant_unref);
4971 g_simple_async_result_complete (state->simple);
4972 g_variant_type_free (state->reply_type);
4973 g_object_unref (state->simple);
4974 g_free (state->method_name);
4976 g_slice_free (CallState, state);
4980 * g_dbus_connection_call:
4981 * @connection: A #GDBusConnection.
4982 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4983 * @object_path: Path of remote object.
4984 * @interface_name: D-Bus interface to invoke method on.
4985 * @method_name: The name of the method to invoke.
4986 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4987 * @reply_type: The expected type of the reply, or %NULL.
4988 * @flags: Flags from the #GDBusCallFlags enumeration.
4989 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4990 * @cancellable: A #GCancellable or %NULL.
4991 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4992 * care about the result of the method invocation.
4993 * @user_data: The data to pass to @callback.
4995 * Asynchronously invokes the @method_name method on the
4996 * @interface_name D-Bus interface on the remote object at
4997 * @object_path owned by @bus_name.
4999 * If @connection is closed then the operation will fail with
5000 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5001 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5002 * not compatible with the D-Bus protocol, the operation fails with
5003 * %G_IO_ERROR_INVALID_ARGUMENT.
5005 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5006 * error will be raised if it does not match. Said another way, if you give a @reply_type
5007 * then any non-%NULL return value will be of this type.
5009 * If the @parameters #GVariant is floating, it is consumed. This allows
5010 * convenient 'inline' use of g_variant_new(), e.g.:
5012 * g_dbus_connection_call (connection,
5013 * "org.freedesktop.StringThings",
5014 * "/org/freedesktop/StringThings",
5015 * "org.freedesktop.StringThings",
5017 * g_variant_new ("(ss)",
5021 * G_DBUS_CALL_FLAGS_NONE,
5024 * (GAsyncReadyCallback) two_strings_done,
5028 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5029 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5030 * of the thread you are calling this method from. You can then call
5031 * g_dbus_connection_call_finish() to get the result of the operation.
5032 * See g_dbus_connection_call_sync() for the synchronous version of this
5038 g_dbus_connection_call (GDBusConnection *connection,
5039 const gchar *bus_name,
5040 const gchar *object_path,
5041 const gchar *interface_name,
5042 const gchar *method_name,
5043 GVariant *parameters,
5044 const GVariantType *reply_type,
5045 GDBusCallFlags flags,
5047 GCancellable *cancellable,
5048 GAsyncReadyCallback callback,
5051 GDBusMessage *message;
5054 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5055 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5056 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5057 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5058 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5059 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5060 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5062 state = g_slice_new (CallState);
5063 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5064 callback, user_data,
5065 g_dbus_connection_call);
5066 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5068 if (reply_type == NULL)
5069 reply_type = G_VARIANT_TYPE_ANY;
5071 state->reply_type = g_variant_type_copy (reply_type);
5073 message = g_dbus_message_new_method_call (bus_name,
5077 add_call_flags (message, flags);
5078 if (parameters != NULL)
5079 g_dbus_message_set_body (message, parameters);
5081 g_dbus_connection_send_message_with_reply (connection,
5083 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5087 g_dbus_connection_call_done,
5090 if (G_UNLIKELY (_g_dbus_debug_call ()))
5092 _g_dbus_debug_print_lock ();
5093 g_print ("========================================================================\n"
5094 "GDBus-debug:Call:\n"
5095 " >>>> ASYNC %s.%s()\n"
5097 " owned by name %s (serial %d)\n",
5101 bus_name != NULL ? bus_name : "(none)",
5103 _g_dbus_debug_print_unlock ();
5106 if (message != NULL)
5107 g_object_unref (message);
5111 * g_dbus_connection_call_finish:
5112 * @connection: A #GDBusConnection.
5113 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5114 * @error: Return location for error or %NULL.
5116 * Finishes an operation started with g_dbus_connection_call().
5118 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5119 * return values. Free with g_variant_unref().
5124 g_dbus_connection_call_finish (GDBusConnection *connection,
5128 GSimpleAsyncResult *simple;
5130 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5131 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5132 g_dbus_connection_call), NULL);
5133 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5135 simple = G_SIMPLE_ASYNC_RESULT (res);
5137 if (g_simple_async_result_propagate_error (simple, error))
5140 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
5143 /* ---------------------------------------------------------------------------------------------------- */
5146 * g_dbus_connection_call_sync:
5147 * @connection: A #GDBusConnection.
5148 * @bus_name: A unique or well-known bus name.
5149 * @object_path: Path of remote object.
5150 * @interface_name: D-Bus interface to invoke method on.
5151 * @method_name: The name of the method to invoke.
5152 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5153 * @reply_type: The expected type of the reply, or %NULL.
5154 * @flags: Flags from the #GDBusCallFlags enumeration.
5155 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
5156 * @cancellable: A #GCancellable or %NULL.
5157 * @error: Return location for error or %NULL.
5159 * Synchronously invokes the @method_name method on the
5160 * @interface_name D-Bus interface on the remote object at
5161 * @object_path owned by @bus_name.
5163 * If @connection is closed then the operation will fail with
5164 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5165 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5166 * contains a value not compatible with the D-Bus protocol, the operation
5167 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5169 * If @reply_type is non-%NULL then the reply will be checked for having
5170 * this type and an error will be raised if it does not match. Said
5171 * another way, if you give a @reply_type then any non-%NULL return
5172 * value will be of this type.
5174 * If the @parameters #GVariant is floating, it is consumed.
5175 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5177 * g_dbus_connection_call_sync (connection,
5178 * "org.freedesktop.StringThings",
5179 * "/org/freedesktop/StringThings",
5180 * "org.freedesktop.StringThings",
5182 * g_variant_new ("(ss)",
5186 * G_DBUS_CALL_FLAGS_NONE,
5192 * The calling thread is blocked until a reply is received. See
5193 * g_dbus_connection_call() for the asynchronous version of
5196 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5197 * return values. Free with g_variant_unref().
5202 g_dbus_connection_call_sync (GDBusConnection *connection,
5203 const gchar *bus_name,
5204 const gchar *object_path,
5205 const gchar *interface_name,
5206 const gchar *method_name,
5207 GVariant *parameters,
5208 const GVariantType *reply_type,
5209 GDBusCallFlags flags,
5211 GCancellable *cancellable,
5214 GDBusMessage *message;
5215 GDBusMessage *reply;
5217 GError *local_error;
5223 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5224 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5225 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5226 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5227 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5228 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5229 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5231 if (reply_type == NULL)
5232 reply_type = G_VARIANT_TYPE_ANY;
5234 message = g_dbus_message_new_method_call (bus_name,
5238 add_call_flags (message, flags);
5239 if (parameters != NULL)
5240 g_dbus_message_set_body (message, parameters);
5242 if (G_UNLIKELY (_g_dbus_debug_call ()))
5244 _g_dbus_debug_print_lock ();
5245 g_print ("========================================================================\n"
5246 "GDBus-debug:Call:\n"
5247 " >>>> SYNC %s.%s()\n"
5249 " owned by name %s\n",
5253 bus_name != NULL ? bus_name : "(none)");
5254 _g_dbus_debug_print_unlock ();
5258 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5260 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5262 NULL, /* volatile guint32 *out_serial */
5266 if (G_UNLIKELY (_g_dbus_debug_call ()))
5268 _g_dbus_debug_print_lock ();
5269 g_print ("========================================================================\n"
5270 "GDBus-debug:Call:\n"
5271 " <<<< SYNC COMPLETE %s.%s()\n"
5277 g_print ("SUCCESS\n");
5281 g_print ("FAILED: %s\n",
5282 local_error->message);
5284 _g_dbus_debug_print_unlock ();
5290 *error = local_error;
5292 g_error_free (local_error);
5296 result = decode_method_reply (reply, method_name, reply_type, error);
5299 if (message != NULL)
5300 g_object_unref (message);
5302 g_object_unref (reply);
5307 /* ---------------------------------------------------------------------------------------------------- */
5309 struct ExportedSubtree
5313 GDBusConnection *connection;
5314 GDBusSubtreeVTable *vtable;
5315 GDBusSubtreeFlags flags;
5317 GMainContext *context;
5319 GDestroyNotify user_data_free_func;
5323 exported_subtree_free (ExportedSubtree *es)
5325 call_destroy_notify (es->context,
5326 es->user_data_free_func,
5329 if (es->context != NULL)
5330 g_main_context_unref (es->context);
5332 _g_dbus_subtree_vtable_free (es->vtable);
5333 g_free (es->object_path);
5337 /* called without lock held */
5339 handle_subtree_introspect (GDBusConnection *connection,
5340 ExportedSubtree *es,
5341 GDBusMessage *message)
5345 GDBusMessage *reply;
5348 const gchar *sender;
5349 const gchar *requested_object_path;
5350 const gchar *requested_node;
5351 GDBusInterfaceInfo **interfaces;
5353 gchar **subnode_paths;
5357 requested_object_path = g_dbus_message_get_path (message);
5358 sender = g_dbus_message_get_sender (message);
5359 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5361 s = g_string_new (NULL);
5362 introspect_append_header (s);
5364 /* Strictly we don't need the children in dynamic mode, but we avoid the
5365 * conditionals to preserve code clarity
5367 children = es->vtable->enumerate (es->connection,
5374 requested_node = strrchr (requested_object_path, '/') + 1;
5376 /* Assert existence of object if we are not dynamic */
5377 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5378 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5383 requested_node = NULL;
5386 interfaces = es->vtable->introspect (es->connection,
5391 if (interfaces != NULL)
5393 introspect_append_standard_interfaces (s);
5395 for (n = 0; interfaces[n] != NULL; n++)
5397 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5398 g_dbus_interface_info_unref (interfaces[n]);
5400 g_free (interfaces);
5403 /* then include <node> entries from the Subtree for the root */
5406 for (n = 0; children != NULL && children[n] != NULL; n++)
5407 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5410 /* finally include nodes registered below us */
5411 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5412 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5413 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5414 g_strfreev (subnode_paths);
5416 g_string_append (s, "</node>\n");
5418 reply = g_dbus_message_new_method_reply (message);
5419 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5420 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5421 g_object_unref (reply);
5426 g_string_free (s, TRUE);
5427 g_strfreev (children);
5431 /* called without lock held */
5433 handle_subtree_method_invocation (GDBusConnection *connection,
5434 ExportedSubtree *es,
5435 GDBusMessage *message)
5438 const gchar *sender;
5439 const gchar *interface_name;
5440 const gchar *member;
5441 const gchar *signature;
5442 const gchar *requested_object_path;
5443 const gchar *requested_node;
5445 GDBusInterfaceInfo *interface_info;
5446 const GDBusInterfaceVTable *interface_vtable;
5447 gpointer interface_user_data;
5449 GDBusInterfaceInfo **interfaces;
5450 gboolean is_property_get;
5451 gboolean is_property_set;
5452 gboolean is_property_get_all;
5457 requested_object_path = g_dbus_message_get_path (message);
5458 sender = g_dbus_message_get_sender (message);
5459 interface_name = g_dbus_message_get_interface (message);
5460 member = g_dbus_message_get_member (message);
5461 signature = g_dbus_message_get_signature (message);
5462 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5464 is_property_get = FALSE;
5465 is_property_set = FALSE;
5466 is_property_get_all = FALSE;
5467 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5469 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5470 is_property_get = TRUE;
5471 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5472 is_property_set = TRUE;
5473 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5474 is_property_get_all = TRUE;
5479 requested_node = strrchr (requested_object_path, '/') + 1;
5481 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5483 /* We don't want to dispatch to unenumerated
5484 * nodes, so ensure that the child exists.
5489 children = es->vtable->enumerate (es->connection,
5494 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5495 g_strfreev (children);
5503 requested_node = NULL;
5506 /* get introspection data for the node */
5507 interfaces = es->vtable->introspect (es->connection,
5509 requested_object_path,
5513 if (interfaces == NULL)
5516 interface_info = NULL;
5517 for (n = 0; interfaces[n] != NULL; n++)
5519 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5520 interface_info = interfaces[n];
5523 /* dispatch the call if the user wants to handle it */
5524 if (interface_info != NULL)
5526 /* figure out where to dispatch the method call */
5527 interface_user_data = NULL;
5528 interface_vtable = es->vtable->dispatch (es->connection,
5533 &interface_user_data,
5535 if (interface_vtable == NULL)
5538 CONNECTION_LOCK (connection);
5539 handled = validate_and_maybe_schedule_method_call (es->connection,
5546 interface_user_data);
5547 CONNECTION_UNLOCK (connection);
5549 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5550 else if (is_property_get || is_property_set || is_property_get_all)
5552 if (is_property_get)
5553 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5554 else if (is_property_set)
5555 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5556 else if (is_property_get_all)
5557 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5559 g_assert_not_reached ();
5561 /* see if the object supports this interface at all */
5562 for (n = 0; interfaces[n] != NULL; n++)
5564 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5565 interface_info = interfaces[n];
5568 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5569 * claims it won't support the interface
5571 if (interface_info == NULL)
5573 GDBusMessage *reply;
5574 reply = g_dbus_message_new_method_error (message,
5575 "org.freedesktop.DBus.Error.InvalidArgs",
5576 _("No such interface `%s'"),
5578 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5579 g_object_unref (reply);
5584 /* figure out where to dispatch the property get/set/getall calls */
5585 interface_user_data = NULL;
5586 interface_vtable = es->vtable->dispatch (es->connection,
5591 &interface_user_data,
5593 if (interface_vtable == NULL)
5595 g_warning ("The subtree introspection function indicates that '%s' "
5596 "is a valid interface name, but calling the dispatch "
5597 "function on that interface gave us NULL", interface_name);
5601 if (is_property_get || is_property_set)
5603 CONNECTION_LOCK (connection);
5604 handled = validate_and_maybe_schedule_property_getset (es->connection,
5612 interface_user_data);
5613 CONNECTION_UNLOCK (connection);
5615 else if (is_property_get_all)
5617 CONNECTION_LOCK (connection);
5618 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5625 interface_user_data);
5626 CONNECTION_UNLOCK (connection);
5631 if (interfaces != NULL)
5633 for (n = 0; interfaces[n] != NULL; n++)
5634 g_dbus_interface_info_unref (interfaces[n]);
5635 g_free (interfaces);
5643 GDBusMessage *message;
5644 ExportedSubtree *es;
5645 } SubtreeDeferredData;
5648 subtree_deferred_data_free (SubtreeDeferredData *data)
5650 g_object_unref (data->message);
5654 /* called without lock held in the thread where the caller registered the subtree */
5656 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5658 SubtreeDeferredData *data = _data;
5663 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5664 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5665 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5666 handled = handle_subtree_introspect (data->es->connection,
5670 handled = handle_subtree_method_invocation (data->es->connection,
5676 CONNECTION_LOCK (data->es->connection);
5677 handled = handle_generic_unlocked (data->es->connection, data->message);
5678 CONNECTION_UNLOCK (data->es->connection);
5681 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5684 GDBusMessage *reply;
5685 reply = g_dbus_message_new_method_error (data->message,
5686 "org.freedesktop.DBus.Error.UnknownMethod",
5687 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5688 g_dbus_message_get_member (data->message),
5689 g_dbus_message_get_interface (data->message),
5690 g_dbus_message_get_signature (data->message));
5691 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5692 g_object_unref (reply);
5698 /* called in message handler thread with lock held */
5700 subtree_message_func (GDBusConnection *connection,
5701 ExportedSubtree *es,
5702 GDBusMessage *message)
5704 GSource *idle_source;
5705 SubtreeDeferredData *data;
5707 data = g_new0 (SubtreeDeferredData, 1);
5708 data->message = g_object_ref (message);
5711 /* defer this call to an idle handler in the right thread */
5712 idle_source = g_idle_source_new ();
5713 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5714 g_source_set_callback (idle_source,
5715 process_subtree_vtable_message_in_idle_cb,
5717 (GDestroyNotify) subtree_deferred_data_free);
5718 g_source_attach (idle_source, es->context);
5719 g_source_unref (idle_source);
5721 /* since we own the entire subtree, handlers for objects not in the subtree have been
5722 * tried already by libdbus-1 - so we just need to ensure that we're always going
5723 * to reply to the message
5729 * g_dbus_connection_register_subtree:
5730 * @connection: A #GDBusConnection.
5731 * @object_path: The object path to register the subtree at.
5732 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5733 * @flags: Flags used to fine tune the behavior of the subtree.
5734 * @user_data: Data to pass to functions in @vtable.
5735 * @user_data_free_func: Function to call when the subtree is unregistered.
5736 * @error: Return location for error or %NULL.
5738 * Registers a whole subtree of <quote>dynamic</quote> objects.
5740 * The @enumerate and @introspection functions in @vtable are used to
5741 * convey, to remote callers, what nodes exist in the subtree rooted
5744 * When handling remote calls into any node in the subtree, first the
5745 * @enumerate function is used to check if the node exists. If the node exists
5746 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5747 * the @introspection function is used to check if the node supports the
5748 * requested method. If so, the @dispatch function is used to determine
5749 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5750 * #gpointer will be used to call into the interface vtable for processing
5753 * All calls into user-provided code will be invoked in the <link
5754 * linkend="g-main-context-push-thread-default">thread-default main
5755 * loop</link> of the thread you are calling this method from.
5757 * If an existing subtree is already registered at @object_path or
5758 * then @error is set to #G_IO_ERROR_EXISTS.
5760 * Note that it is valid to register regular objects (using
5761 * g_dbus_connection_register_object()) in a subtree registered with
5762 * g_dbus_connection_register_subtree() - if so, the subtree handler
5763 * is tried as the last resort. One way to think about a subtree
5764 * handler is to consider it a <quote>fallback handler</quote>
5765 * for object paths not registered via g_dbus_connection_register_object()
5766 * or other bindings.
5768 * Note that @vtable will be copied so you cannot change it after
5771 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5773 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5774 * that can be used with g_dbus_connection_unregister_subtree() .
5779 g_dbus_connection_register_subtree (GDBusConnection *connection,
5780 const gchar *object_path,
5781 const GDBusSubtreeVTable *vtable,
5782 GDBusSubtreeFlags flags,
5784 GDestroyNotify user_data_free_func,
5788 ExportedSubtree *es;
5790 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5791 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5792 g_return_val_if_fail (vtable != NULL, 0);
5793 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5797 CONNECTION_LOCK (connection);
5799 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5805 _("A subtree is already exported for %s"),
5810 es = g_new0 (ExportedSubtree, 1);
5811 es->object_path = g_strdup (object_path);
5812 es->connection = connection;
5814 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5816 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5817 es->user_data = user_data;
5818 es->user_data_free_func = user_data_free_func;
5819 es->context = g_main_context_get_thread_default ();
5820 if (es->context != NULL)
5821 g_main_context_ref (es->context);
5823 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5824 g_hash_table_insert (connection->map_id_to_es,
5825 GUINT_TO_POINTER (es->id),
5831 CONNECTION_UNLOCK (connection);
5836 /* ---------------------------------------------------------------------------------------------------- */
5839 * g_dbus_connection_unregister_subtree:
5840 * @connection: A #GDBusConnection.
5841 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5843 * Unregisters a subtree.
5845 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5850 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5851 guint registration_id)
5853 ExportedSubtree *es;
5856 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5860 CONNECTION_LOCK (connection);
5862 es = g_hash_table_lookup (connection->map_id_to_es,
5863 GUINT_TO_POINTER (registration_id));
5867 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5868 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5873 CONNECTION_UNLOCK (connection);
5878 /* ---------------------------------------------------------------------------------------------------- */
5880 /* must be called with lock held */
5882 handle_generic_ping_unlocked (GDBusConnection *connection,
5883 const gchar *object_path,
5884 GDBusMessage *message)
5886 GDBusMessage *reply;
5887 reply = g_dbus_message_new_method_reply (message);
5888 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5889 g_object_unref (reply);
5892 /* must be called with lock held */
5894 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5895 const gchar *object_path,
5896 GDBusMessage *message)
5898 GDBusMessage *reply;
5901 if (connection->machine_id == NULL)
5906 connection->machine_id = _g_dbus_get_machine_id (&error);
5907 if (connection->machine_id == NULL)
5909 reply = g_dbus_message_new_method_error_literal (message,
5910 "org.freedesktop.DBus.Error.Failed",
5912 g_error_free (error);
5918 reply = g_dbus_message_new_method_reply (message);
5919 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5921 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5922 g_object_unref (reply);
5925 /* must be called with lock held */
5927 handle_generic_introspect_unlocked (GDBusConnection *connection,
5928 const gchar *object_path,
5929 GDBusMessage *message)
5934 GDBusMessage *reply;
5936 /* first the header */
5937 s = g_string_new (NULL);
5938 introspect_append_header (s);
5940 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5941 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5942 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5943 g_strfreev (registered);
5944 g_string_append (s, "</node>\n");
5946 reply = g_dbus_message_new_method_reply (message);
5947 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5948 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5949 g_object_unref (reply);
5950 g_string_free (s, TRUE);
5953 /* must be called with lock held */
5955 handle_generic_unlocked (GDBusConnection *connection,
5956 GDBusMessage *message)
5959 const gchar *interface_name;
5960 const gchar *member;
5961 const gchar *signature;
5964 CONNECTION_ENSURE_LOCK (connection);
5968 interface_name = g_dbus_message_get_interface (message);
5969 member = g_dbus_message_get_member (message);
5970 signature = g_dbus_message_get_signature (message);
5971 path = g_dbus_message_get_path (message);
5973 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5974 g_strcmp0 (member, "Introspect") == 0 &&
5975 g_strcmp0 (signature, "") == 0)
5977 handle_generic_introspect_unlocked (connection, path, message);
5980 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5981 g_strcmp0 (member, "Ping") == 0 &&
5982 g_strcmp0 (signature, "") == 0)
5984 handle_generic_ping_unlocked (connection, path, message);
5987 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5988 g_strcmp0 (member, "GetMachineId") == 0 &&
5989 g_strcmp0 (signature, "") == 0)
5991 handle_generic_get_machine_id_unlocked (connection, path, message);
5998 /* ---------------------------------------------------------------------------------------------------- */
6000 /* called in message handler thread with lock held */
6002 distribute_method_call (GDBusConnection *connection,
6003 GDBusMessage *message)
6005 GDBusMessage *reply;
6007 ExportedSubtree *es;
6008 const gchar *object_path;
6009 const gchar *interface_name;
6010 const gchar *member;
6011 const gchar *signature;
6013 gchar *subtree_path;
6016 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6018 interface_name = g_dbus_message_get_interface (message);
6019 member = g_dbus_message_get_member (message);
6020 signature = g_dbus_message_get_signature (message);
6021 path = g_dbus_message_get_path (message);
6022 subtree_path = g_strdup (path);
6023 needle = strrchr (subtree_path, '/');
6024 if (needle != NULL && needle != subtree_path)
6030 g_free (subtree_path);
6031 subtree_path = NULL;
6035 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6037 _g_dbus_debug_print_lock ();
6038 g_print ("========================================================================\n"
6039 "GDBus-debug:Incoming:\n"
6040 " <<<< METHOD INVOCATION %s.%s()\n"
6042 " invoked by name %s\n"
6044 interface_name, member,
6046 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6047 g_dbus_message_get_serial (message));
6048 _g_dbus_debug_print_unlock ();
6052 g_debug ("interface = `%s'", interface_name);
6053 g_debug ("member = `%s'", member);
6054 g_debug ("signature = `%s'", signature);
6055 g_debug ("path = `%s'", path);
6056 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
6059 object_path = g_dbus_message_get_path (message);
6060 g_assert (object_path != NULL);
6062 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6065 if (obj_message_func (connection, eo, message))
6069 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6072 if (subtree_message_func (connection, es, message))
6076 if (subtree_path != NULL)
6078 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6081 if (subtree_message_func (connection, es, message))
6086 if (handle_generic_unlocked (connection, message))
6089 /* if we end up here, the message has not been not handled - so return an error saying this */
6090 reply = g_dbus_message_new_method_error (message,
6091 "org.freedesktop.DBus.Error.UnknownMethod",
6092 _("No such interface `%s' on object at path %s"),
6095 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6096 g_object_unref (reply);
6099 g_free (subtree_path);
6102 /* ---------------------------------------------------------------------------------------------------- */
6104 static GDBusConnection **
6105 message_bus_get_singleton (GBusType bus_type,
6108 GDBusConnection **ret;
6109 const gchar *starter_bus;
6115 case G_BUS_TYPE_SESSION:
6116 ret = &the_session_bus;
6119 case G_BUS_TYPE_SYSTEM:
6120 ret = &the_system_bus;
6123 case G_BUS_TYPE_STARTER:
6124 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6125 if (g_strcmp0 (starter_bus, "session") == 0)
6127 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6130 else if (g_strcmp0 (starter_bus, "system") == 0)
6132 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6137 if (starter_bus != NULL)
6141 G_IO_ERROR_INVALID_ARGUMENT,
6142 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6143 " - unknown value `%s'"),
6148 g_set_error_literal (error,
6150 G_IO_ERROR_INVALID_ARGUMENT,
6151 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6152 "variable is not set"));
6158 g_assert_not_reached ();
6166 static GDBusConnection *
6167 get_uninitialized_connection (GBusType bus_type,
6168 GCancellable *cancellable,
6171 GDBusConnection **singleton;
6172 GDBusConnection *ret;
6176 G_LOCK (message_bus_lock);
6177 singleton = message_bus_get_singleton (bus_type, error);
6178 if (singleton == NULL)
6181 if (*singleton == NULL)
6184 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6185 if (address == NULL)
6187 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6189 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6190 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6191 "exit-on-close", TRUE,
6197 ret = g_object_ref (*singleton);
6200 g_assert (ret != NULL);
6203 G_UNLOCK (message_bus_lock);
6209 * @bus_type: A #GBusType.
6210 * @cancellable: A #GCancellable or %NULL.
6211 * @error: Return location for error or %NULL.
6213 * Synchronously connects to the message bus specified by @bus_type.
6214 * Note that the returned object may shared with other callers,
6215 * e.g. if two separate parts of a process calls this function with
6216 * the same @bus_type, they will share the same object.
6218 * This is a synchronous failable function. See g_bus_get() and
6219 * g_bus_get_finish() for the asynchronous version.
6221 * The returned object is a singleton, that is, shared with other
6222 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6223 * event that you need a private message bus connection, use
6224 * g_dbus_address_get_for_bus_sync() and
6225 * g_dbus_connection_new_for_address().
6227 * Note that the returned #GDBusConnection object will (usually) have
6228 * the #GDBusConnection:exit-on-close property set to %TRUE.
6230 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6235 g_bus_get_sync (GBusType bus_type,
6236 GCancellable *cancellable,
6239 GDBusConnection *connection;
6241 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6243 connection = get_uninitialized_connection (bus_type, cancellable, error);
6244 if (connection == NULL)
6247 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6249 g_object_unref (connection);
6258 bus_get_async_initable_cb (GObject *source_object,
6262 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6266 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6270 g_assert (error != NULL);
6271 g_simple_async_result_set_from_error (simple, error);
6272 g_error_free (error);
6273 g_object_unref (source_object);
6277 g_simple_async_result_set_op_res_gpointer (simple,
6281 g_simple_async_result_complete_in_idle (simple);
6282 g_object_unref (simple);
6287 * @bus_type: A #GBusType.
6288 * @cancellable: A #GCancellable or %NULL.
6289 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6290 * @user_data: The data to pass to @callback.
6292 * Asynchronously connects to the message bus specified by @bus_type.
6294 * When the operation is finished, @callback will be invoked. You can
6295 * then call g_bus_get_finish() to get the result of the operation.
6297 * This is a asynchronous failable function. See g_bus_get_sync() for
6298 * the synchronous version.
6303 g_bus_get (GBusType bus_type,
6304 GCancellable *cancellable,
6305 GAsyncReadyCallback callback,
6308 GDBusConnection *connection;
6309 GSimpleAsyncResult *simple;
6312 simple = g_simple_async_result_new (NULL,
6318 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6319 if (connection == NULL)
6321 g_assert (error != NULL);
6322 g_simple_async_result_set_from_error (simple, error);
6323 g_error_free (error);
6324 g_simple_async_result_complete_in_idle (simple);
6325 g_object_unref (simple);
6329 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6332 bus_get_async_initable_cb,
6339 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6340 * @error: Return location for error or %NULL.
6342 * Finishes an operation started with g_bus_get().
6344 * The returned object is a singleton, that is, shared with other
6345 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6346 * event that you need a private message bus connection, use
6347 * g_dbus_address_get_for_bus() and
6348 * g_dbus_connection_new_for_address().
6350 * Note that the returned #GDBusConnection object will (usually) have
6351 * the #GDBusConnection:exit-on-close property set to %TRUE.
6353 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6358 g_bus_get_finish (GAsyncResult *res,
6361 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6363 GDBusConnection *ret;
6365 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6367 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6371 if (g_simple_async_result_propagate_error (simple, error))
6374 object = g_simple_async_result_get_op_res_gpointer (simple);
6375 g_assert (object != NULL);
6376 ret = g_object_ref (G_DBUS_CONNECTION (object));
6382 /* ---------------------------------------------------------------------------------------------------- */