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 * - Validate all data (e.g. UTF-8) and check all the required D-Bus headers
27 * are present and forbidden ones aren't
28 * - When writing: g_dbus_message_to_blob()
29 * - When reading: g_dbus_message_new_from_blob()
31 * - would be nice to expose GDBusAuthMechanism and an extension point
33 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
34 * the mechanism VFuncs need to be able to set an error.
36 * - Need to document other mechanisms/sources for determining the D-Bus
37 * address of a well-known bus.
39 * - e.g. on Win32 we need code like from here
41 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
43 * that was never copied over here because it originally was copy-paste
44 * from the GPLv2 / AFL 2.1 libdbus sources.
46 * - on OS X we need to look in launchd for the address
48 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
50 * - on X11 we need to look in a X11 property on the X server
51 * - (we can also just use dbus-launch(1) from the D-Bus
54 * - (ideally) this requires D-Bus spec work because none of
55 * this has never really been specced out properly (excect
58 * - Related to the above, we also need to be able to launch a message bus
59 * instance.... Since we don't want to write our own bus daemon we should
60 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
62 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
63 * to specify where the nonce is stored. This will allow people to use
64 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
65 * to easily acheive secure RPC via nonce-tcp.
67 * - need to expose an extension point for resolving D-Bus address and
68 * turning them into GIOStream objects. This will allow us to implement
69 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
71 * - see g_dbus_address_connect() in gdbusaddress.c
73 * - would be cute to use kernel-specific APIs to resolve fds for
74 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
76 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
78 * maybe we can show more information about what fd 21 really is.
79 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
80 * Initial experiments on Linux 2.6 suggests that the symlink looks
85 * e.g. not of much use.
87 * - GDBus High-Level docs
88 * - Proxy: properties, signals...
89 * - Connection: IOStream based, ::close, connection setup steps
90 * mainloop integration, threading
91 * - Differences from libdbus (extend "Migrating from")
92 * - the message handling thread
93 * - Using GVariant instead of GValue
94 * - Explain why the high-level API is a good thing and what
95 * kind of pitfalls it avoids
96 * - Export objects before claiming names
97 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
104 #include <sys/types.h>
109 #include "gdbusauth.h"
110 #include "gdbusutils.h"
111 #include "gdbusaddress.h"
112 #include "gdbusmessage.h"
113 #include "gdbusconnection.h"
114 #include "gdbuserror.h"
115 #include "gioenumtypes.h"
116 #include "gdbusintrospection.h"
117 #include "gdbusmethodinvocation.h"
118 #include "gdbusprivate.h"
119 #include "gdbusauthobserver.h"
120 #include "gio-marshal.h"
121 #include "ginitable.h"
122 #include "gasyncinitable.h"
123 #include "giostream.h"
124 #include "gasyncresult.h"
125 #include "gsimpleasyncresult.h"
128 #include "gunixconnection.h"
129 #include "gunixfdmessage.h"
132 #include "glibintl.h"
133 #include "gioalias.h"
136 * SECTION:gdbusconnection
137 * @short_description: D-Bus Connections
138 * @include: gio/gio.h
140 * The #GDBusConnection type is used for D-Bus connections to remote
141 * peers such as a message buses. It is a low-level API that offers a
142 * lot of flexibility. For instance, it lets you establish a connection
143 * over any transport that can by represented as an #GIOStream.
145 * This class is rarely used directly in D-Bus clients. If you are writing
146 * an D-Bus client, it is often easier to use the g_bus_own_name(),
147 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
149 * <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>
151 * <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>
153 * <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>
155 * <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>
158 /* ---------------------------------------------------------------------------------------------------- */
160 G_LOCK_DEFINE_STATIC (message_bus_lock);
162 static GDBusConnection *the_session_bus = NULL;
163 static GDBusConnection *the_system_bus = NULL;
165 /* ---------------------------------------------------------------------------------------------------- */
168 _g_strv_has_string (const gchar* const *haystack,
173 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
175 if (g_strcmp0 (haystack[n], needle) == 0)
181 /* ---------------------------------------------------------------------------------------------------- */
184 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
186 // TODO: for some reason this doesn't work on Windows
187 #define CONNECTION_ENSURE_LOCK(obj) do { \
188 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
190 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
191 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
196 #define CONNECTION_LOCK(obj) do { \
197 g_mutex_lock ((obj)->priv->lock); \
200 #define CONNECTION_UNLOCK(obj) do { \
201 g_mutex_unlock ((obj)->priv->lock); \
204 struct _GDBusConnectionPrivate
206 /* ------------------------------------------------------------------------ */
207 /* -- General object state ------------------------------------------------ */
208 /* ------------------------------------------------------------------------ */
210 /* object-wide lock */
213 /* A lock used in the init() method of the GInitable interface - see comments
214 * in initable_init() for why a separate lock is needed
218 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
219 * someone calls org.freedesktop.DBus.GetMachineId()
223 /* The underlying stream used for communication */
226 /* The object used for authentication (if any) */
229 /* Set to TRUE if the connection has been closed */
232 /* Last serial used */
235 /* The object used to send/receive message */
238 /* If connected to a message bus, this contains the unique name assigned to
239 * us by the bus (e.g. ":1.42")
241 gchar *bus_unique_name;
243 /* The GUID returned by the other side if we authenticed as a client or
244 * the GUID to use if authenticating as a server
248 /* set to TRUE exactly when initable_init() has finished running */
249 gboolean is_initialized;
251 /* If the connection could not be established during initable_init(), this GError will set */
252 GError *initialization_error;
254 /* The result of g_main_context_get_thread_default() when the object
255 * was created (the GObject _init() function) - this is used for delivery
256 * of the :closed GObject signal.
258 GMainContext *main_context_at_construction;
260 /* construct properties */
262 GDBusConnectionFlags flags;
264 /* Map used for managing method replies */
265 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
267 /* Maps used for managing signal subscription */
268 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
269 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
270 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
272 /* Maps used for managing exported objects and subtrees */
273 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
274 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
275 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
276 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
278 /* Structure used for message filters */
281 /* Whether to exit on close */
282 gboolean exit_on_close;
284 /* Capabilities negotiated during authentication */
285 GDBusCapabilityFlags capabilities;
287 GDBusAuthObserver *authentication_observer;
288 GCredentials *crendentials;
291 typedef struct ExportedObject ExportedObject;
292 static void exported_object_free (ExportedObject *eo);
294 typedef struct ExportedSubtree ExportedSubtree;
295 static void exported_subtree_free (ExportedSubtree *es);
313 PROP_CAPABILITY_FLAGS,
314 PROP_AUTHENTICATION_OBSERVER,
317 static void distribute_signals (GDBusConnection *connection,
318 GDBusMessage *message);
320 static void distribute_method_call (GDBusConnection *connection,
321 GDBusMessage *message);
323 static gboolean handle_generic_unlocked (GDBusConnection *connection,
324 GDBusMessage *message);
327 static void purge_all_signal_subscriptions (GDBusConnection *connection);
328 static void purge_all_filters (GDBusConnection *connection);
330 #define _G_ENSURE_LOCK(name) do { \
331 if (G_UNLIKELY (G_TRYLOCK(name))) \
333 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
334 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
338 static guint signals[LAST_SIGNAL] = { 0 };
340 static void initable_iface_init (GInitableIface *initable_iface);
341 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
343 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
344 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
345 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
349 g_dbus_connection_dispose (GObject *object)
351 GDBusConnection *connection = G_DBUS_CONNECTION (object);
353 G_LOCK (message_bus_lock);
354 //g_debug ("disposing %p", connection);
355 if (connection == the_session_bus)
357 the_session_bus = NULL;
359 else if (connection == the_system_bus)
361 the_system_bus = NULL;
363 if (connection->priv->worker != NULL)
365 _g_dbus_worker_stop (connection->priv->worker);
366 connection->priv->worker = NULL;
368 G_UNLOCK (message_bus_lock);
370 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
371 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
375 g_dbus_connection_finalize (GObject *object)
377 GDBusConnection *connection = G_DBUS_CONNECTION (object);
379 if (connection->priv->authentication_observer != NULL)
380 g_object_unref (connection->priv->authentication_observer);
382 if (connection->priv->auth != NULL)
383 g_object_unref (connection->priv->auth);
385 //g_debug ("finalizing %p", connection);
386 if (connection->priv->stream != NULL)
388 /* We don't really care if closing the stream succeeds or not */
389 g_io_stream_close_async (connection->priv->stream,
391 NULL, /* GCancellable */
392 NULL, /* GAsyncReadyCallback */
393 NULL); /* userdata */
394 g_object_unref (connection->priv->stream);
395 connection->priv->stream = NULL;
398 g_free (connection->priv->address);
400 g_free (connection->priv->guid);
401 g_free (connection->priv->bus_unique_name);
403 if (connection->priv->initialization_error != NULL)
404 g_error_free (connection->priv->initialization_error);
406 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
408 purge_all_signal_subscriptions (connection);
409 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
410 g_hash_table_unref (connection->priv->map_id_to_signal_data);
411 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
413 g_hash_table_unref (connection->priv->map_id_to_ei);
414 g_hash_table_unref (connection->priv->map_object_path_to_eo);
415 g_hash_table_unref (connection->priv->map_id_to_es);
416 g_hash_table_unref (connection->priv->map_object_path_to_es);
418 purge_all_filters (connection);
419 g_ptr_array_unref (connection->priv->filters);
421 if (connection->priv->main_context_at_construction != NULL)
422 g_main_context_unref (connection->priv->main_context_at_construction);
424 g_free (connection->priv->machine_id);
426 g_mutex_free (connection->priv->init_lock);
427 g_mutex_free (connection->priv->lock);
429 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
433 g_dbus_connection_get_property (GObject *object,
438 GDBusConnection *connection = G_DBUS_CONNECTION (object);
443 g_value_set_object (value, g_dbus_connection_get_stream (connection));
447 g_value_set_string (value, g_dbus_connection_get_guid (connection));
450 case PROP_UNIQUE_NAME:
451 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
455 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
458 case PROP_EXIT_ON_CLOSE:
459 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
462 case PROP_CAPABILITY_FLAGS:
463 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
467 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
473 g_dbus_connection_set_property (GObject *object,
478 GDBusConnection *connection = G_DBUS_CONNECTION (object);
483 connection->priv->stream = g_value_dup_object (value);
487 connection->priv->guid = g_value_dup_string (value);
491 connection->priv->address = g_value_dup_string (value);
495 connection->priv->flags = g_value_get_flags (value);
498 case PROP_EXIT_ON_CLOSE:
499 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
502 case PROP_AUTHENTICATION_OBSERVER:
503 connection->priv->authentication_observer = g_value_dup_object (value);
507 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
513 g_dbus_connection_real_closed (GDBusConnection *connection,
514 gboolean remote_peer_vanished,
517 if (remote_peer_vanished && connection->priv->exit_on_close)
519 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
525 g_dbus_connection_class_init (GDBusConnectionClass *klass)
527 GObjectClass *gobject_class;
529 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
531 gobject_class = G_OBJECT_CLASS (klass);
533 gobject_class->finalize = g_dbus_connection_finalize;
534 gobject_class->dispose = g_dbus_connection_dispose;
535 gobject_class->set_property = g_dbus_connection_set_property;
536 gobject_class->get_property = g_dbus_connection_get_property;
538 klass->closed = g_dbus_connection_real_closed;
541 * GDBusConnection:stream:
543 * The underlying #GIOStream used for I/O.
547 g_object_class_install_property (gobject_class,
549 g_param_spec_object ("stream",
551 P_("The underlying streams used for I/O"),
555 G_PARAM_CONSTRUCT_ONLY |
556 G_PARAM_STATIC_NAME |
557 G_PARAM_STATIC_BLURB |
558 G_PARAM_STATIC_NICK));
561 * GDBusConnection:address:
563 * A D-Bus address specifying potential endpoints that can be used
564 * when establishing the connection.
568 g_object_class_install_property (gobject_class,
570 g_param_spec_string ("address",
572 P_("D-Bus address specifying potential socket endpoints"),
575 G_PARAM_CONSTRUCT_ONLY |
576 G_PARAM_STATIC_NAME |
577 G_PARAM_STATIC_BLURB |
578 G_PARAM_STATIC_NICK));
581 * GDBusConnection:flags:
583 * Flags from the #GDBusConnectionFlags enumeration.
587 g_object_class_install_property (gobject_class,
589 g_param_spec_flags ("flags",
592 G_TYPE_DBUS_CONNECTION_FLAGS,
593 G_DBUS_CONNECTION_FLAGS_NONE,
595 G_PARAM_CONSTRUCT_ONLY |
596 G_PARAM_STATIC_NAME |
597 G_PARAM_STATIC_BLURB |
598 G_PARAM_STATIC_NICK));
601 * GDBusConnection:guid:
603 * The GUID of the peer performing the role of server when
606 * If you are constructing a #GDBusConnection and pass
607 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
608 * #GDBusConnection:flags property then you MUST also set this
609 * property to a valid guid.
611 * If you are constructing a #GDBusConnection and pass
612 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
613 * #GDBusConnection:flags property you will be able to read the GUID
614 * of the other peer here after the connection has been successfully
619 g_object_class_install_property (gobject_class,
621 g_param_spec_string ("guid",
623 P_("GUID of the server peer"),
627 G_PARAM_CONSTRUCT_ONLY |
628 G_PARAM_STATIC_NAME |
629 G_PARAM_STATIC_BLURB |
630 G_PARAM_STATIC_NICK));
633 * GDBusConnection:unique-name:
635 * The unique name as assigned by the message bus or %NULL if the
636 * connection is not open or not a message bus connection.
640 g_object_class_install_property (gobject_class,
642 g_param_spec_string ("unique-name",
644 P_("Unique name of bus connection"),
647 G_PARAM_STATIC_NAME |
648 G_PARAM_STATIC_BLURB |
649 G_PARAM_STATIC_NICK));
652 * GDBusConnection:closed:
654 * A boolean specifying whether the connection has been closed.
658 g_object_class_install_property (gobject_class,
660 g_param_spec_boolean ("closed",
662 P_("Whether the connection is closed"),
665 G_PARAM_STATIC_NAME |
666 G_PARAM_STATIC_BLURB |
667 G_PARAM_STATIC_NICK));
670 * GDBusConnection:exit-on-close:
672 * A boolean specifying whether the process will be terminated (by
673 * calling <literal>raise(SIGTERM)</literal>) if the connection
674 * is closed by the remote peer.
678 g_object_class_install_property (gobject_class,
680 g_param_spec_boolean ("exit-on-close",
682 P_("Whether the process is terminated when the connection is closed"),
686 G_PARAM_STATIC_NAME |
687 G_PARAM_STATIC_BLURB |
688 G_PARAM_STATIC_NICK));
691 * GDBusConnection:capabilities:
693 * Flags from the #GDBusCapabilityFlags enumeration
694 * representing connection features negotiated with the other peer.
698 g_object_class_install_property (gobject_class,
699 PROP_CAPABILITY_FLAGS,
700 g_param_spec_flags ("capabilities",
703 G_TYPE_DBUS_CAPABILITY_FLAGS,
704 G_DBUS_CAPABILITY_FLAGS_NONE,
706 G_PARAM_STATIC_NAME |
707 G_PARAM_STATIC_BLURB |
708 G_PARAM_STATIC_NICK));
711 * GDBusConnection:authentication-observer:
713 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
717 g_object_class_install_property (gobject_class,
718 PROP_AUTHENTICATION_OBSERVER,
719 g_param_spec_object ("authentication-observer",
720 P_("Authentication Observer"),
721 P_("Object used to assist in the authentication process"),
722 G_TYPE_DBUS_AUTH_OBSERVER,
724 G_PARAM_CONSTRUCT_ONLY |
725 G_PARAM_STATIC_NAME |
726 G_PARAM_STATIC_BLURB |
727 G_PARAM_STATIC_NICK));
730 * GDBusConnection::closed:
731 * @connection: The #GDBusConnection emitting the signal.
732 * @remote_peer_vanished: %TRUE if @connection is closed because the
733 * remote peer closed its end of the connection.
734 * @error: A #GError with more details about the event or %NULL.
736 * Emitted when the connection is closed.
738 * The cause of this event can be
741 * If g_dbus_connection_close() is called. In this case
742 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
745 * If the remote peer closes the connection. In this case
746 * @remote_peer_vanished is set to %TRUE and @error is set.
749 * If the remote peer sends invalid or malformed data. In this
750 * case @remote_peer_vanished is set to %FALSE and @error
755 * Upon receiving this signal, you should give up your reference to
756 * @connection. You are guaranteed that this signal is emitted only
761 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
762 G_TYPE_DBUS_CONNECTION,
764 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
767 _gio_marshal_VOID__BOOLEAN_BOXED,
775 g_dbus_connection_init (GDBusConnection *connection)
777 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
779 connection->priv->lock = g_mutex_new ();
780 connection->priv->init_lock = g_mutex_new ();
782 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
784 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
786 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
788 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
793 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
796 (GDestroyNotify) exported_object_free);
798 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
801 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
804 (GDestroyNotify) exported_subtree_free);
806 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
809 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
810 if (connection->priv->main_context_at_construction != NULL)
811 g_main_context_ref (connection->priv->main_context_at_construction);
813 connection->priv->filters = g_ptr_array_new ();
817 * g_dbus_connection_get_stream:
818 * @connection: a #GDBusConnection
820 * Gets the underlying stream used for IO.
822 * Returns: the stream used for IO
827 g_dbus_connection_get_stream (GDBusConnection *connection)
829 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
830 return connection->priv->stream;
835 * g_dbus_connection_is_closed:
836 * @connection: A #GDBusConnection.
838 * Gets whether @connection is closed.
840 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
845 g_dbus_connection_is_closed (GDBusConnection *connection)
847 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
848 return connection->priv->closed;
852 * g_dbus_connection_get_capabilities:
853 * @connection: A #GDBusConnection.
855 * Gets the capabilities negotiated with the remote peer
857 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
862 g_dbus_connection_get_capabilities (GDBusConnection *connection)
864 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
865 return connection->priv->capabilities;
869 /* ---------------------------------------------------------------------------------------------------- */
873 GDBusConnection *connection;
875 gboolean remote_peer_vanished;
879 emit_closed_data_free (EmitClosedData *data)
881 g_object_unref (data->connection);
882 if (data->error != NULL)
883 g_error_free (data->error);
888 emit_closed_in_idle (gpointer user_data)
890 EmitClosedData *data = user_data;
893 g_object_notify (G_OBJECT (data->connection), "closed");
894 g_signal_emit (data->connection,
895 signals[CLOSED_SIGNAL],
897 data->remote_peer_vanished,
903 /* Can be called from any thread, must hold lock */
905 set_closed_unlocked (GDBusConnection *connection,
906 gboolean remote_peer_vanished,
909 GSource *idle_source;
910 EmitClosedData *data;
912 CONNECTION_ENSURE_LOCK (connection);
914 g_assert (!connection->priv->closed);
916 connection->priv->closed = TRUE;
918 data = g_new0 (EmitClosedData, 1);
919 data->connection = g_object_ref (connection);
920 data->remote_peer_vanished = remote_peer_vanished;
921 data->error = error != NULL ? g_error_copy (error) : NULL;
923 idle_source = g_idle_source_new ();
924 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
925 g_source_set_callback (idle_source,
928 (GDestroyNotify) emit_closed_data_free);
929 g_source_attach (idle_source, connection->priv->main_context_at_construction);
930 g_source_unref (idle_source);
933 /* ---------------------------------------------------------------------------------------------------- */
936 * g_dbus_connection_close:
937 * @connection: A #GDBusConnection.
939 * Closes @connection. Note that this never causes the process to
940 * exit (this might only happen if the other end of a shared message
941 * bus connection disconnects).
943 * If @connection is already closed, this method does nothing.
948 g_dbus_connection_close (GDBusConnection *connection)
950 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
952 CONNECTION_LOCK (connection);
953 if (!connection->priv->closed)
955 GError *error = NULL;
957 /* TODO: do this async */
958 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
959 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
961 g_warning ("Error closing stream: %s", error->message);
962 g_error_free (error);
965 set_closed_unlocked (connection, FALSE, NULL);
967 CONNECTION_UNLOCK (connection);
970 /* ---------------------------------------------------------------------------------------------------- */
973 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
974 GDBusMessage *message,
975 volatile guint32 *out_serial,
980 guint32 serial_to_use;
983 CONNECTION_ENSURE_LOCK (connection);
985 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
986 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
988 /* TODO: check all necessary headers are present */
993 if (out_serial != NULL)
996 if (connection->priv->closed)
998 g_set_error_literal (error,
1001 _("The connection is closed"));
1005 blob = g_dbus_message_to_blob (message,
1007 connection->priv->capabilities,
1012 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
1017 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1020 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1023 g_assert_not_reached ();
1028 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1029 blob_size, serial_to_use, connection);
1030 g_printerr ("----\n");
1031 hexdump (blob, blob_size);
1032 g_printerr ("----\n");
1035 /* TODO: use connection->priv->auth to encode the blob */
1037 if (out_serial != NULL)
1038 *out_serial = serial_to_use;
1040 g_dbus_message_set_serial (message, serial_to_use);
1042 _g_dbus_worker_send_message (connection->priv->worker,
1046 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1057 * g_dbus_connection_send_message:
1058 * @connection: A #GDBusConnection.
1059 * @message: A #GDBusMessage
1060 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1061 * @error: Return location for error or %NULL.
1063 * Asynchronously sends @message to the peer represented by @connection.
1065 * If @out_serial is not %NULL, then the serial number assigned to
1066 * @message by @connection will be written to this location prior to
1067 * submitting the message to the underlying transport.
1069 * If @connection is closed then the operation will fail with
1070 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1071 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1072 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1074 * See <xref linkend="gdbus-server"/> and <xref
1075 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1076 * low-level API to send and receive UNIX file descriptors.
1078 * Returns: %TRUE if the message was well-formed and queued for
1079 * transmission, %FALSE if @error is set.
1084 g_dbus_connection_send_message (GDBusConnection *connection,
1085 GDBusMessage *message,
1086 volatile guint32 *out_serial,
1091 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1092 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1093 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1095 CONNECTION_LOCK (connection);
1096 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1097 CONNECTION_UNLOCK (connection);
1101 /* ---------------------------------------------------------------------------------------------------- */
1105 volatile gint ref_count;
1106 GDBusConnection *connection;
1108 GSimpleAsyncResult *simple;
1110 GMainContext *main_context;
1112 GCancellable *cancellable;
1114 gulong cancellable_handler_id;
1116 GSource *timeout_source;
1121 static SendMessageData *
1122 send_message_data_ref (SendMessageData *data)
1124 g_atomic_int_inc (&data->ref_count);
1129 send_message_data_unref (SendMessageData *data)
1131 if (g_atomic_int_dec_and_test (&data->ref_count))
1133 g_assert (data->timeout_source == NULL);
1134 g_assert (data->simple == NULL);
1135 g_assert (data->cancellable_handler_id == 0);
1136 g_object_unref (data->connection);
1137 if (data->cancellable != NULL)
1138 g_object_unref (data->cancellable);
1139 if (data->main_context != NULL)
1140 g_main_context_unref (data->main_context);
1145 /* ---------------------------------------------------------------------------------------------------- */
1147 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1149 send_message_with_reply_deliver (SendMessageData *data)
1151 CONNECTION_ENSURE_LOCK (data->connection);
1153 g_assert (!data->delivered);
1155 data->delivered = TRUE;
1157 g_simple_async_result_complete_in_idle (data->simple);
1158 g_object_unref (data->simple);
1159 data->simple = NULL;
1161 if (data->timeout_source != NULL)
1163 g_source_destroy (data->timeout_source);
1164 data->timeout_source = NULL;
1166 if (data->cancellable_handler_id > 0)
1168 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1169 data->cancellable_handler_id = 0;
1172 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1173 GUINT_TO_POINTER (data->serial)));
1175 send_message_data_unref (data);
1178 /* ---------------------------------------------------------------------------------------------------- */
1180 /* must hold lock */
1182 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1183 GDBusMessage *reply)
1185 if (data->delivered)
1188 g_simple_async_result_set_op_res_gpointer (data->simple,
1189 g_object_ref (reply),
1192 send_message_with_reply_deliver (data);
1198 /* ---------------------------------------------------------------------------------------------------- */
1201 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1203 SendMessageData *data = user_data;
1205 CONNECTION_LOCK (data->connection);
1206 if (data->delivered)
1209 g_simple_async_result_set_error (data->simple,
1211 G_IO_ERROR_CANCELLED,
1212 _("Operation was cancelled"));
1214 send_message_with_reply_deliver (data);
1217 CONNECTION_UNLOCK (data->connection);
1221 /* Can be called from any thread with or without lock held */
1223 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1226 SendMessageData *data = user_data;
1227 GSource *idle_source;
1229 /* postpone cancellation to idle handler since we may be called directly
1230 * via g_cancellable_connect() (e.g. holding lock)
1232 idle_source = g_idle_source_new ();
1233 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1234 g_source_set_callback (idle_source,
1235 send_message_with_reply_cancelled_idle_cb,
1236 send_message_data_ref (data),
1237 (GDestroyNotify) send_message_data_unref);
1238 g_source_attach (idle_source, data->main_context);
1239 g_source_unref (idle_source);
1242 /* ---------------------------------------------------------------------------------------------------- */
1245 send_message_with_reply_timeout_cb (gpointer user_data)
1247 SendMessageData *data = user_data;
1249 CONNECTION_LOCK (data->connection);
1250 if (data->delivered)
1253 g_simple_async_result_set_error (data->simple,
1255 G_IO_ERROR_TIMED_OUT,
1256 _("Timeout was reached"));
1258 send_message_with_reply_deliver (data);
1261 CONNECTION_UNLOCK (data->connection);
1266 /* ---------------------------------------------------------------------------------------------------- */
1269 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1270 GDBusMessage *message,
1272 volatile guint32 *out_serial,
1273 GCancellable *cancellable,
1274 GAsyncReadyCallback callback,
1277 GSimpleAsyncResult *simple;
1278 SendMessageData *data;
1280 volatile guint32 serial;
1284 if (out_serial == NULL)
1285 out_serial = &serial;
1287 if (timeout_msec == -1)
1288 timeout_msec = 25 * 1000;
1290 simple = g_simple_async_result_new (G_OBJECT (connection),
1293 g_dbus_connection_send_message_with_reply);
1295 if (g_cancellable_is_cancelled (cancellable))
1297 g_simple_async_result_set_error (simple,
1299 G_IO_ERROR_CANCELLED,
1300 _("Operation was cancelled"));
1301 g_simple_async_result_complete_in_idle (simple);
1302 g_object_unref (simple);
1306 if (connection->priv->closed)
1308 g_simple_async_result_set_error (simple,
1311 _("The connection is closed"));
1312 g_simple_async_result_complete_in_idle (simple);
1313 g_object_unref (simple);
1318 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1320 g_simple_async_result_set_from_error (simple, error);
1321 g_simple_async_result_complete_in_idle (simple);
1322 g_object_unref (simple);
1326 data = g_new0 (SendMessageData, 1);
1327 data->ref_count = 1;
1328 data->connection = g_object_ref (connection);
1329 data->simple = simple;
1330 data->serial = *out_serial;
1331 data->main_context = g_main_context_get_thread_default ();
1332 if (data->main_context != NULL)
1333 g_main_context_ref (data->main_context);
1335 if (cancellable != NULL)
1337 data->cancellable = g_object_ref (cancellable);
1338 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1339 G_CALLBACK (send_message_with_reply_cancelled_cb),
1340 send_message_data_ref (data),
1341 (GDestroyNotify) send_message_data_unref);
1342 g_object_set_data_full (G_OBJECT (simple),
1344 g_object_ref (cancellable),
1345 (GDestroyNotify) g_object_unref);
1348 data->timeout_source = g_timeout_source_new (timeout_msec);
1349 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1350 g_source_set_callback (data->timeout_source,
1351 send_message_with_reply_timeout_cb,
1352 send_message_data_ref (data),
1353 (GDestroyNotify) send_message_data_unref);
1354 g_source_attach (data->timeout_source, data->main_context);
1355 g_source_unref (data->timeout_source);
1357 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1358 GUINT_TO_POINTER (*out_serial),
1366 * g_dbus_connection_send_message_with_reply:
1367 * @connection: A #GDBusConnection.
1368 * @message: A #GDBusMessage.
1369 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1370 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1371 * @cancellable: A #GCancellable or %NULL.
1372 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1373 * care about the result.
1374 * @user_data: The data to pass to @callback.
1376 * Asynchronously sends @message to the peer represented by @connection.
1378 * If @out_serial is not %NULL, then the serial number assigned to
1379 * @message by @connection will be written to this location prior to
1380 * submitting the message to the underlying transport.
1382 * If @connection is closed then the operation will fail with
1383 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1384 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1385 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1387 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1388 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1389 * of the thread you are calling this method from. You can then call
1390 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1391 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1393 * See <xref linkend="gdbus-server"/> and <xref
1394 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1395 * low-level API to send and receive UNIX file descriptors.
1400 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1401 GDBusMessage *message,
1403 volatile guint32 *out_serial,
1404 GCancellable *cancellable,
1405 GAsyncReadyCallback callback,
1408 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1409 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1410 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1412 CONNECTION_LOCK (connection);
1413 g_dbus_connection_send_message_with_reply_unlocked (connection,
1420 CONNECTION_UNLOCK (connection);
1424 * g_dbus_connection_send_message_with_reply_finish:
1425 * @connection: a #GDBusConnection
1426 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1427 * @error: Return location for error or %NULL.
1429 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1431 * Note that @error is only set if a local in-process error
1432 * occured. That is to say that the returned #GDBusMessage object may
1433 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1434 * g_dbus_message_to_gerror() to transcode this to a #GError.
1436 * See <xref linkend="gdbus-server"/> and <xref
1437 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1438 * low-level API to send and receive UNIX file descriptors.
1440 * Returns: A #GDBusMessage or %NULL if @error is set.
1445 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1449 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1450 GDBusMessage *reply;
1451 GCancellable *cancellable;
1453 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1454 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1458 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1460 if (g_simple_async_result_propagate_error (simple, error))
1463 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1464 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1465 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1467 g_object_unref (reply);
1469 g_set_error_literal (error,
1471 G_IO_ERROR_CANCELLED,
1472 _("Operation was cancelled"));
1478 /* ---------------------------------------------------------------------------------------------------- */
1483 GMainContext *context;
1485 } SendMessageSyncData;
1488 send_message_with_reply_sync_cb (GDBusConnection *connection,
1492 SendMessageSyncData *data = user_data;
1493 data->res = g_object_ref (res);
1494 g_main_loop_quit (data->loop);
1498 * g_dbus_connection_send_message_with_reply_sync:
1499 * @connection: A #GDBusConnection.
1500 * @message: A #GDBusMessage.
1501 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1502 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1503 * @cancellable: A #GCancellable or %NULL.
1504 * @error: Return location for error or %NULL.
1506 * Synchronously sends @message to the peer represented by @connection
1507 * and blocks the calling thread until a reply is received or the
1508 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1509 * for the asynchronous version of this method.
1511 * If @out_serial is not %NULL, then the serial number assigned to
1512 * @message by @connection will be written to this location prior to
1513 * submitting the message to the underlying transport.
1515 * If @connection is closed then the operation will fail with
1516 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1517 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1518 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1520 * Note that @error is only set if a local in-process error
1521 * occured. That is to say that the returned #GDBusMessage object may
1522 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1523 * g_dbus_message_to_gerror() to transcode this to a #GError.
1525 * See <xref linkend="gdbus-server"/> and <xref
1526 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1527 * low-level API to send and receive UNIX file descriptors.
1529 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1534 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1535 GDBusMessage *message,
1537 volatile guint32 *out_serial,
1538 GCancellable *cancellable,
1541 SendMessageSyncData *data;
1542 GDBusMessage *reply;
1544 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1545 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1546 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1547 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1549 data = g_new0 (SendMessageSyncData, 1);
1550 data->context = g_main_context_new ();
1551 data->loop = g_main_loop_new (data->context, FALSE);
1553 g_main_context_push_thread_default (data->context);
1555 g_dbus_connection_send_message_with_reply (connection,
1560 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1562 g_main_loop_run (data->loop);
1563 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1567 g_main_context_pop_thread_default (data->context);
1569 g_main_context_unref (data->context);
1570 g_main_loop_unref (data->loop);
1571 g_object_unref (data->res);
1577 /* ---------------------------------------------------------------------------------------------------- */
1581 GDBusMessageFilterFunction func;
1588 GDBusMessageFilterFunction filter_function;
1590 GDestroyNotify user_data_free_func;
1593 /* Called in worker's thread - we must not block */
1595 on_worker_message_received (GDBusWorker *worker,
1596 GDBusMessage *message,
1599 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1600 FilterCallback *filters;
1601 gboolean consumed_by_filter;
1605 //g_debug ("in on_worker_message_received");
1607 g_object_ref (connection);
1609 /* First collect the set of callback functions */
1610 CONNECTION_LOCK (connection);
1611 num_filters = connection->priv->filters->len;
1612 filters = g_new0 (FilterCallback, num_filters);
1613 for (n = 0; n < num_filters; n++)
1615 FilterData *data = connection->priv->filters->pdata[n];
1616 filters[n].func = data->filter_function;
1617 filters[n].user_data = data->user_data;
1619 CONNECTION_UNLOCK (connection);
1621 /* the call the filters in order (without holding the lock) */
1622 consumed_by_filter = FALSE;
1623 for (n = 0; n < num_filters; n++)
1625 consumed_by_filter = filters[n].func (connection,
1627 filters[n].user_data);
1628 if (consumed_by_filter)
1632 /* Standard dispatch unless the filter ate the message */
1633 if (!consumed_by_filter)
1635 GDBusMessageType message_type;
1637 message_type = g_dbus_message_get_message_type (message);
1638 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1640 guint32 reply_serial;
1641 SendMessageData *send_message_data;
1643 reply_serial = g_dbus_message_get_reply_serial (message);
1644 CONNECTION_LOCK (connection);
1645 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1646 GUINT_TO_POINTER (reply_serial));
1647 if (send_message_data != NULL)
1649 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1650 send_message_data_deliver_reply_unlocked (send_message_data, message);
1654 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1656 CONNECTION_UNLOCK (connection);
1658 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1660 CONNECTION_LOCK (connection);
1661 distribute_signals (connection, message);
1662 CONNECTION_UNLOCK (connection);
1664 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1666 CONNECTION_LOCK (connection);
1667 distribute_method_call (connection, message);
1668 CONNECTION_UNLOCK (connection);
1672 g_object_unref (connection);
1676 /* Called in worker's thread - we must not block */
1678 on_worker_closed (GDBusWorker *worker,
1679 gboolean remote_peer_vanished,
1683 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1685 //g_debug ("in on_worker_closed: %s", error->message);
1687 CONNECTION_LOCK (connection);
1688 if (!connection->priv->closed)
1689 set_closed_unlocked (connection, remote_peer_vanished, error);
1690 CONNECTION_UNLOCK (connection);
1693 /* ---------------------------------------------------------------------------------------------------- */
1695 /* Determines the biggest set of capabilities we can support on this connection */
1696 static GDBusCapabilityFlags
1697 get_offered_capabilities_max (GDBusConnection *connection)
1699 GDBusCapabilityFlags ret;
1700 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1702 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1703 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1709 initable_init (GInitable *initable,
1710 GCancellable *cancellable,
1713 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1716 /* This method needs to be idempotent to work with the singleton
1717 * pattern. See the docs for g_initable_init(). We implement this by
1720 * Unfortunately we can't use the main lock since the on_worker_*()
1721 * callbacks above needs the lock during initialization (for message
1722 * bus connections we do a synchronous Hello() call on the bus).
1724 g_mutex_lock (connection->priv->init_lock);
1728 if (connection->priv->is_initialized)
1730 if (connection->priv->stream != NULL)
1733 g_assert (connection->priv->initialization_error != NULL);
1736 g_assert (connection->priv->initialization_error == NULL);
1738 /* The user can pass multiple (but mutally exclusive) construct
1741 * - stream (of type GIOStream)
1742 * - address (of type gchar*)
1744 * At the end of the day we end up with a non-NULL GIOStream
1745 * object in connection->priv->stream.
1747 if (connection->priv->address != NULL)
1749 g_assert (connection->priv->stream == NULL);
1751 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1752 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1754 g_set_error_literal (error,
1756 G_IO_ERROR_INVALID_ARGUMENT,
1757 _("Unsupported flags encountered when constructing a client-side connection"));
1761 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1762 NULL, /* TODO: out_guid */
1764 &connection->priv->initialization_error);
1765 if (connection->priv->stream == NULL)
1768 else if (connection->priv->stream != NULL)
1774 g_assert_not_reached ();
1777 /* Authenticate the connection */
1778 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1780 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1781 g_assert (connection->priv->guid != NULL);
1782 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1783 if (!_g_dbus_auth_run_server (connection->priv->auth,
1784 connection->priv->authentication_observer,
1785 connection->priv->guid,
1786 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1787 get_offered_capabilities_max (connection),
1788 &connection->priv->capabilities,
1789 &connection->priv->crendentials,
1791 &connection->priv->initialization_error))
1794 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1796 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1797 g_assert (connection->priv->guid == NULL);
1798 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1799 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1800 get_offered_capabilities_max (connection),
1801 &connection->priv->capabilities,
1803 &connection->priv->initialization_error);
1804 if (connection->priv->guid == NULL)
1808 if (connection->priv->authentication_observer != NULL)
1810 g_object_unref (connection->priv->authentication_observer);
1811 connection->priv->authentication_observer = NULL;
1814 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1816 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1821 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1825 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1827 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1831 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1832 connection->priv->capabilities,
1833 on_worker_message_received,
1837 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1838 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1840 GVariant *hello_result;
1842 hello_result = g_dbus_connection_call_sync (connection,
1843 "org.freedesktop.DBus", /* name */
1844 "/org/freedesktop/DBus", /* path */
1845 "org.freedesktop.DBus", /* interface */
1847 NULL, /* parameters */
1848 G_VARIANT_TYPE ("(s)"),
1849 G_DBUS_CALL_FLAGS_NONE,
1851 NULL, /* TODO: cancellable */
1852 &connection->priv->initialization_error);
1853 if (hello_result == NULL)
1856 g_variant_get (hello_result, "(s)", &connection->priv->bus_unique_name);
1857 g_variant_unref (hello_result);
1858 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1861 connection->priv->is_initialized = TRUE;
1867 g_assert (connection->priv->initialization_error != NULL);
1868 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1871 g_mutex_unlock (connection->priv->init_lock);
1877 initable_iface_init (GInitableIface *initable_iface)
1879 initable_iface->init = initable_init;
1882 /* ---------------------------------------------------------------------------------------------------- */
1885 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1890 /* ---------------------------------------------------------------------------------------------------- */
1893 * g_dbus_connection_new:
1894 * @stream: A #GIOStream.
1895 * @guid: The GUID to use if a authenticating as a server or %NULL.
1896 * @flags: Flags describing how to make the connection.
1897 * @observer: A #GDBusAuthObserver or %NULL.
1898 * @cancellable: A #GCancellable or %NULL.
1899 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1900 * @user_data: The data to pass to @callback.
1902 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1903 * with the end represented by @stream.
1905 * If @observer is not %NULL it may be used to control the
1906 * authentication process.
1908 * When the operation is finished, @callback will be invoked. You can
1909 * then call g_dbus_connection_new_finish() to get the result of the
1912 * This is a asynchronous failable constructor. See
1913 * g_dbus_connection_new_sync() for the synchronous
1919 g_dbus_connection_new (GIOStream *stream,
1921 GDBusConnectionFlags flags,
1922 GDBusAuthObserver *observer,
1923 GCancellable *cancellable,
1924 GAsyncReadyCallback callback,
1927 g_return_if_fail (G_IS_IO_STREAM (stream));
1928 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1936 "authentication-observer", observer,
1941 * g_dbus_connection_new_finish:
1942 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1943 * @error: Return location for error or %NULL.
1945 * Finishes an operation started with g_dbus_connection_new().
1947 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1952 g_dbus_connection_new_finish (GAsyncResult *res,
1956 GObject *source_object;
1958 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1959 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1961 source_object = g_async_result_get_source_object (res);
1962 g_assert (source_object != NULL);
1963 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1966 g_object_unref (source_object);
1968 return G_DBUS_CONNECTION (object);
1974 * g_dbus_connection_new_sync:
1975 * @stream: A #GIOStream.
1976 * @guid: The GUID to use if a authenticating as a server or %NULL.
1977 * @flags: Flags describing how to make the connection.
1978 * @observer: A #GDBusAuthObserver or %NULL.
1979 * @cancellable: A #GCancellable or %NULL.
1980 * @error: Return location for error or %NULL.
1982 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1983 * with the end represented by @stream.
1985 * If @observer is not %NULL it may be used to control the
1986 * authentication process.
1988 * This is a synchronous failable constructor. See
1989 * g_dbus_connection_new() for the asynchronous version.
1991 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1996 g_dbus_connection_new_sync (GIOStream *stream,
1998 GDBusConnectionFlags flags,
1999 GDBusAuthObserver *observer,
2000 GCancellable *cancellable,
2003 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2004 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2005 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2011 "authentication-observer", observer,
2015 /* ---------------------------------------------------------------------------------------------------- */
2018 * g_dbus_connection_new_for_address:
2019 * @address: A D-Bus address.
2020 * @flags: Flags describing how to make the connection.
2021 * @observer: A #GDBusAuthObserver or %NULL.
2022 * @cancellable: A #GCancellable or %NULL.
2023 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2024 * @user_data: The data to pass to @callback.
2026 * Asynchronously connects and sets up a D-Bus client connection for
2027 * exchanging D-Bus messages with an endpoint specified by @address
2028 * which must be in the D-Bus address format.
2030 * This constructor can only be used to initiate client-side
2031 * connections - use g_dbus_connection_new() if you need to act as the
2032 * server. In particular, @flags cannot contain the
2033 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2034 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2036 * When the operation is finished, @callback will be invoked. You can
2037 * then call g_dbus_connection_new_finish() to get the result of the
2040 * If @observer is not %NULL it may be used to control the
2041 * authentication process.
2043 * This is a asynchronous failable constructor. See
2044 * g_dbus_connection_new_for_address_sync() for the synchronous
2050 g_dbus_connection_new_for_address (const gchar *address,
2051 GDBusConnectionFlags flags,
2052 GDBusAuthObserver *observer,
2053 GCancellable *cancellable,
2054 GAsyncReadyCallback callback,
2057 g_return_if_fail (address != NULL);
2058 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2065 "authentication-observer", observer,
2070 * g_dbus_connection_new_for_address_finish:
2071 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2072 * @error: Return location for error or %NULL.
2074 * Finishes an operation started with g_dbus_connection_new_for_address().
2076 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2081 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2085 GObject *source_object;
2087 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2088 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2090 source_object = g_async_result_get_source_object (res);
2091 g_assert (source_object != NULL);
2092 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2095 g_object_unref (source_object);
2097 return G_DBUS_CONNECTION (object);
2103 * g_dbus_connection_new_for_address_sync:
2104 * @address: A D-Bus address.
2105 * @flags: Flags describing how to make the connection.
2106 * @observer: A #GDBusAuthObserver or %NULL.
2107 * @cancellable: A #GCancellable or %NULL.
2108 * @error: Return location for error or %NULL.
2110 * Synchronously connects and sets up a D-Bus client connection for
2111 * exchanging D-Bus messages with an endpoint specified by @address
2112 * which must be in the D-Bus address format.
2114 * This constructor can only be used to initiate client-side
2115 * connections - use g_dbus_connection_new_sync() if you need to act
2116 * as the server. In particular, @flags cannot contain the
2117 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2118 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2120 * This is a synchronous failable constructor. See
2121 * g_dbus_connection_new_for_address() for the asynchronous version.
2123 * If @observer is not %NULL it may be used to control the
2124 * authentication process.
2126 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2131 g_dbus_connection_new_for_address_sync (const gchar *address,
2132 GDBusConnectionFlags flags,
2133 GDBusAuthObserver *observer,
2134 GCancellable *cancellable,
2137 g_return_val_if_fail (address != NULL, NULL);
2138 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2139 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2144 "authentication-observer", observer,
2148 /* ---------------------------------------------------------------------------------------------------- */
2151 * g_dbus_connection_set_exit_on_close:
2152 * @connection: A #GDBusConnection.
2153 * @exit_on_close: Whether the process should be terminated
2154 * when @connection is closed by the remote peer.
2156 * Sets whether the process should be terminated when @connection is
2157 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2163 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2164 gboolean exit_on_close)
2166 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2167 connection->priv->exit_on_close = exit_on_close;
2171 * g_dbus_connection_get_exit_on_close:
2172 * @connection: A #GDBusConnection.
2174 * Gets whether the process is terminated when @connection is
2175 * closed by the remote peer. See
2176 * #GDBusConnection:exit-on-close for more details.
2178 * Returns: Whether the process is terminated when @connection is
2179 * closed by the remote peer.
2184 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2186 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2187 return connection->priv->exit_on_close;
2191 * g_dbus_connection_get_guid:
2192 * @connection: A #GDBusConnection.
2194 * The GUID of the peer performing the role of server when
2195 * authenticating. See #GDBusConnection:guid for more details.
2197 * Returns: The GUID. Do not free this string, it is owned by
2203 g_dbus_connection_get_guid (GDBusConnection *connection)
2205 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2206 return connection->priv->guid;
2210 * g_dbus_connection_get_unique_name:
2211 * @connection: A #GDBusConnection.
2213 * Gets the unique name of @connection as assigned by the message
2214 * bus. This can also be used to figure out if @connection is a
2215 * message bus connection.
2217 * Returns: The unique name or %NULL if @connection is not a message
2218 * bus connection. Do not free this string, it is owned by
2224 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2226 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2227 return connection->priv->bus_unique_name;
2231 * g_dbus_connection_get_peer_credentials:
2232 * @connection: A #GDBusConnection.
2234 * Gets the credentials of the authenticated peer. This will always
2235 * return %NULL unless @connection acted as a server
2236 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2237 * when set up and the client passed credentials as part of the
2238 * authentication process.
2240 * In a message bus setup, the message bus is always the server and
2241 * each application is a client. So this method will always return
2242 * %NULL for message bus clients.
2244 * Returns: A #GCredentials or %NULL if not available. Do not free
2245 * this object, it is owned by @connection.
2250 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2252 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2253 return connection->priv->crendentials;
2256 /* ---------------------------------------------------------------------------------------------------- */
2258 static guint _global_filter_id = 1;
2261 * g_dbus_connection_add_filter:
2262 * @connection: A #GDBusConnection.
2263 * @filter_function: A filter function.
2264 * @user_data: User data to pass to @filter_function.
2265 * @user_data_free_func: Function to free @user_data with when filter
2266 * is removed or %NULL.
2268 * Adds a message filter. Filters are handlers that are run on all
2269 * incoming messages, prior to standard dispatch. Filters are run in
2270 * the order that they were added. The same handler can be added as a
2271 * filter more than once, in which case it will be run more than once.
2272 * Filters added during a filter callback won't be run on the message
2275 * Note that filters are run in a dedicated message handling thread so
2276 * they can't block and, generally, can't do anything but signal a
2277 * worker thread. Also note that filters are rarely needed - use API
2278 * such as g_dbus_connection_send_message_with_reply(),
2279 * g_dbus_connection_signal_subscribe() or
2280 * g_dbus_connection_call() instead.
2282 * Returns: A filter identifier that can be used with
2283 * g_dbus_connection_remove_filter().
2288 g_dbus_connection_add_filter (GDBusConnection *connection,
2289 GDBusMessageFilterFunction filter_function,
2291 GDestroyNotify user_data_free_func)
2295 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2296 g_return_val_if_fail (filter_function != NULL, 0);
2298 CONNECTION_LOCK (connection);
2299 data = g_new0 (FilterData, 1);
2300 data->id = _global_filter_id++; /* TODO: overflow etc. */
2301 data->filter_function = filter_function;
2302 data->user_data = user_data;
2303 data->user_data_free_func = user_data_free_func;
2304 g_ptr_array_add (connection->priv->filters, data);
2305 CONNECTION_UNLOCK (connection);
2310 /* only called from finalize(), removes all filters */
2312 purge_all_filters (GDBusConnection *connection)
2315 for (n = 0; n < connection->priv->filters->len; n++)
2317 FilterData *data = connection->priv->filters->pdata[n];
2318 if (data->user_data_free_func != NULL)
2319 data->user_data_free_func (data->user_data);
2325 * g_dbus_connection_remove_filter:
2326 * @connection: a #GDBusConnection
2327 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2334 g_dbus_connection_remove_filter (GDBusConnection *connection,
2338 FilterData *to_destroy;
2340 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2342 CONNECTION_LOCK (connection);
2344 for (n = 0; n < connection->priv->filters->len; n++)
2346 FilterData *data = connection->priv->filters->pdata[n];
2347 if (data->id == filter_id)
2349 g_ptr_array_remove_index (connection->priv->filters, n);
2354 CONNECTION_UNLOCK (connection);
2356 /* do free without holding lock */
2357 if (to_destroy != NULL)
2359 if (to_destroy->user_data_free_func != NULL)
2360 to_destroy->user_data_free_func (to_destroy->user_data);
2361 g_free (to_destroy);
2365 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2369 /* ---------------------------------------------------------------------------------------------------- */
2375 gchar *interface_name;
2379 GArray *subscribers;
2384 GDBusSignalCallback callback;
2386 GDestroyNotify user_data_free_func;
2388 GMainContext *context;
2392 signal_data_free (SignalData *data)
2394 g_free (data->rule);
2395 g_free (data->sender);
2396 g_free (data->interface_name);
2397 g_free (data->member);
2398 g_free (data->object_path);
2399 g_free (data->arg0);
2400 g_array_free (data->subscribers, TRUE);
2405 args_to_rule (const gchar *sender,
2406 const gchar *interface_name,
2407 const gchar *member,
2408 const gchar *object_path,
2413 rule = g_string_new ("type='signal'");
2415 g_string_append_printf (rule, ",sender='%s'", sender);
2416 if (interface_name != NULL)
2417 g_string_append_printf (rule, ",interface='%s'", interface_name);
2419 g_string_append_printf (rule, ",member='%s'", member);
2420 if (object_path != NULL)
2421 g_string_append_printf (rule, ",path='%s'", object_path);
2423 g_string_append_printf (rule, ",arg0='%s'", arg0);
2425 return g_string_free (rule, FALSE);
2428 static guint _global_subscriber_id = 1;
2429 static guint _global_registration_id = 1;
2430 static guint _global_subtree_registration_id = 1;
2432 /* ---------------------------------------------------------------------------------------------------- */
2434 /* must hold lock when calling */
2436 add_match_rule (GDBusConnection *connection,
2437 const gchar *match_rule)
2440 GDBusMessage *message;
2442 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2443 "/org/freedesktop/DBus", /* path */
2444 "org.freedesktop.DBus", /* interface */
2446 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2449 if (!g_dbus_connection_send_message_unlocked (connection,
2454 g_critical ("Error while sending AddMatch() message: %s", error->message);
2455 g_error_free (error);
2457 g_object_unref (message);
2460 /* ---------------------------------------------------------------------------------------------------- */
2462 /* must hold lock when calling */
2464 remove_match_rule (GDBusConnection *connection,
2465 const gchar *match_rule)
2468 GDBusMessage *message;
2470 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2471 "/org/freedesktop/DBus", /* path */
2472 "org.freedesktop.DBus", /* interface */
2474 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2477 if (!g_dbus_connection_send_message_unlocked (connection,
2482 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2483 g_error_free (error);
2485 g_object_unref (message);
2488 /* ---------------------------------------------------------------------------------------------------- */
2491 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2493 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2494 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2495 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2496 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2497 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2500 /* ---------------------------------------------------------------------------------------------------- */
2503 * g_dbus_connection_signal_subscribe:
2504 * @connection: A #GDBusConnection.
2505 * @sender: Sender name to match on. Must be either <literal>org.freedesktop.DBus</literal> (for listening to signals from the message bus daemon) or a unique name or %NULL to listen from all senders.
2506 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2507 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2508 * @object_path: Object path to match on or %NULL to match on all object paths.
2509 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2510 * @callback: Callback to invoke when there is a signal matching the requested data.
2511 * @user_data: User data to pass to @callback.
2512 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2514 * Subscribes to signals on @connection and invokes @callback with a
2515 * whenever the signal is received. Note that @callback
2516 * will be invoked in the <link
2517 * linkend="g-main-context-push-thread-default">thread-default main
2518 * loop</link> of the thread you are calling this method from.
2520 * It is considered a programming error to use this function if @connection is closed.
2522 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2523 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2524 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2525 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2526 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2527 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2529 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2534 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2535 const gchar *sender,
2536 const gchar *interface_name,
2537 const gchar *member,
2538 const gchar *object_path,
2540 GDBusSignalCallback callback,
2542 GDestroyNotify user_data_free_func)
2545 SignalData *signal_data;
2546 SignalSubscriber subscriber;
2547 GPtrArray *signal_data_array;
2549 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2550 * an OOM condition. We might want to change that but that would involve making
2551 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2552 * handle that. And there's really no sensible way of handling this short of retrying
2553 * to add the match rule... and then there's the little thing that, hey, maybe there's
2554 * a reason the bus in an OOM condition.
2556 * Doable, but not really sure it's worth it...
2559 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2560 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2561 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2562 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2563 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2564 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2565 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2566 g_return_val_if_fail (callback != NULL, 0);
2568 CONNECTION_LOCK (connection);
2570 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2575 subscriber.callback = callback;
2576 subscriber.user_data = user_data;
2577 subscriber.user_data_free_func = user_data_free_func;
2578 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2579 subscriber.context = g_main_context_get_thread_default ();
2580 if (subscriber.context != NULL)
2581 g_main_context_ref (subscriber.context);
2583 /* see if we've already have this rule */
2584 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2585 if (signal_data != NULL)
2587 g_array_append_val (signal_data->subscribers, subscriber);
2592 signal_data = g_new0 (SignalData, 1);
2593 signal_data->rule = rule;
2594 signal_data->sender = g_strdup (sender);
2595 signal_data->interface_name = g_strdup (interface_name);
2596 signal_data->member = g_strdup (member);
2597 signal_data->object_path = g_strdup (object_path);
2598 signal_data->arg0 = g_strdup (arg0);
2599 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2600 g_array_append_val (signal_data->subscribers, subscriber);
2602 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2606 /* Add the match rule to the bus...
2608 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2609 * always send such messages to us.
2611 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2613 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2614 add_match_rule (connection, signal_data->rule);
2618 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2619 GUINT_TO_POINTER (subscriber.id),
2622 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2623 signal_data->sender);
2624 if (signal_data_array == NULL)
2626 signal_data_array = g_ptr_array_new ();
2627 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2628 g_strdup (signal_data->sender),
2631 g_ptr_array_add (signal_data_array, signal_data);
2633 CONNECTION_UNLOCK (connection);
2635 return subscriber.id;
2638 /* ---------------------------------------------------------------------------------------------------- */
2640 /* must hold lock when calling this */
2642 unsubscribe_id_internal (GDBusConnection *connection,
2643 guint subscription_id,
2644 GArray *out_removed_subscribers)
2646 SignalData *signal_data;
2647 GPtrArray *signal_data_array;
2650 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2651 GUINT_TO_POINTER (subscription_id));
2652 if (signal_data == NULL)
2654 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2658 for (n = 0; n < signal_data->subscribers->len; n++)
2660 SignalSubscriber *subscriber;
2662 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2663 if (subscriber->id != subscription_id)
2666 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2667 GUINT_TO_POINTER (subscription_id)));
2668 g_array_append_val (out_removed_subscribers, *subscriber);
2669 g_array_remove_index (signal_data->subscribers, n);
2671 if (signal_data->subscribers->len == 0)
2672 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2674 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2675 signal_data->sender);
2676 g_warn_if_fail (signal_data_array != NULL);
2677 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2679 if (signal_data_array->len == 0)
2681 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2683 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2684 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2686 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2687 remove_match_rule (connection, signal_data->rule);
2690 signal_data_free (signal_data);
2696 g_assert_not_reached ();
2703 * g_dbus_connection_signal_unsubscribe:
2704 * @connection: A #GDBusConnection.
2705 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2707 * Unsubscribes from signals.
2712 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2713 guint subscription_id)
2715 GArray *subscribers;
2718 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2720 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2722 CONNECTION_LOCK (connection);
2723 unsubscribe_id_internal (connection,
2726 CONNECTION_UNLOCK (connection);
2729 g_assert (subscribers->len == 0 || subscribers->len == 1);
2731 /* call GDestroyNotify without lock held */
2732 for (n = 0; n < subscribers->len; n++)
2734 SignalSubscriber *subscriber;
2735 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2736 if (subscriber->user_data_free_func != NULL)
2737 subscriber->user_data_free_func (subscriber->user_data);
2738 if (subscriber->context != NULL)
2739 g_main_context_unref (subscriber->context);
2742 g_array_free (subscribers, TRUE);
2745 /* ---------------------------------------------------------------------------------------------------- */
2749 guint subscription_id;
2750 GDBusSignalCallback callback;
2752 GDBusMessage *message;
2753 GDBusConnection *connection;
2754 const gchar *sender;
2756 const gchar *interface;
2757 const gchar *member;
2760 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2764 emit_signal_instance_in_idle_cb (gpointer data)
2766 SignalInstance *signal_instance = data;
2767 GVariant *parameters;
2768 gboolean has_subscription;
2770 parameters = g_dbus_message_get_body (signal_instance->message);
2771 if (parameters == NULL)
2773 parameters = g_variant_new ("()");
2774 g_variant_ref_sink (parameters);
2778 g_variant_ref_sink (parameters);
2782 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2783 signal_instance->sender,
2784 signal_instance->path,
2785 signal_instance->interface,
2786 signal_instance->member,
2787 g_variant_print (parameters, TRUE));
2790 /* Careful here, don't do the callback if we no longer has the subscription */
2791 CONNECTION_LOCK (signal_instance->connection);
2792 has_subscription = FALSE;
2793 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2794 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2795 has_subscription = TRUE;
2796 CONNECTION_UNLOCK (signal_instance->connection);
2798 if (has_subscription)
2799 signal_instance->callback (signal_instance->connection,
2800 signal_instance->sender,
2801 signal_instance->path,
2802 signal_instance->interface,
2803 signal_instance->member,
2805 signal_instance->user_data);
2807 if (parameters != NULL)
2808 g_variant_unref (parameters);
2814 signal_instance_free (SignalInstance *signal_instance)
2816 g_object_unref (signal_instance->message);
2817 g_object_unref (signal_instance->connection);
2818 g_free (signal_instance);
2821 /* called in message handler thread WITH lock held */
2823 schedule_callbacks (GDBusConnection *connection,
2824 GPtrArray *signal_data_array,
2825 GDBusMessage *message,
2826 const gchar *sender)
2829 const gchar *interface;
2830 const gchar *member;
2839 interface = g_dbus_message_get_interface (message);
2840 member = g_dbus_message_get_member (message);
2841 path = g_dbus_message_get_path (message);
2842 arg0 = g_dbus_message_get_arg0 (message);
2845 g_debug ("sender = `%s'", sender);
2846 g_debug ("interface = `%s'", interface);
2847 g_debug ("member = `%s'", member);
2848 g_debug ("path = `%s'", path);
2849 g_debug ("arg0 = `%s'", arg0);
2852 /* TODO: if this is slow, then we can change signal_data_array into
2853 * map_object_path_to_signal_data_array or something.
2855 for (n = 0; n < signal_data_array->len; n++)
2857 SignalData *signal_data = signal_data_array->pdata[n];
2859 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2862 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2865 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2868 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2871 for (m = 0; m < signal_data->subscribers->len; m++)
2873 SignalSubscriber *subscriber;
2874 GSource *idle_source;
2875 SignalInstance *signal_instance;
2877 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2879 signal_instance = g_new0 (SignalInstance, 1);
2880 signal_instance->subscription_id = subscriber->id;
2881 signal_instance->callback = subscriber->callback;
2882 signal_instance->user_data = subscriber->user_data;
2883 signal_instance->message = g_object_ref (message);
2884 signal_instance->connection = g_object_ref (connection);
2885 signal_instance->sender = sender;
2886 signal_instance->path = path;
2887 signal_instance->interface = interface;
2888 signal_instance->member = member;
2890 idle_source = g_idle_source_new ();
2891 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2892 g_source_set_callback (idle_source,
2893 emit_signal_instance_in_idle_cb,
2895 (GDestroyNotify) signal_instance_free);
2896 g_source_attach (idle_source, subscriber->context);
2897 g_source_unref (idle_source);
2902 /* called in message handler thread with lock held */
2904 distribute_signals (GDBusConnection *connection,
2905 GDBusMessage *message)
2907 GPtrArray *signal_data_array;
2908 const gchar *sender;
2910 sender = g_dbus_message_get_sender (message);
2912 /* collect subscribers that match on sender */
2915 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2916 if (signal_data_array != NULL)
2917 schedule_callbacks (connection, signal_data_array, message, sender);
2920 /* collect subscribers not matching on sender */
2921 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2922 if (signal_data_array != NULL)
2923 schedule_callbacks (connection, signal_data_array, message, sender);
2926 /* ---------------------------------------------------------------------------------------------------- */
2928 /* only called from finalize(), removes all subscriptions */
2930 purge_all_signal_subscriptions (GDBusConnection *connection)
2932 GHashTableIter iter;
2935 GArray *subscribers;
2938 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2939 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2940 while (g_hash_table_iter_next (&iter, &key, NULL))
2942 guint subscription_id = GPOINTER_TO_UINT (key);
2943 g_array_append_val (ids, subscription_id);
2946 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2947 for (n = 0; n < ids->len; n++)
2949 guint subscription_id = g_array_index (ids, guint, n);
2950 unsubscribe_id_internal (connection,
2954 g_array_free (ids, TRUE);
2956 /* call GDestroyNotify without lock held */
2957 for (n = 0; n < subscribers->len; n++)
2959 SignalSubscriber *subscriber;
2960 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2961 if (subscriber->user_data_free_func != NULL)
2962 subscriber->user_data_free_func (subscriber->user_data);
2963 if (subscriber->context != NULL)
2964 g_main_context_unref (subscriber->context);
2967 g_array_free (subscribers, TRUE);
2970 /* ---------------------------------------------------------------------------------------------------- */
2972 struct ExportedObject
2975 GDBusConnection *connection;
2977 /* maps gchar* -> ExportedInterface* */
2978 GHashTable *map_if_name_to_ei;
2981 /* only called with lock held */
2983 exported_object_free (ExportedObject *eo)
2985 g_free (eo->object_path);
2986 g_hash_table_unref (eo->map_if_name_to_ei);
2995 gchar *interface_name;
2996 const GDBusInterfaceVTable *vtable;
2997 const GDBusInterfaceInfo *introspection_data;
2999 GMainContext *context;
3001 GDestroyNotify user_data_free_func;
3002 } ExportedInterface;
3004 /* called with lock held */
3006 exported_interface_free (ExportedInterface *ei)
3008 if (ei->user_data_free_func != NULL)
3009 /* TODO: push to thread-default mainloop */
3010 ei->user_data_free_func (ei->user_data);
3012 if (ei->context != NULL)
3013 g_main_context_unref (ei->context);
3015 g_free (ei->interface_name);
3019 /* ---------------------------------------------------------------------------------------------------- */
3021 /* Convenience function to check if @registration_id (if not zero) or
3022 * @subtree_registration_id (if not zero) has been unregistered. If
3023 * so, returns %TRUE.
3025 * Caller must *not* hold lock.
3028 has_object_been_unregistered (GDBusConnection *connection,
3029 guint registration_id,
3030 guint subtree_registration_id)
3034 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3038 CONNECTION_LOCK (connection);
3039 if (registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_ei,
3040 GUINT_TO_POINTER (registration_id)) == NULL)
3044 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_es,
3045 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3049 CONNECTION_UNLOCK (connection);
3054 /* ---------------------------------------------------------------------------------------------------- */
3058 GDBusConnection *connection;
3059 GDBusMessage *message;
3061 const gchar *property_name;
3062 const GDBusInterfaceVTable *vtable;
3063 const GDBusInterfaceInfo *interface_info;
3064 const GDBusPropertyInfo *property_info;
3065 guint registration_id;
3066 guint subtree_registration_id;
3070 property_data_free (PropertyData *data)
3072 g_object_unref (data->connection);
3073 g_object_unref (data->message);
3077 /* called in thread where object was registered - no locks held */
3079 invoke_get_property_in_idle_cb (gpointer _data)
3081 PropertyData *data = _data;
3084 GDBusMessage *reply;
3086 if (has_object_been_unregistered (data->connection,
3087 data->registration_id,
3088 data->subtree_registration_id))
3090 reply = g_dbus_message_new_method_error (data->message,
3091 "org.freedesktop.DBus.Error.UnknownMethod",
3092 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3093 g_dbus_message_get_path (data->message));
3094 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3095 g_object_unref (reply);
3100 value = data->vtable->get_property (data->connection,
3101 g_dbus_message_get_sender (data->message),
3102 g_dbus_message_get_path (data->message),
3103 data->interface_info->name,
3104 data->property_name,
3111 g_assert_no_error (error);
3113 g_variant_ref_sink (value);
3114 reply = g_dbus_message_new_method_reply (data->message);
3115 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3116 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3117 g_variant_unref (value);
3118 g_object_unref (reply);
3122 gchar *dbus_error_name;
3123 g_assert (error != NULL);
3124 dbus_error_name = g_dbus_error_encode_gerror (error);
3125 reply = g_dbus_message_new_method_error_literal (data->message,
3128 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3129 g_free (dbus_error_name);
3130 g_error_free (error);
3131 g_object_unref (reply);
3138 /* called in thread where object was registered - no locks held */
3140 invoke_set_property_in_idle_cb (gpointer _data)
3142 PropertyData *data = _data;
3144 GDBusMessage *reply;
3150 g_variant_get (g_dbus_message_get_body (data->message),
3156 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3157 * of the given value is wrong
3159 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3161 reply = g_dbus_message_new_method_error (data->message,
3162 "org.freedesktop.DBus.Error.InvalidArgs",
3163 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3164 data->property_info->name,
3165 data->property_info->signature,
3166 g_variant_get_type_string (value));
3170 if (!data->vtable->set_property (data->connection,
3171 g_dbus_message_get_sender (data->message),
3172 g_dbus_message_get_path (data->message),
3173 data->interface_info->name,
3174 data->property_name,
3179 gchar *dbus_error_name;
3180 g_assert (error != NULL);
3181 dbus_error_name = g_dbus_error_encode_gerror (error);
3182 reply = g_dbus_message_new_method_error_literal (data->message,
3185 g_free (dbus_error_name);
3186 g_error_free (error);
3190 reply = g_dbus_message_new_method_reply (data->message);
3194 g_assert (reply != NULL);
3195 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3196 g_object_unref (reply);
3201 /* called with lock held */
3203 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3204 GDBusMessage *message,
3205 guint registration_id,
3206 guint subtree_registration_id,
3208 const GDBusInterfaceInfo *introspection_data,
3209 const GDBusInterfaceVTable *vtable,
3210 GMainContext *main_context,
3214 const char *interface_name;
3215 const char *property_name;
3216 const GDBusPropertyInfo *property_info;
3217 GSource *idle_source;
3218 PropertyData *property_data;
3219 GDBusMessage *reply;
3224 g_variant_get (g_dbus_message_get_body (message),
3229 g_variant_get (g_dbus_message_get_body (message),
3238 if (vtable == NULL || vtable->get_property == NULL)
3243 if (vtable == NULL || vtable->set_property == NULL)
3247 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3249 property_info = NULL;
3251 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3252 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3253 if (property_info == NULL)
3255 reply = g_dbus_message_new_method_error (message,
3256 "org.freedesktop.DBus.Error.InvalidArgs",
3257 _("No such property `%s'"),
3259 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3260 g_object_unref (reply);
3265 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3267 reply = g_dbus_message_new_method_error (message,
3268 "org.freedesktop.DBus.Error.InvalidArgs",
3269 _("Property `%s' is not readable"),
3271 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3272 g_object_unref (reply);
3276 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3278 reply = g_dbus_message_new_method_error (message,
3279 "org.freedesktop.DBus.Error.InvalidArgs",
3280 _("Property `%s' is not writable"),
3282 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3283 g_object_unref (reply);
3288 /* ok, got the property info - call user code in an idle handler */
3289 property_data = g_new0 (PropertyData, 1);
3290 property_data->connection = g_object_ref (connection);
3291 property_data->message = g_object_ref (message);
3292 property_data->user_data = user_data;
3293 property_data->property_name = property_name;
3294 property_data->vtable = vtable;
3295 property_data->interface_info = introspection_data;
3296 property_data->property_info = property_info;
3297 property_data->registration_id = registration_id;
3298 property_data->subtree_registration_id = subtree_registration_id;
3300 idle_source = g_idle_source_new ();
3301 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3302 g_source_set_callback (idle_source,
3303 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3305 (GDestroyNotify) property_data_free);
3306 g_source_attach (idle_source, main_context);
3307 g_source_unref (idle_source);
3315 /* called with lock held */
3317 handle_getset_property (GDBusConnection *connection,
3319 GDBusMessage *message,
3322 ExportedInterface *ei;
3324 const char *interface_name;
3325 const char *property_name;
3330 g_variant_get (g_dbus_message_get_body (message),
3335 g_variant_get (g_dbus_message_get_body (message),
3341 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3342 * no such interface registered
3344 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3347 GDBusMessage *reply;
3348 reply = g_dbus_message_new_method_error (message,
3349 "org.freedesktop.DBus.Error.InvalidArgs",
3350 _("No such interface `%s'"),
3352 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3353 g_object_unref (reply);
3358 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3363 ei->introspection_data,
3371 /* ---------------------------------------------------------------------------------------------------- */
3375 GDBusConnection *connection;
3376 GDBusMessage *message;
3378 const GDBusInterfaceVTable *vtable;
3379 const GDBusInterfaceInfo *interface_info;
3380 guint registration_id;
3381 guint subtree_registration_id;
3382 } PropertyGetAllData;
3385 property_get_all_data_free (PropertyData *data)
3387 g_object_unref (data->connection);
3388 g_object_unref (data->message);
3392 /* called in thread where object was registered - no locks held */
3394 invoke_get_all_properties_in_idle_cb (gpointer _data)
3396 PropertyGetAllData *data = _data;
3397 GVariantBuilder builder;
3399 GDBusMessage *reply;
3402 if (has_object_been_unregistered (data->connection,
3403 data->registration_id,
3404 data->subtree_registration_id))
3406 reply = g_dbus_message_new_method_error (data->message,
3407 "org.freedesktop.DBus.Error.UnknownMethod",
3408 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3409 g_dbus_message_get_path (data->message));
3410 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3411 g_object_unref (reply);
3417 /* TODO: Right now we never fail this call - we just omit values if
3418 * a get_property() call is failing.
3420 * We could fail the whole call if just a single get_property() call
3421 * returns an error. We need clarification in the D-Bus spec about this.
3423 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3424 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3425 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3427 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3430 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3433 value = data->vtable->get_property (data->connection,
3434 g_dbus_message_get_sender (data->message),
3435 g_dbus_message_get_path (data->message),
3436 data->interface_info->name,
3437 property_info->name,
3444 g_variant_builder_add (&builder,
3446 property_info->name,
3449 g_variant_builder_close (&builder);
3451 reply = g_dbus_message_new_method_reply (data->message);
3452 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3453 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3454 g_object_unref (reply);
3460 /* called with lock held */
3462 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3463 GDBusMessage *message,
3464 guint registration_id,
3465 guint subtree_registration_id,
3466 const GDBusInterfaceInfo *introspection_data,
3467 const GDBusInterfaceVTable *vtable,
3468 GMainContext *main_context,
3472 const char *interface_name;
3473 GSource *idle_source;
3474 PropertyGetAllData *property_get_all_data;
3478 g_variant_get (g_dbus_message_get_body (message),
3482 if (vtable == NULL || vtable->get_property == NULL)
3485 /* ok, got the property info - call user in an idle handler */
3486 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3487 property_get_all_data->connection = g_object_ref (connection);
3488 property_get_all_data->message = g_object_ref (message);
3489 property_get_all_data->user_data = user_data;
3490 property_get_all_data->vtable = vtable;
3491 property_get_all_data->interface_info = introspection_data;
3492 property_get_all_data->registration_id = registration_id;
3493 property_get_all_data->subtree_registration_id = subtree_registration_id;
3495 idle_source = g_idle_source_new ();
3496 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3497 g_source_set_callback (idle_source,
3498 invoke_get_all_properties_in_idle_cb,
3499 property_get_all_data,
3500 (GDestroyNotify) property_get_all_data_free);
3501 g_source_attach (idle_source, main_context);
3502 g_source_unref (idle_source);
3510 /* called with lock held */
3512 handle_get_all_properties (GDBusConnection *connection,
3514 GDBusMessage *message)
3516 ExportedInterface *ei;
3518 const char *interface_name;
3522 g_variant_get (g_dbus_message_get_body (message),
3526 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3527 * no such interface registered
3529 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3532 GDBusMessage *reply;
3533 reply = g_dbus_message_new_method_error (message,
3534 "org.freedesktop.DBus.Error.InvalidArgs",
3535 _("No such interface"),
3537 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3538 g_object_unref (reply);
3543 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3547 ei->introspection_data,
3555 /* ---------------------------------------------------------------------------------------------------- */
3557 static const gchar introspect_header[] =
3558 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3559 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3560 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3563 static const gchar introspect_tail[] =
3566 static const gchar introspect_standard_interfaces[] =
3567 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3568 " <method name=\"Get\">\n"
3569 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3570 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3571 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3573 " <method name=\"GetAll\">\n"
3574 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3575 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3577 " <method name=\"Set\">\n"
3578 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3579 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3580 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3582 " <signal name=\"PropertiesChanged\">\n"
3583 " <arg type=\"s\" name=\"interface_name\"/>\n"
3584 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3585 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3588 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3589 " <method name=\"Introspect\">\n"
3590 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3593 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3594 " <method name=\"Ping\"/>\n"
3595 " <method name=\"GetMachineId\">\n"
3596 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3601 introspect_append_header (GString *s)
3603 g_string_append (s, introspect_header);
3607 introspect_append_standard_interfaces (GString *s)
3609 g_string_append (s, introspect_standard_interfaces);
3613 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3615 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len)
3621 begin = object_path + path_len;
3622 end = strchr (begin, '/');
3625 s = g_strndup (begin, end - begin);
3627 s = g_strdup (begin);
3629 if (g_hash_table_lookup (set, s) == NULL)
3630 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3636 /* TODO: we want a nicer public interface for this */
3638 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3643 GHashTableIter hash_iter;
3644 const gchar *object_path;
3650 CONNECTION_ENSURE_LOCK (connection);
3652 path_len = strlen (path);
3656 set = g_hash_table_new (g_str_hash, g_str_equal);
3658 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3659 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3660 maybe_add_path (path, path_len, object_path, set);
3662 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3663 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3664 maybe_add_path (path, path_len, object_path, set);
3666 p = g_ptr_array_new ();
3667 keys = g_hash_table_get_keys (set);
3668 for (l = keys; l != NULL; l = l->next)
3669 g_ptr_array_add (p, l->data);
3670 g_hash_table_unref (set);
3673 g_ptr_array_add (p, NULL);
3674 ret = (gchar **) g_ptr_array_free (p, FALSE);
3679 g_dbus_connection_list_registered (GDBusConnection *connection,
3683 CONNECTION_LOCK (connection);
3684 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3685 CONNECTION_UNLOCK (connection);
3689 /* called in message handler thread with lock held */
3691 handle_introspect (GDBusConnection *connection,
3693 GDBusMessage *message)
3697 GDBusMessage *reply;
3698 GHashTableIter hash_iter;
3699 ExportedInterface *ei;
3702 /* first the header with the standard interfaces */
3703 s = g_string_sized_new (sizeof (introspect_header) +
3704 sizeof (introspect_standard_interfaces) +
3705 sizeof (introspect_tail));
3706 introspect_append_header (s);
3707 introspect_append_standard_interfaces (s);
3709 /* then include the registered interfaces */
3710 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3711 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3712 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3714 /* finally include nodes registered below us */
3715 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3716 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3717 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3718 g_strfreev (registered);
3719 g_string_append (s, introspect_tail);
3721 reply = g_dbus_message_new_method_reply (message);
3722 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3723 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3724 g_object_unref (reply);
3725 g_string_free (s, TRUE);
3730 /* called in thread where object was registered - no locks held */
3732 call_in_idle_cb (gpointer user_data)
3734 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3735 GDBusInterfaceVTable *vtable;
3736 guint registration_id;
3737 guint subtree_registration_id;
3739 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3740 g_assert (vtable != NULL && vtable->method_call != NULL);
3742 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
3743 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
3745 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
3747 subtree_registration_id))
3749 GDBusMessage *reply;
3750 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
3751 "org.freedesktop.DBus.Error.UnknownMethod",
3752 _("No such interface `%s' on object at path %s"),
3753 g_dbus_method_invocation_get_interface_name (invocation),
3754 g_dbus_method_invocation_get_object_path (invocation));
3755 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, NULL, NULL);
3756 g_object_unref (reply);
3760 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3761 g_dbus_method_invocation_get_sender (invocation),
3762 g_dbus_method_invocation_get_object_path (invocation),
3763 g_dbus_method_invocation_get_interface_name (invocation),
3764 g_dbus_method_invocation_get_method_name (invocation),
3765 g_dbus_method_invocation_get_parameters (invocation),
3766 g_object_ref (invocation),
3767 g_dbus_method_invocation_get_user_data (invocation));
3773 /* called in message handler thread with lock held */
3775 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3776 GDBusMessage *message,
3777 guint registration_id,
3778 guint subtree_registration_id,
3779 const GDBusInterfaceInfo *introspection_data,
3780 const GDBusInterfaceVTable *vtable,
3781 GMainContext *main_context,
3784 GDBusMethodInvocation *invocation;
3785 const GDBusMethodInfo *method_info;
3786 GDBusMessage *reply;
3787 GVariant *parameters;
3788 GSource *idle_source;
3790 GVariantType *in_type;
3794 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3795 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3797 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3798 * error to the caller
3800 if (method_info == NULL)
3802 reply = g_dbus_message_new_method_error (message,
3803 "org.freedesktop.DBus.Error.UnknownMethod",
3804 _("No such method `%s'"),
3805 g_dbus_message_get_member (message));
3806 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3807 g_object_unref (reply);
3812 parameters = g_dbus_message_get_body (message);
3813 if (parameters == NULL)
3815 parameters = g_variant_new ("()");
3816 g_variant_ref_sink (parameters);
3820 g_variant_ref (parameters);
3823 /* Check that the incoming args are of the right type - if they are not, return
3824 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3826 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
3827 if (!g_variant_is_of_type (parameters, in_type))
3831 type_string = g_variant_type_dup_string (in_type);
3833 reply = g_dbus_message_new_method_error (message,
3834 "org.freedesktop.DBus.Error.InvalidArgs",
3835 _("Type of message, `%s', does not match expected type `%s'"),
3836 g_variant_get_type_string (parameters),
3838 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3839 g_variant_type_free (in_type);
3840 g_variant_unref (parameters);
3841 g_object_unref (reply);
3842 g_free (type_string);
3846 g_variant_type_free (in_type);
3848 /* schedule the call in idle */
3849 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3850 g_dbus_message_get_path (message),
3851 g_dbus_message_get_interface (message),
3852 g_dbus_message_get_member (message),
3858 g_variant_unref (parameters);
3860 /* TODO: would be nicer with a real MethodData like we already
3861 * have PropertyData and PropertyGetAllData... */
3862 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
3863 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
3864 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
3866 idle_source = g_idle_source_new ();
3867 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3868 g_source_set_callback (idle_source,
3872 g_source_attach (idle_source, main_context);
3873 g_source_unref (idle_source);
3881 /* ---------------------------------------------------------------------------------------------------- */
3883 /* called in message handler thread with lock held */
3885 obj_message_func (GDBusConnection *connection,
3887 GDBusMessage *message)
3889 const gchar *interface_name;
3890 const gchar *member;
3891 const gchar *signature;
3896 interface_name = g_dbus_message_get_interface (message);
3897 member = g_dbus_message_get_member (message);
3898 signature = g_dbus_message_get_signature (message);
3900 /* see if we have an interface for handling this call */
3901 if (interface_name != NULL)
3903 ExportedInterface *ei;
3904 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3907 /* we do - invoke the handler in idle in the right thread */
3909 /* handle no vtable or handler being present */
3910 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3913 handled = validate_and_maybe_schedule_method_call (connection,
3917 ei->introspection_data,
3925 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3926 g_strcmp0 (member, "Introspect") == 0 &&
3927 g_strcmp0 (signature, "") == 0)
3929 handled = handle_introspect (connection, eo, message);
3932 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3933 g_strcmp0 (member, "Get") == 0 &&
3934 g_strcmp0 (signature, "ss") == 0)
3936 handled = handle_getset_property (connection, eo, message, TRUE);
3939 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3940 g_strcmp0 (member, "Set") == 0 &&
3941 g_strcmp0 (signature, "ssv") == 0)
3943 handled = handle_getset_property (connection, eo, message, FALSE);
3946 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3947 g_strcmp0 (member, "GetAll") == 0 &&
3948 g_strcmp0 (signature, "s") == 0)
3950 handled = handle_get_all_properties (connection, eo, message);
3959 * g_dbus_connection_register_object:
3960 * @connection: A #GDBusConnection.
3961 * @object_path: The object path to register at.
3962 * @introspection_data: Introspection data for the interface.
3963 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3964 * @user_data: Data to pass to functions in @vtable.
3965 * @user_data_free_func: Function to call when the object path is unregistered.
3966 * @error: Return location for error or %NULL.
3968 * Registers callbacks for exported objects at @object_path with the
3969 * D-Bus interface that is described in @introspection_data.
3971 * Calls to functions in @vtable (and @user_data_free_func) will
3972 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3973 * loop</link> of the thread you are calling this method from.
3975 * Note that all #GVariant values passed to functions in @vtable will match
3976 * the signature given in @introspection_data - if a remote caller passes
3977 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3978 * is returned to the remote caller.
3980 * Additionally, if the remote caller attempts to invoke methods or
3981 * access properties not mentioned in @introspection_data the
3982 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3983 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3984 * are returned to the caller.
3986 * It is considered a programming error if the
3987 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3988 * #GVariant of incorrect type.
3990 * If an existing callback is already registered at @object_path and
3991 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3993 * Note that @vtable is not copied, so the struct you pass must exist until
3994 * the path is unregistered. One possibility is to free @vtable at the
3995 * same time as @user_data when @user_data_free_func is called.
3997 * GDBus automatically implements the standard D-Bus interfaces
3998 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
3999 * and org.freedesktop.Peer, so you don't have to implement those for
4000 * the objects you export. You <emphasis>can</emphasis> implement
4001 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4002 * and setting of properties asynchronously.
4004 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4006 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4007 * that can be used with g_dbus_connection_unregister_object() .
4012 g_dbus_connection_register_object (GDBusConnection *connection,
4013 const gchar *object_path,
4014 const GDBusInterfaceInfo *introspection_data,
4015 const GDBusInterfaceVTable *vtable,
4017 GDestroyNotify user_data_free_func,
4021 ExportedInterface *ei;
4024 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4025 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
4026 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4027 g_return_val_if_fail (introspection_data != NULL, 0);
4028 g_return_val_if_fail (g_dbus_is_interface_name (introspection_data->name), 0);
4029 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4033 CONNECTION_LOCK (connection);
4035 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
4038 eo = g_new0 (ExportedObject, 1);
4039 eo->object_path = g_strdup (object_path);
4040 eo->connection = connection;
4041 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4044 (GDestroyNotify) exported_interface_free);
4045 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
4048 ei = g_hash_table_lookup (eo->map_if_name_to_ei, introspection_data->name);
4054 _("An object is already exported for the interface %s at %s"),
4055 introspection_data->name,
4060 ei = g_new0 (ExportedInterface, 1);
4061 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4063 ei->user_data = user_data;
4064 ei->user_data_free_func = user_data_free_func;
4065 ei->vtable = vtable;
4066 ei->introspection_data = introspection_data;
4067 ei->interface_name = g_strdup (introspection_data->name);
4068 ei->context = g_main_context_get_thread_default ();
4069 if (ei->context != NULL)
4070 g_main_context_ref (ei->context);
4072 g_hash_table_insert (eo->map_if_name_to_ei,
4073 (gpointer) ei->interface_name,
4075 g_hash_table_insert (connection->priv->map_id_to_ei,
4076 GUINT_TO_POINTER (ei->id),
4082 CONNECTION_UNLOCK (connection);
4088 * g_dbus_connection_unregister_object:
4089 * @connection: A #GDBusConnection.
4090 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4092 * Unregisters an object.
4094 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4099 g_dbus_connection_unregister_object (GDBusConnection *connection,
4100 guint registration_id)
4102 ExportedInterface *ei;
4106 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4110 CONNECTION_LOCK (connection);
4112 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4113 GUINT_TO_POINTER (registration_id));
4119 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4120 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4121 /* unregister object path if we have no more exported interfaces */
4122 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4123 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4129 CONNECTION_UNLOCK (connection);
4134 /* ---------------------------------------------------------------------------------------------------- */
4137 * g_dbus_connection_emit_signal:
4138 * @connection: A #GDBusConnection.
4139 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4140 * @object_path: Path of remote object.
4141 * @interface_name: D-Bus interface to emit a signal on.
4142 * @signal_name: The name of the signal to emit.
4143 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4144 * @error: Return location for error or %NULL.
4148 * If the parameters GVariant is floating, it is consumed.
4150 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4152 * Returns: %TRUE unless @error is set.
4157 g_dbus_connection_emit_signal (GDBusConnection *connection,
4158 const gchar *destination_bus_name,
4159 const gchar *object_path,
4160 const gchar *interface_name,
4161 const gchar *signal_name,
4162 GVariant *parameters,
4165 GDBusMessage *message;
4171 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4172 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4173 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4174 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4175 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4176 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4178 message = g_dbus_message_new_signal (object_path,
4182 if (destination_bus_name != NULL)
4183 g_dbus_message_set_header (message,
4184 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4185 g_variant_new_string (destination_bus_name));
4187 if (parameters != NULL)
4188 g_dbus_message_set_body (message, parameters);
4190 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4191 g_object_unref (message);
4197 add_call_flags (GDBusMessage *message,
4198 GDBusCallFlags flags)
4200 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4201 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4205 decode_method_reply (GDBusMessage *reply,
4206 const gchar *method_name,
4207 const GVariantType *reply_type,
4213 switch (g_dbus_message_get_message_type (reply))
4215 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4216 result = g_dbus_message_get_body (reply);
4219 result = g_variant_new ("()");
4220 g_variant_ref_sink (result);
4224 g_variant_ref (result);
4227 if (!g_variant_is_of_type (result, reply_type))
4229 gchar *type_string = g_variant_type_dup_string (reply_type);
4233 G_IO_ERROR_INVALID_ARGUMENT,
4234 _("Method `%s' returned type `%s', but expected `%s'"),
4235 method_name, g_variant_get_type_string (result), type_string);
4237 g_variant_unref (result);
4238 g_free (type_string);
4243 case G_DBUS_MESSAGE_TYPE_ERROR:
4244 g_dbus_message_to_gerror (reply, error);
4248 g_assert_not_reached ();
4258 GSimpleAsyncResult *simple;
4259 GVariantType *reply_type;
4260 gchar *method_name; /* for error message */
4264 g_dbus_connection_call_done (GObject *source,
4265 GAsyncResult *result,
4268 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4269 CallState *state = user_data;
4270 GError *error = NULL;
4271 GDBusMessage *reply;
4274 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4279 value = decode_method_reply (reply, state->method_name,
4280 state->reply_type, &error);
4281 g_object_unref (reply);
4288 g_simple_async_result_set_from_error (state->simple, error);
4289 g_error_free (error);
4292 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4293 (GDestroyNotify) g_variant_unref);
4295 g_simple_async_result_complete (state->simple);
4296 g_variant_type_free (state->reply_type);
4297 g_object_unref (state->simple);
4298 g_free (state->method_name);
4300 g_slice_free (CallState, state);
4304 * g_dbus_connection_call:
4305 * @connection: A #GDBusConnection.
4306 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4307 * @object_path: Path of remote object.
4308 * @interface_name: D-Bus interface to invoke method on.
4309 * @method_name: The name of the method to invoke.
4310 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4311 * @reply_type: The expected type of the reply, or %NULL.
4312 * @flags: Flags from the #GDBusCallFlags enumeration.
4313 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4314 * @cancellable: A #GCancellable or %NULL.
4315 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4316 * care about the result of the method invocation.
4317 * @user_data: The data to pass to @callback.
4319 * Asynchronously invokes the @method_name method on the
4320 * @interface_name D-Bus interface on the remote object at
4321 * @object_path owned by @bus_name.
4323 * If @connection is closed then the operation will fail with
4324 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4325 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4326 * not compatible with the D-Bus protocol, the operation fails with
4327 * %G_IO_ERROR_INVALID_ARGUMENT.
4329 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4330 * error will be raised if it does not match. Said another way, if you give a @reply_type
4331 * then any non-%NULL return value will be of this type.
4333 * If the @parameters #GVariant is floating, it is consumed. This allows
4334 * convenient 'inline' use of g_variant_new(), e.g.:
4336 * g_dbus_connection_call (connection,
4337 * "org.freedesktop.StringThings",
4338 * "/org/freedesktop/StringThings",
4339 * "org.freedesktop.StringThings",
4341 * g_variant_new ("(ss)",
4345 * G_DBUS_CALL_FLAGS_NONE,
4348 * (GAsyncReadyCallback) two_strings_done,
4352 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4353 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4354 * of the thread you are calling this method from. You can then call
4355 * g_dbus_connection_call_finish() to get the result of the operation.
4356 * See g_dbus_connection_call_sync() for the synchronous version of this
4362 g_dbus_connection_call (GDBusConnection *connection,
4363 const gchar *bus_name,
4364 const gchar *object_path,
4365 const gchar *interface_name,
4366 const gchar *method_name,
4367 GVariant *parameters,
4368 const GVariantType *reply_type,
4369 GDBusCallFlags flags,
4371 GCancellable *cancellable,
4372 GAsyncReadyCallback callback,
4375 GDBusMessage *message;
4378 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4379 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4380 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4381 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4382 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4383 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4384 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4386 state = g_slice_new (CallState);
4387 state->simple = g_simple_async_result_new (G_OBJECT (connection),
4388 callback, user_data,
4389 g_dbus_connection_call);
4390 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4392 if (reply_type == NULL)
4393 reply_type = G_VARIANT_TYPE_ANY;
4395 state->reply_type = g_variant_type_copy (reply_type);
4397 message = g_dbus_message_new_method_call (bus_name,
4401 add_call_flags (message, flags);
4402 if (parameters != NULL)
4403 g_dbus_message_set_body (message, parameters);
4405 g_dbus_connection_send_message_with_reply (connection,
4408 NULL, /* volatile guint32 *out_serial */
4410 g_dbus_connection_call_done,
4413 if (message != NULL)
4414 g_object_unref (message);
4418 * g_dbus_connection_call_finish:
4419 * @connection: A #GDBusConnection.
4420 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4421 * @error: Return location for error or %NULL.
4423 * Finishes an operation started with g_dbus_connection_call().
4425 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4426 * return values. Free with g_variant_unref().
4431 g_dbus_connection_call_finish (GDBusConnection *connection,
4435 GSimpleAsyncResult *simple;
4437 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4438 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
4439 g_dbus_connection_call), NULL);
4440 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4442 simple = G_SIMPLE_ASYNC_RESULT (res);
4444 if (g_simple_async_result_propagate_error (simple, error))
4447 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
4450 /* ---------------------------------------------------------------------------------------------------- */
4453 * g_dbus_connection_call_sync:
4454 * @connection: A #GDBusConnection.
4455 * @bus_name: A unique or well-known bus name.
4456 * @object_path: Path of remote object.
4457 * @interface_name: D-Bus interface to invoke method on.
4458 * @method_name: The name of the method to invoke.
4459 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4460 * @reply_type: The expected type of the reply, or %NULL.
4461 * @flags: Flags from the #GDBusCallFlags enumeration.
4462 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4463 * @cancellable: A #GCancellable or %NULL.
4464 * @error: Return location for error or %NULL.
4466 * Synchronously invokes the @method_name method on the
4467 * @interface_name D-Bus interface on the remote object at
4468 * @object_path owned by @bus_name.
4470 * If @connection is closed then the operation will fail with
4471 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4472 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4473 * contains a value not compatible with the D-Bus protocol, the operation
4474 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4476 * If @reply_type is non-%NULL then the reply will be checked for having
4477 * this type and an error will be raised if it does not match. Said
4478 * another way, if you give a @reply_type then any non-%NULL return
4479 * value will be of this type.
4481 * If the @parameters #GVariant is floating, it is consumed.
4482 * This allows convenient 'inline' use of g_variant_new(), e.g.:
4484 * g_dbus_connection_call_sync (connection,
4485 * "org.freedesktop.StringThings",
4486 * "/org/freedesktop/StringThings",
4487 * "org.freedesktop.StringThings",
4489 * g_variant_new ("(ss)",
4493 * G_DBUS_CALL_FLAGS_NONE,
4499 * The calling thread is blocked until a reply is received. See
4500 * g_dbus_connection_call() for the asynchronous version of
4503 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4504 * return values. Free with g_variant_unref().
4509 g_dbus_connection_call_sync (GDBusConnection *connection,
4510 const gchar *bus_name,
4511 const gchar *object_path,
4512 const gchar *interface_name,
4513 const gchar *method_name,
4514 GVariant *parameters,
4515 const GVariantType *reply_type,
4516 GDBusCallFlags flags,
4518 GCancellable *cancellable,
4521 GDBusMessage *message;
4522 GDBusMessage *reply;
4529 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4530 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4531 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4532 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4533 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4534 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4535 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4537 if (reply_type == NULL)
4538 reply_type = G_VARIANT_TYPE_ANY;
4540 message = g_dbus_message_new_method_call (bus_name,
4544 add_call_flags (message, flags);
4545 if (parameters != NULL)
4546 g_dbus_message_set_body (message, parameters);
4548 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4551 NULL, /* volatile guint32 *out_serial */
4558 result = decode_method_reply (reply, method_name, reply_type, error);
4561 if (message != NULL)
4562 g_object_unref (message);
4564 g_object_unref (reply);
4569 /* ---------------------------------------------------------------------------------------------------- */
4571 struct ExportedSubtree
4575 GDBusConnection *connection;
4576 const GDBusSubtreeVTable *vtable;
4577 GDBusSubtreeFlags flags;
4579 GMainContext *context;
4581 GDestroyNotify user_data_free_func;
4585 exported_subtree_free (ExportedSubtree *es)
4587 if (es->user_data_free_func != NULL)
4588 /* TODO: push to thread-default mainloop */
4589 es->user_data_free_func (es->user_data);
4591 if (es->context != NULL)
4592 g_main_context_unref (es->context);
4594 g_free (es->object_path);
4598 /* called without lock held */
4600 handle_subtree_introspect (GDBusConnection *connection,
4601 ExportedSubtree *es,
4602 GDBusMessage *message)
4606 GDBusMessage *reply;
4609 const gchar *sender;
4610 const gchar *requested_object_path;
4611 const gchar *requested_node;
4612 GPtrArray *interfaces;
4614 gchar **subnode_paths;
4618 requested_object_path = g_dbus_message_get_path (message);
4619 sender = g_dbus_message_get_sender (message);
4620 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4622 s = g_string_new (NULL);
4623 introspect_append_header (s);
4625 /* Strictly we don't need the children in dynamic mode, but we avoid the
4626 * conditionals to preserve code clarity
4628 children = es->vtable->enumerate (es->connection,
4635 requested_node = strrchr (requested_object_path, '/') + 1;
4637 /* Assert existence of object if we are not dynamic */
4638 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4639 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4644 requested_node = "/";
4647 interfaces = es->vtable->introspect (es->connection,
4652 if (interfaces != NULL)
4654 if (interfaces->len > 0)
4656 /* we're in business */
4657 introspect_append_standard_interfaces (s);
4659 for (n = 0; n < interfaces->len; n++)
4661 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4662 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4665 g_ptr_array_unref (interfaces);
4668 /* then include <node> entries from the Subtree for the root */
4671 for (n = 0; children != NULL && children[n] != NULL; n++)
4672 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4675 /* finally include nodes registered below us */
4676 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4677 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4678 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4679 g_strfreev (subnode_paths);
4681 g_string_append (s, "</node>\n");
4683 reply = g_dbus_message_new_method_reply (message);
4684 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4685 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4686 g_object_unref (reply);
4691 g_string_free (s, TRUE);
4692 g_strfreev (children);
4696 /* called without lock held */
4698 handle_subtree_method_invocation (GDBusConnection *connection,
4699 ExportedSubtree *es,
4700 GDBusMessage *message)
4703 const gchar *sender;
4704 const gchar *interface_name;
4705 const gchar *member;
4706 const gchar *signature;
4707 const gchar *requested_object_path;
4708 const gchar *requested_node;
4711 const GDBusInterfaceInfo *introspection_data;
4712 const GDBusInterfaceVTable *interface_vtable;
4713 gpointer interface_user_data;
4715 GPtrArray *interfaces;
4716 gboolean is_property_get;
4717 gboolean is_property_set;
4718 gboolean is_property_get_all;
4723 requested_object_path = g_dbus_message_get_path (message);
4724 sender = g_dbus_message_get_sender (message);
4725 interface_name = g_dbus_message_get_interface (message);
4726 member = g_dbus_message_get_member (message);
4727 signature = g_dbus_message_get_signature (message);
4728 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4730 is_property_get = FALSE;
4731 is_property_set = FALSE;
4732 is_property_get_all = FALSE;
4733 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4735 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4736 is_property_get = TRUE;
4737 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4738 is_property_set = TRUE;
4739 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4740 is_property_get_all = TRUE;
4743 children = es->vtable->enumerate (es->connection,
4750 requested_node = strrchr (requested_object_path, '/') + 1;
4752 /* If not dynamic, skip if requested node is not part of children */
4753 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4754 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4759 requested_node = "/";
4762 /* get introspection data for the node */
4763 interfaces = es->vtable->introspect (es->connection,
4765 requested_object_path,
4768 g_assert (interfaces != NULL);
4769 introspection_data = NULL;
4770 for (n = 0; n < interfaces->len; n++)
4772 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4773 if (g_strcmp0 (id_n->name, interface_name) == 0)
4774 introspection_data = id_n;
4777 /* dispatch the call if the user wants to handle it */
4778 if (introspection_data != NULL)
4780 /* figure out where to dispatch the method call */
4781 interface_user_data = NULL;
4782 interface_vtable = es->vtable->dispatch (es->connection,
4787 &interface_user_data,
4789 if (interface_vtable == NULL)
4792 CONNECTION_LOCK (connection);
4793 handled = validate_and_maybe_schedule_method_call (es->connection,
4800 interface_user_data);
4801 CONNECTION_UNLOCK (connection);
4803 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4804 else if (is_property_get || is_property_set || is_property_get_all)
4806 if (is_property_get)
4807 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
4808 else if (is_property_set)
4809 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
4810 else if (is_property_get_all)
4811 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
4813 g_assert_not_reached ();
4815 /* see if the object supports this interface at all */
4816 for (n = 0; n < interfaces->len; n++)
4818 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4819 if (g_strcmp0 (id_n->name, interface_name) == 0)
4820 introspection_data = id_n;
4823 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4824 * claims it won't support the interface
4826 if (introspection_data == NULL)
4828 GDBusMessage *reply;
4829 reply = g_dbus_message_new_method_error (message,
4830 "org.freedesktop.DBus.Error.InvalidArgs",
4831 _("No such interface `%s'"),
4833 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4834 g_object_unref (reply);
4839 /* figure out where to dispatch the property get/set/getall calls */
4840 interface_user_data = NULL;
4841 interface_vtable = es->vtable->dispatch (es->connection,
4846 &interface_user_data,
4848 if (interface_vtable == NULL)
4851 if (is_property_get || is_property_set)
4853 CONNECTION_LOCK (connection);
4854 handled = validate_and_maybe_schedule_property_getset (es->connection,
4862 interface_user_data);
4863 CONNECTION_UNLOCK (connection);
4865 else if (is_property_get_all)
4867 CONNECTION_LOCK (connection);
4868 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4875 interface_user_data);
4876 CONNECTION_UNLOCK (connection);
4881 if (interfaces != NULL)
4882 g_ptr_array_unref (interfaces);
4883 g_strfreev (children);
4889 GDBusMessage *message;
4890 ExportedSubtree *es;
4891 } SubtreeDeferredData;
4894 subtree_deferred_data_free (SubtreeDeferredData *data)
4896 g_object_unref (data->message);
4900 /* called without lock held in the thread where the caller registered the subtree */
4902 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4904 SubtreeDeferredData *data = _data;
4909 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4910 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4911 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4912 handled = handle_subtree_introspect (data->es->connection,
4916 handled = handle_subtree_method_invocation (data->es->connection,
4922 CONNECTION_LOCK (data->es->connection);
4923 handled = handle_generic_unlocked (data->es->connection, data->message);
4924 CONNECTION_UNLOCK (data->es->connection);
4927 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4930 GDBusMessage *reply;
4931 reply = g_dbus_message_new_method_error (data->message,
4932 "org.freedesktop.DBus.Error.UnknownMethod",
4933 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4934 g_dbus_message_get_member (data->message),
4935 g_dbus_message_get_interface (data->message),
4936 g_dbus_message_get_signature (data->message));
4937 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4938 g_object_unref (reply);
4944 /* called in message handler thread with lock held */
4946 subtree_message_func (GDBusConnection *connection,
4947 ExportedSubtree *es,
4948 GDBusMessage *message)
4950 GSource *idle_source;
4951 SubtreeDeferredData *data;
4953 data = g_new0 (SubtreeDeferredData, 1);
4954 data->message = g_object_ref (message);
4957 /* defer this call to an idle handler in the right thread */
4958 idle_source = g_idle_source_new ();
4959 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4960 g_source_set_callback (idle_source,
4961 process_subtree_vtable_message_in_idle_cb,
4963 (GDestroyNotify) subtree_deferred_data_free);
4964 g_source_attach (idle_source, es->context);
4965 g_source_unref (idle_source);
4967 /* since we own the entire subtree, handlers for objects not in the subtree have been
4968 * tried already by libdbus-1 - so we just need to ensure that we're always going
4969 * to reply to the message
4975 * g_dbus_connection_register_subtree:
4976 * @connection: A #GDBusConnection.
4977 * @object_path: The object path to register the subtree at.
4978 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4979 * @flags: Flags used to fine tune the behavior of the subtree.
4980 * @user_data: Data to pass to functions in @vtable.
4981 * @user_data_free_func: Function to call when the subtree is unregistered.
4982 * @error: Return location for error or %NULL.
4984 * Registers a whole subtree of <quote>dynamic</quote> objects.
4986 * The @enumerate and @introspection functions in @vtable are used to
4987 * convey, to remote callers, what nodes exist in the subtree rooted
4990 * When handling remote calls into any node in the subtree, first the
4991 * @enumerate function is used to check if the node exists. If the node exists
4992 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4993 * the @introspection function is used to check if the node supports the
4994 * requested method. If so, the @dispatch function is used to determine
4995 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4996 * #gpointer will be used to call into the interface vtable for processing
4999 * All calls into user-provided code will be invoked in the <link
5000 * linkend="g-main-context-push-thread-default">thread-default main
5001 * loop</link> of the thread you are calling this method from.
5003 * If an existing subtree is already registered at @object_path or
5004 * then @error is set to #G_IO_ERROR_EXISTS.
5006 * Note that it is valid to register regular objects (using
5007 * g_dbus_connection_register_object()) in a subtree registered with
5008 * g_dbus_connection_register_subtree() - if so, the subtree handler
5009 * is tried as the last resort. One way to think about a subtree
5010 * handler is to consider it a <quote>fallback handler</quote>
5011 * for object paths not registered via g_dbus_connection_register_object()
5012 * or other bindings.
5014 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5016 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5017 * that can be used with g_dbus_connection_unregister_subtree() .
5022 g_dbus_connection_register_subtree (GDBusConnection *connection,
5023 const gchar *object_path,
5024 const GDBusSubtreeVTable *vtable,
5025 GDBusSubtreeFlags flags,
5027 GDestroyNotify user_data_free_func,
5031 ExportedSubtree *es;
5033 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5034 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5035 g_return_val_if_fail (vtable != NULL, 0);
5036 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5040 CONNECTION_LOCK (connection);
5042 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5048 _("A subtree is already exported for %s"),
5053 es = g_new0 (ExportedSubtree, 1);
5054 es->object_path = g_strdup (object_path);
5055 es->connection = connection;
5057 es->vtable = vtable;
5059 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5060 es->user_data = user_data;
5061 es->user_data_free_func = user_data_free_func;
5062 es->context = g_main_context_get_thread_default ();
5063 if (es->context != NULL)
5064 g_main_context_ref (es->context);
5066 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
5067 g_hash_table_insert (connection->priv->map_id_to_es,
5068 GUINT_TO_POINTER (es->id),
5074 CONNECTION_UNLOCK (connection);
5079 /* ---------------------------------------------------------------------------------------------------- */
5082 * g_dbus_connection_unregister_subtree:
5083 * @connection: A #GDBusConnection.
5084 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5086 * Unregisters a subtree.
5088 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5093 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5094 guint registration_id)
5096 ExportedSubtree *es;
5099 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5103 CONNECTION_LOCK (connection);
5105 es = g_hash_table_lookup (connection->priv->map_id_to_es,
5106 GUINT_TO_POINTER (registration_id));
5110 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
5111 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
5116 CONNECTION_UNLOCK (connection);
5121 /* ---------------------------------------------------------------------------------------------------- */
5123 /* must be called with lock held */
5125 handle_generic_ping_unlocked (GDBusConnection *connection,
5126 const gchar *object_path,
5127 GDBusMessage *message)
5129 GDBusMessage *reply;
5130 reply = g_dbus_message_new_method_reply (message);
5131 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5132 g_object_unref (reply);
5135 /* must be called with lock held */
5137 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5138 const gchar *object_path,
5139 GDBusMessage *message)
5141 GDBusMessage *reply;
5144 if (connection->priv->machine_id == NULL)
5148 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
5149 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
5150 &connection->priv->machine_id,
5154 reply = g_dbus_message_new_method_error (message,
5155 "org.freedesktop.DBus.Error.Failed",
5156 _("Unable to load /var/lib/dbus/machine-id: %s"),
5158 g_error_free (error);
5162 g_strstrip (connection->priv->machine_id);
5163 /* TODO: validate value */
5169 reply = g_dbus_message_new_method_reply (message);
5170 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5172 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5173 g_object_unref (reply);
5176 /* must be called with lock held */
5178 handle_generic_introspect_unlocked (GDBusConnection *connection,
5179 const gchar *object_path,
5180 GDBusMessage *message)
5185 GDBusMessage *reply;
5187 /* first the header */
5188 s = g_string_new (NULL);
5189 introspect_append_header (s);
5191 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5192 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5193 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5194 g_strfreev (registered);
5195 g_string_append (s, "</node>\n");
5197 reply = g_dbus_message_new_method_reply (message);
5198 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5199 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5200 g_object_unref (reply);
5201 g_string_free (s, TRUE);
5204 /* must be called with lock held */
5206 handle_generic_unlocked (GDBusConnection *connection,
5207 GDBusMessage *message)
5210 const gchar *interface_name;
5211 const gchar *member;
5212 const gchar *signature;
5215 CONNECTION_ENSURE_LOCK (connection);
5219 interface_name = g_dbus_message_get_interface (message);
5220 member = g_dbus_message_get_member (message);
5221 signature = g_dbus_message_get_signature (message);
5222 path = g_dbus_message_get_path (message);
5224 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5225 g_strcmp0 (member, "Introspect") == 0 &&
5226 g_strcmp0 (signature, "") == 0)
5228 handle_generic_introspect_unlocked (connection, path, message);
5231 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5232 g_strcmp0 (member, "Ping") == 0 &&
5233 g_strcmp0 (signature, "") == 0)
5235 handle_generic_ping_unlocked (connection, path, message);
5238 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5239 g_strcmp0 (member, "GetMachineId") == 0 &&
5240 g_strcmp0 (signature, "") == 0)
5242 handle_generic_get_machine_id_unlocked (connection, path, message);
5249 /* ---------------------------------------------------------------------------------------------------- */
5251 /* called in message handler thread with lock held */
5253 distribute_method_call (GDBusConnection *connection,
5254 GDBusMessage *message)
5256 GDBusMessage *reply;
5258 ExportedSubtree *es;
5259 const gchar *object_path;
5260 const gchar *interface_name;
5261 const gchar *member;
5262 const gchar *signature;
5264 gchar *subtree_path;
5267 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5269 interface_name = g_dbus_message_get_interface (message);
5270 member = g_dbus_message_get_member (message);
5271 signature = g_dbus_message_get_signature (message);
5272 path = g_dbus_message_get_path (message);
5273 subtree_path = g_strdup (path);
5274 needle = strrchr (subtree_path, '/');
5275 if (needle != NULL && needle != subtree_path)
5281 g_free (subtree_path);
5282 subtree_path = NULL;
5286 g_debug ("interface = `%s'", interface_name);
5287 g_debug ("member = `%s'", member);
5288 g_debug ("signature = `%s'", signature);
5289 g_debug ("path = `%s'", path);
5290 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5293 object_path = g_dbus_message_get_path (message);
5294 g_assert (object_path != NULL);
5296 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5299 if (obj_message_func (connection, eo, message))
5303 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5306 if (subtree_message_func (connection, es, message))
5310 if (subtree_path != NULL)
5312 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5315 if (subtree_message_func (connection, es, message))
5320 if (handle_generic_unlocked (connection, message))
5323 /* if we end up here, the message has not been not handled - so return an error saying this */
5324 reply = g_dbus_message_new_method_error (message,
5325 "org.freedesktop.DBus.Error.UnknownMethod",
5326 _("No such interface `%s' on object at path %s"),
5329 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5330 g_object_unref (reply);
5333 g_free (subtree_path);
5336 /* ---------------------------------------------------------------------------------------------------- */
5338 static GDBusConnection **
5339 message_bus_get_singleton (GBusType bus_type,
5342 GDBusConnection **ret;
5343 const gchar *starter_bus;
5349 case G_BUS_TYPE_SESSION:
5350 ret = &the_session_bus;
5353 case G_BUS_TYPE_SYSTEM:
5354 ret = &the_system_bus;
5357 case G_BUS_TYPE_STARTER:
5358 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5359 if (g_strcmp0 (starter_bus, "session") == 0)
5361 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5364 else if (g_strcmp0 (starter_bus, "system") == 0)
5366 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5371 if (starter_bus != NULL)
5375 G_IO_ERROR_INVALID_ARGUMENT,
5376 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5377 " - unknown value `%s'"),
5382 g_set_error_literal (error,
5384 G_IO_ERROR_INVALID_ARGUMENT,
5385 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5386 "variable is not set"));
5392 g_assert_not_reached ();
5400 static GDBusConnection *
5401 get_uninitialized_connection (GBusType bus_type,
5402 GCancellable *cancellable,
5405 GDBusConnection **singleton;
5406 GDBusConnection *ret;
5410 G_LOCK (message_bus_lock);
5411 singleton = message_bus_get_singleton (bus_type, error);
5412 if (singleton == NULL)
5415 if (*singleton == NULL)
5418 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5419 if (address == NULL)
5421 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5423 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5424 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5425 "exit-on-close", TRUE,
5431 ret = g_object_ref (*singleton);
5434 g_assert (ret != NULL);
5437 G_UNLOCK (message_bus_lock);
5443 * @bus_type: A #GBusType.
5444 * @cancellable: A #GCancellable or %NULL.
5445 * @error: Return location for error or %NULL.
5447 * Synchronously connects to the message bus specified by @bus_type.
5448 * Note that the returned object may shared with other callers,
5449 * e.g. if two separate parts of a process calls this function with
5450 * the same @bus_type, they will share the same object.
5452 * This is a synchronous failable function. See g_bus_get() and
5453 * g_bus_get_finish() for the asynchronous version.
5455 * The returned object is a singleton, that is, shared with other
5456 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5457 * event that you need a private message bus connection, use
5458 * g_dbus_address_get_for_bus_sync() and
5459 * g_dbus_connection_new_for_address().
5461 * Note that the returned #GDBusConnection object will (usually) have
5462 * the #GDBusConnection:exit-on-close property set to %TRUE.
5464 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5469 g_bus_get_sync (GBusType bus_type,
5470 GCancellable *cancellable,
5473 GDBusConnection *connection;
5475 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5477 connection = get_uninitialized_connection (bus_type, cancellable, error);
5478 if (connection == NULL)
5481 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5483 g_object_unref (connection);
5492 bus_get_async_initable_cb (GObject *source_object,
5496 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5500 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5504 g_assert (error != NULL);
5505 g_simple_async_result_set_from_error (simple, error);
5506 g_error_free (error);
5507 g_object_unref (source_object);
5511 g_simple_async_result_set_op_res_gpointer (simple,
5515 g_simple_async_result_complete_in_idle (simple);
5516 g_object_unref (simple);
5521 * @bus_type: A #GBusType.
5522 * @cancellable: A #GCancellable or %NULL.
5523 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5524 * @user_data: The data to pass to @callback.
5526 * Asynchronously connects to the message bus specified by @bus_type.
5528 * When the operation is finished, @callback will be invoked. You can
5529 * then call g_bus_get_finish() to get the result of the operation.
5531 * This is a asynchronous failable function. See g_bus_get_sync() for
5532 * the synchronous version.
5537 g_bus_get (GBusType bus_type,
5538 GCancellable *cancellable,
5539 GAsyncReadyCallback callback,
5542 GDBusConnection *connection;
5543 GSimpleAsyncResult *simple;
5546 simple = g_simple_async_result_new (NULL,
5552 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5553 if (connection == NULL)
5555 g_assert (error != NULL);
5556 g_simple_async_result_set_from_error (simple, error);
5557 g_error_free (error);
5558 g_simple_async_result_complete_in_idle (simple);
5559 g_object_unref (simple);
5563 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5566 bus_get_async_initable_cb,
5573 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5574 * @error: Return location for error or %NULL.
5576 * Finishes an operation started with g_bus_get().
5578 * The returned object is a singleton, that is, shared with other
5579 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5580 * event that you need a private message bus connection, use
5581 * g_dbus_address_get_for_bus() and
5582 * g_dbus_connection_new_for_address().
5584 * Note that the returned #GDBusConnection object will (usually) have
5585 * the #GDBusConnection:exit-on-close property set to %TRUE.
5587 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5592 g_bus_get_finish (GAsyncResult *res,
5595 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5597 GDBusConnection *ret;
5599 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5601 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5605 if (g_simple_async_result_propagate_error (simple, error))
5608 object = g_simple_async_result_get_op_res_gpointer (simple);
5609 g_assert (object != NULL);
5610 ret = g_object_ref (G_DBUS_CONNECTION (object));
5616 /* ---------------------------------------------------------------------------------------------------- */
5618 #define __G_DBUS_CONNECTION_C__
5619 #include "gioaliasdef.c"