1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - The GDBusProxy::g-properties-changed signal currently looks like this
33 * void user_function (GDBusProxy *proxy,
34 * GHashTable *changed_properties,
35 * gpointer user_data);
37 * which is problematic because some people frown upon GHashTable
38 * usage in public API (in particular some of the JS people). Maybe we
39 * need to rework it, maybe it doesn't matter since GDBusProxy is
40 * a low-level API and, for C code, we expect code generators to
41 * spit out subclasses that automatically hook up to this signal
42 * and does g_object_notify() anyway? Hmm...
44 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
45 * to specify where the nonce is stored. This will allow people to use
46 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
47 * to easily acheive secure RPC via nonce-tcp.
49 * - need to expose an extension point for resolving D-Bus address and
50 * turning them into GIOStream objects. This will allow us to implement
51 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
53 * - see g_dbus_address_connect() in gdbusaddress.c
55 * - would be cute to use kernel-specific APIs to resolve fds for
56 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
58 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
60 * maybe we can show more information about what fd 21 really is.
61 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
62 * Initial experiments on Linux 2.6 suggests that the symlink looks
67 * e.g. not of much use.
75 #include "gdbusauth.h"
76 #include "gdbusutils.h"
77 #include "gdbusaddress.h"
78 #include "gdbusmessage.h"
79 #include "gdbusconnection.h"
80 #include "gdbuserror.h"
81 #include "gioenumtypes.h"
82 #include "gdbusintrospection.h"
83 #include "gdbusmethodinvocation.h"
84 #include "gdbusprivate.h"
85 #include "gdbusauthobserver.h"
86 #include "gio-marshal.h"
87 #include "ginitable.h"
88 #include "gasyncinitable.h"
89 #include "giostream.h"
90 #include "gasyncresult.h"
91 #include "gsimpleasyncresult.h"
94 #include <gio/gunixconnection.h>
95 #include <gio/gunixfdmessage.h>
97 #include <sys/types.h>
100 #include "glibintl.h"
101 #include "gioalias.h"
104 * SECTION:gdbusconnection
105 * @short_description: D-Bus Connections
106 * @include: gio/gio.h
108 * The #GDBusConnection type is used for D-Bus connections to remote
109 * peers such as a message buses. It is a low-level API that offers a
110 * lot of flexibility. For instance, it lets you establish a connection
111 * over any transport that can by represented as an #GIOStream.
113 * This class is rarely used directly in D-Bus clients. If you are writing
114 * an D-Bus client, it is often easier to use the g_bus_own_name(),
115 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
117 * <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>
119 * <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>
121 * <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>
124 /* ---------------------------------------------------------------------------------------------------- */
126 G_LOCK_DEFINE_STATIC (message_bus_lock);
128 static GDBusConnection *the_session_bus = NULL;
129 static GDBusConnection *the_system_bus = NULL;
131 /* ---------------------------------------------------------------------------------------------------- */
134 _g_strv_has_string (const gchar* const *haystack,
139 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
141 if (g_strcmp0 (haystack[n], needle) == 0)
147 /* ---------------------------------------------------------------------------------------------------- */
150 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
152 // TODO: for some reason this doesn't work on Windows
153 #define CONNECTION_ENSURE_LOCK(obj) do { \
154 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
156 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
157 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
162 #define CONNECTION_LOCK(obj) do { \
163 g_mutex_lock ((obj)->priv->lock); \
166 #define CONNECTION_UNLOCK(obj) do { \
167 g_mutex_unlock ((obj)->priv->lock); \
170 struct _GDBusConnectionPrivate
172 /* ------------------------------------------------------------------------ */
173 /* -- General object state ------------------------------------------------ */
174 /* ------------------------------------------------------------------------ */
176 /* object-wide lock */
179 /* A lock used in the init() method of the GInitable interface - see comments
180 * in initable_init() for why a separate lock is needed
184 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
185 * someone calls org.freedesktop.DBus.GetMachineId()
189 /* The underlying stream used for communication */
192 /* The object used for authentication (if any) */
195 /* Set to TRUE if the connection has been closed */
198 /* Last serial used */
201 /* The object used to send/receive message */
204 /* If connected to a message bus, this contains the unique name assigned to
205 * us by the bus (e.g. ":1.42")
207 gchar *bus_unique_name;
209 /* The GUID returned by the other side if we authenticed as a client or
210 * the GUID to use if authenticating as a server
214 /* set to TRUE exactly when initable_init() has finished running */
215 gboolean is_initialized;
217 /* If the connection could not be established during initable_init(), this GError will set */
218 GError *initialization_error;
220 /* The result of g_main_context_get_thread_default() when the object
221 * was created (the GObject _init() function) - this is used for delivery
222 * of the :closed GObject signal.
224 GMainContext *main_context_at_construction;
226 /* construct properties */
228 GDBusConnectionFlags flags;
230 /* Map used for managing method replies */
231 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
233 /* Maps used for managing signal subscription */
234 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
235 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
236 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
238 /* Maps used for managing exported objects and subtrees */
239 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
240 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
241 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
242 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
244 /* Structure used for message filters */
247 /* Whether to exit on close */
248 gboolean exit_on_close;
250 /* Capabilities negotiated during authentication */
251 GDBusCapabilityFlags capabilities;
253 GDBusAuthObserver *authentication_observer;
254 GCredentials *crendentials;
257 typedef struct ExportedObject ExportedObject;
258 static void exported_object_free (ExportedObject *eo);
260 typedef struct ExportedSubtree ExportedSubtree;
261 static void exported_subtree_free (ExportedSubtree *es);
279 PROP_CAPABILITY_FLAGS,
280 PROP_AUTHENTICATION_OBSERVER,
283 static void distribute_signals (GDBusConnection *connection,
284 GDBusMessage *message);
286 static void distribute_method_call (GDBusConnection *connection,
287 GDBusMessage *message);
289 static gboolean handle_generic_unlocked (GDBusConnection *connection,
290 GDBusMessage *message);
293 static void purge_all_signal_subscriptions (GDBusConnection *connection);
294 static void purge_all_filters (GDBusConnection *connection);
296 #define _G_ENSURE_LOCK(name) do { \
297 if (G_UNLIKELY (G_TRYLOCK(name))) \
299 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
300 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
304 static guint signals[LAST_SIGNAL] = { 0 };
306 static void initable_iface_init (GInitableIface *initable_iface);
307 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
309 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
310 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
311 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
315 g_dbus_connection_dispose (GObject *object)
317 GDBusConnection *connection = G_DBUS_CONNECTION (object);
319 G_LOCK (message_bus_lock);
320 //g_debug ("disposing %p", connection);
321 if (connection == the_session_bus)
323 the_session_bus = NULL;
325 else if (connection == the_system_bus)
327 the_system_bus = NULL;
329 if (connection->priv->worker != NULL)
331 _g_dbus_worker_stop (connection->priv->worker);
332 connection->priv->worker = NULL;
334 G_UNLOCK (message_bus_lock);
336 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
337 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
341 g_dbus_connection_finalize (GObject *object)
343 GDBusConnection *connection = G_DBUS_CONNECTION (object);
345 if (connection->priv->authentication_observer != NULL)
346 g_object_unref (connection->priv->authentication_observer);
348 if (connection->priv->auth != NULL)
349 g_object_unref (connection->priv->auth);
351 //g_debug ("finalizing %p", connection);
352 if (connection->priv->stream != NULL)
354 /* We don't really care if closing the stream succeeds or not */
355 g_io_stream_close_async (connection->priv->stream,
357 NULL, /* GCancellable */
358 NULL, /* GAsyncReadyCallback */
359 NULL); /* userdata */
360 g_object_unref (connection->priv->stream);
361 connection->priv->stream = NULL;
364 g_free (connection->priv->address);
366 g_free (connection->priv->guid);
367 g_free (connection->priv->bus_unique_name);
369 if (connection->priv->initialization_error != NULL)
370 g_error_free (connection->priv->initialization_error);
372 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
374 purge_all_signal_subscriptions (connection);
375 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
376 g_hash_table_unref (connection->priv->map_id_to_signal_data);
377 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
379 g_hash_table_unref (connection->priv->map_id_to_ei);
380 g_hash_table_unref (connection->priv->map_object_path_to_eo);
381 g_hash_table_unref (connection->priv->map_id_to_es);
382 g_hash_table_unref (connection->priv->map_object_path_to_es);
384 purge_all_filters (connection);
385 g_ptr_array_unref (connection->priv->filters);
387 if (connection->priv->main_context_at_construction != NULL)
388 g_main_context_unref (connection->priv->main_context_at_construction);
390 g_free (connection->priv->machine_id);
392 g_mutex_free (connection->priv->init_lock);
393 g_mutex_free (connection->priv->lock);
395 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
399 g_dbus_connection_get_property (GObject *object,
404 GDBusConnection *connection = G_DBUS_CONNECTION (object);
409 g_value_set_object (value, g_dbus_connection_get_stream (connection));
413 g_value_set_string (value, g_dbus_connection_get_guid (connection));
416 case PROP_UNIQUE_NAME:
417 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
421 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
424 case PROP_EXIT_ON_CLOSE:
425 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
428 case PROP_CAPABILITY_FLAGS:
429 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
433 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
439 g_dbus_connection_set_property (GObject *object,
444 GDBusConnection *connection = G_DBUS_CONNECTION (object);
449 connection->priv->stream = g_value_dup_object (value);
453 connection->priv->guid = g_value_dup_string (value);
457 connection->priv->address = g_value_dup_string (value);
461 connection->priv->flags = g_value_get_flags (value);
464 case PROP_EXIT_ON_CLOSE:
465 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
468 case PROP_AUTHENTICATION_OBSERVER:
469 connection->priv->authentication_observer = g_value_dup_object (value);
473 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
479 g_dbus_connection_real_closed (GDBusConnection *connection,
480 gboolean remote_peer_vanished,
483 if (remote_peer_vanished && connection->priv->exit_on_close)
485 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
491 g_dbus_connection_class_init (GDBusConnectionClass *klass)
493 GObjectClass *gobject_class;
495 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
497 gobject_class = G_OBJECT_CLASS (klass);
499 gobject_class->finalize = g_dbus_connection_finalize;
500 gobject_class->dispose = g_dbus_connection_dispose;
501 gobject_class->set_property = g_dbus_connection_set_property;
502 gobject_class->get_property = g_dbus_connection_get_property;
504 klass->closed = g_dbus_connection_real_closed;
507 * GDBusConnection:stream:
509 * The underlying #GIOStream used for I/O.
513 g_object_class_install_property (gobject_class,
515 g_param_spec_object ("stream",
517 P_("The underlying streams used for I/O"),
521 G_PARAM_CONSTRUCT_ONLY |
522 G_PARAM_STATIC_NAME |
523 G_PARAM_STATIC_BLURB |
524 G_PARAM_STATIC_NICK));
527 * GDBusConnection:address:
529 * A D-Bus address specifying potential endpoints that can be used
530 * when establishing the connection.
534 g_object_class_install_property (gobject_class,
536 g_param_spec_string ("address",
538 P_("D-Bus address specifying potential socket endpoints"),
541 G_PARAM_CONSTRUCT_ONLY |
542 G_PARAM_STATIC_NAME |
543 G_PARAM_STATIC_BLURB |
544 G_PARAM_STATIC_NICK));
547 * GDBusConnection:flags:
549 * Flags from the #GDBusConnectionFlags enumeration.
553 g_object_class_install_property (gobject_class,
555 g_param_spec_flags ("flags",
558 G_TYPE_DBUS_CONNECTION_FLAGS,
559 G_DBUS_CONNECTION_FLAGS_NONE,
561 G_PARAM_CONSTRUCT_ONLY |
562 G_PARAM_STATIC_NAME |
563 G_PARAM_STATIC_BLURB |
564 G_PARAM_STATIC_NICK));
567 * GDBusConnection:guid:
569 * The GUID of the peer performing the role of server when
572 * If you are constructing a #GDBusConnection and pass
573 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
574 * #GDBusConnection:flags property then you MUST also set this
575 * property to a valid guid.
577 * If you are constructing a #GDBusConnection and pass
578 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
579 * #GDBusConnection:flags property you will be able to read the GUID
580 * of the other peer here after the connection has been successfully
585 g_object_class_install_property (gobject_class,
587 g_param_spec_string ("guid",
589 P_("GUID of the server peer"),
593 G_PARAM_CONSTRUCT_ONLY |
594 G_PARAM_STATIC_NAME |
595 G_PARAM_STATIC_BLURB |
596 G_PARAM_STATIC_NICK));
599 * GDBusConnection:unique-name:
601 * The unique name as assigned by the message bus or %NULL if the
602 * connection is not open or not a message bus connection.
606 g_object_class_install_property (gobject_class,
608 g_param_spec_string ("unique-name",
610 P_("Unique name of bus connection"),
613 G_PARAM_STATIC_NAME |
614 G_PARAM_STATIC_BLURB |
615 G_PARAM_STATIC_NICK));
618 * GDBusConnection:closed:
620 * A boolean specifying whether the connection has been closed.
624 g_object_class_install_property (gobject_class,
626 g_param_spec_boolean ("closed",
628 P_("Whether the connection is closed"),
631 G_PARAM_STATIC_NAME |
632 G_PARAM_STATIC_BLURB |
633 G_PARAM_STATIC_NICK));
636 * GDBusConnection:exit-on-close:
638 * A boolean specifying whether the process will be terminated (by
639 * calling <literal>raise(SIGTERM)</literal>) if the connection
640 * is closed by the remote peer.
644 g_object_class_install_property (gobject_class,
646 g_param_spec_boolean ("exit-on-close",
648 P_("Whether the process is terminated when the connection is closed"),
652 G_PARAM_STATIC_NAME |
653 G_PARAM_STATIC_BLURB |
654 G_PARAM_STATIC_NICK));
657 * GDBusConnection:capabilities:
659 * Flags from the #GDBusCapabilityFlags enumeration
660 * representing connection features negotiated with the other peer.
664 g_object_class_install_property (gobject_class,
665 PROP_CAPABILITY_FLAGS,
666 g_param_spec_flags ("capabilities",
669 G_TYPE_DBUS_CAPABILITY_FLAGS,
670 G_DBUS_CAPABILITY_FLAGS_NONE,
672 G_PARAM_STATIC_NAME |
673 G_PARAM_STATIC_BLURB |
674 G_PARAM_STATIC_NICK));
677 * GDBusConnection:authentication-observer:
679 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
683 g_object_class_install_property (gobject_class,
684 PROP_AUTHENTICATION_OBSERVER,
685 g_param_spec_object ("authentication-observer",
686 P_("Authentication Observer"),
687 P_("Object used to assist in the authentication process"),
688 G_TYPE_DBUS_AUTH_OBSERVER,
690 G_PARAM_CONSTRUCT_ONLY |
691 G_PARAM_STATIC_NAME |
692 G_PARAM_STATIC_BLURB |
693 G_PARAM_STATIC_NICK));
696 * GDBusConnection::closed:
697 * @connection: The #GDBusConnection emitting the signal.
698 * @remote_peer_vanished: %TRUE if @connection is closed because the
699 * remote peer closed its end of the connection.
700 * @error: A #GError with more details about the event or %NULL.
702 * Emitted when the connection is closed.
704 * The cause of this event can be
707 * If g_dbus_connection_close() is called. In this case
708 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
711 * If the remote peer closes the connection. In this case
712 * @remote_peer_vanished is set to %TRUE and @error is set.
715 * If the remote peer sends invalid or malformed data. In this
716 * case @remote_peer_vanished is set to %FALSE and @error
721 * Upon receiving this signal, you should give up your reference to
722 * @connection. You are guaranteed that this signal is emitted only
727 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
728 G_TYPE_DBUS_CONNECTION,
730 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
733 _gio_marshal_VOID__BOOLEAN_BOXED,
741 g_dbus_connection_init (GDBusConnection *connection)
743 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
745 connection->priv->lock = g_mutex_new ();
746 connection->priv->init_lock = g_mutex_new ();
748 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
750 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
752 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
754 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
759 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
762 (GDestroyNotify) exported_object_free);
764 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
767 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
770 (GDestroyNotify) exported_subtree_free);
772 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
775 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
776 if (connection->priv->main_context_at_construction != NULL)
777 g_main_context_ref (connection->priv->main_context_at_construction);
779 connection->priv->filters = g_ptr_array_new ();
783 * g_dbus_connection_get_stream:
784 * @connection: a #GDBusConnection
786 * Gets the underlying stream used for IO.
788 * Returns: the stream used for IO
793 g_dbus_connection_get_stream (GDBusConnection *connection)
795 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
796 return connection->priv->stream;
801 * g_dbus_connection_is_closed:
802 * @connection: A #GDBusConnection.
804 * Gets whether @connection is closed.
806 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
811 g_dbus_connection_is_closed (GDBusConnection *connection)
813 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
814 return connection->priv->closed;
818 * g_dbus_connection_get_capabilities:
819 * @connection: A #GDBusConnection.
821 * Gets the capabilities negotiated with the remote peer
823 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
828 g_dbus_connection_get_capabilities (GDBusConnection *connection)
830 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
831 return connection->priv->capabilities;
835 /* ---------------------------------------------------------------------------------------------------- */
839 GDBusConnection *connection;
841 gboolean remote_peer_vanished;
845 emit_closed_data_free (EmitClosedData *data)
847 g_object_unref (data->connection);
848 if (data->error != NULL)
849 g_error_free (data->error);
854 emit_closed_in_idle (gpointer user_data)
856 EmitClosedData *data = user_data;
859 g_object_notify (G_OBJECT (data->connection), "closed");
860 g_signal_emit (data->connection,
861 signals[CLOSED_SIGNAL],
863 data->remote_peer_vanished,
869 /* Can be called from any thread, must hold lock */
871 set_closed_unlocked (GDBusConnection *connection,
872 gboolean remote_peer_vanished,
875 GSource *idle_source;
876 EmitClosedData *data;
878 CONNECTION_ENSURE_LOCK (connection);
880 g_assert (!connection->priv->closed);
882 connection->priv->closed = TRUE;
884 data = g_new0 (EmitClosedData, 1);
885 data->connection = g_object_ref (connection);
886 data->remote_peer_vanished = remote_peer_vanished;
887 data->error = error != NULL ? g_error_copy (error) : NULL;
889 idle_source = g_idle_source_new ();
890 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
891 g_source_set_callback (idle_source,
894 (GDestroyNotify) emit_closed_data_free);
895 g_source_attach (idle_source, connection->priv->main_context_at_construction);
896 g_source_unref (idle_source);
899 /* ---------------------------------------------------------------------------------------------------- */
902 * g_dbus_connection_close:
903 * @connection: A #GDBusConnection.
905 * Closes @connection. Note that this never causes the process to
906 * exit (this might only happen if the other end of a shared message
907 * bus connection disconnects).
909 * If @connection is already closed, this method does nothing.
914 g_dbus_connection_close (GDBusConnection *connection)
916 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
918 CONNECTION_LOCK (connection);
919 if (!connection->priv->closed)
921 GError *error = NULL;
923 /* TODO: do this async */
924 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
925 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
927 g_warning ("Error closing stream: %s", error->message);
928 g_error_free (error);
931 set_closed_unlocked (connection, FALSE, NULL);
933 CONNECTION_UNLOCK (connection);
936 /* ---------------------------------------------------------------------------------------------------- */
939 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
940 GDBusMessage *message,
941 volatile guint32 *out_serial,
946 guint32 serial_to_use;
949 CONNECTION_ENSURE_LOCK (connection);
951 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
952 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
954 /* TODO: check all necessary headers are present */
959 if (out_serial != NULL)
962 if (connection->priv->closed)
964 g_set_error_literal (error,
967 _("The connection is closed"));
971 blob = g_dbus_message_to_blob (message,
977 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
982 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
985 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
988 g_assert_not_reached ();
993 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
994 blob_size, serial_to_use, connection);
995 g_printerr ("----\n");
996 hexdump (blob, blob_size);
997 g_printerr ("----\n");
1000 /* TODO: use connection->priv->auth to encode the blob */
1002 if (out_serial != NULL)
1003 *out_serial = serial_to_use;
1005 g_dbus_message_set_serial (message, serial_to_use);
1007 _g_dbus_worker_send_message (connection->priv->worker,
1011 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1022 * g_dbus_connection_send_message:
1023 * @connection: A #GDBusConnection.
1024 * @message: A #GDBusMessage
1025 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1026 * @error: Return location for error or %NULL.
1028 * Asynchronously sends @message to the peer represented by @connection.
1030 * If @out_serial is not %NULL, then the serial number assigned to
1031 * @message by @connection will be written to this location prior to
1032 * submitting the message to the underlying transport.
1034 * If @connection is closed then the operation will fail with
1035 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1036 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1037 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1039 * See <xref linkend="gdbus-server"/> and <xref
1040 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1041 * low-level API to send and receive UNIX file descriptors.
1043 * Returns: %TRUE if the message was well-formed and queued for
1044 * transmission, %FALSE if @error is set.
1049 g_dbus_connection_send_message (GDBusConnection *connection,
1050 GDBusMessage *message,
1051 volatile guint32 *out_serial,
1056 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1057 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1058 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1060 CONNECTION_LOCK (connection);
1061 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1062 CONNECTION_UNLOCK (connection);
1066 /* ---------------------------------------------------------------------------------------------------- */
1070 volatile gint ref_count;
1071 GDBusConnection *connection;
1073 GSimpleAsyncResult *simple;
1075 GMainContext *main_context;
1077 GCancellable *cancellable;
1079 gulong cancellable_handler_id;
1081 GSource *timeout_source;
1086 static SendMessageData *
1087 send_message_data_ref (SendMessageData *data)
1089 g_atomic_int_inc (&data->ref_count);
1094 send_message_data_unref (SendMessageData *data)
1096 if (g_atomic_int_dec_and_test (&data->ref_count))
1098 g_assert (data->timeout_source == NULL);
1099 g_assert (data->simple == NULL);
1100 g_assert (data->cancellable_handler_id == 0);
1101 g_object_unref (data->connection);
1102 if (data->cancellable != NULL)
1103 g_object_unref (data->cancellable);
1104 if (data->main_context != NULL)
1105 g_main_context_unref (data->main_context);
1110 /* ---------------------------------------------------------------------------------------------------- */
1112 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1114 send_message_with_reply_deliver (SendMessageData *data)
1116 CONNECTION_ENSURE_LOCK (data->connection);
1118 g_assert (!data->delivered);
1120 data->delivered = TRUE;
1122 g_simple_async_result_complete_in_idle (data->simple);
1123 g_object_unref (data->simple);
1124 data->simple = NULL;
1126 if (data->timeout_source != NULL)
1128 g_source_destroy (data->timeout_source);
1129 data->timeout_source = NULL;
1131 if (data->cancellable_handler_id > 0)
1133 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1134 data->cancellable_handler_id = 0;
1137 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1138 GUINT_TO_POINTER (data->serial)));
1140 send_message_data_unref (data);
1143 /* ---------------------------------------------------------------------------------------------------- */
1145 /* must hold lock */
1147 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1148 GDBusMessage *reply)
1150 if (data->delivered)
1153 g_simple_async_result_set_op_res_gpointer (data->simple,
1154 g_object_ref (reply),
1157 send_message_with_reply_deliver (data);
1163 /* ---------------------------------------------------------------------------------------------------- */
1166 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1168 SendMessageData *data = user_data;
1170 CONNECTION_LOCK (data->connection);
1171 if (data->delivered)
1174 g_simple_async_result_set_error (data->simple,
1176 G_IO_ERROR_CANCELLED,
1177 _("Operation was cancelled"));
1179 send_message_with_reply_deliver (data);
1182 CONNECTION_UNLOCK (data->connection);
1186 /* Can be called from any thread with or without lock held */
1188 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1191 SendMessageData *data = user_data;
1192 GSource *idle_source;
1194 /* postpone cancellation to idle handler since we may be called directly
1195 * via g_cancellable_connect() (e.g. holding lock)
1197 idle_source = g_idle_source_new ();
1198 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1199 g_source_set_callback (idle_source,
1200 send_message_with_reply_cancelled_idle_cb,
1201 send_message_data_ref (data),
1202 (GDestroyNotify) send_message_data_unref);
1203 g_source_attach (idle_source, data->main_context);
1204 g_source_unref (idle_source);
1207 /* ---------------------------------------------------------------------------------------------------- */
1210 send_message_with_reply_timeout_cb (gpointer user_data)
1212 SendMessageData *data = user_data;
1214 CONNECTION_LOCK (data->connection);
1215 if (data->delivered)
1218 g_simple_async_result_set_error (data->simple,
1220 G_IO_ERROR_TIMED_OUT,
1221 _("Timeout was reached"));
1223 send_message_with_reply_deliver (data);
1226 CONNECTION_UNLOCK (data->connection);
1231 /* ---------------------------------------------------------------------------------------------------- */
1234 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1235 GDBusMessage *message,
1237 volatile guint32 *out_serial,
1238 GCancellable *cancellable,
1239 GAsyncReadyCallback callback,
1242 GSimpleAsyncResult *simple;
1243 SendMessageData *data;
1245 volatile guint32 serial;
1249 if (out_serial == NULL)
1250 out_serial = &serial;
1252 if (timeout_msec == -1)
1253 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1255 simple = g_simple_async_result_new (G_OBJECT (connection),
1258 g_dbus_connection_send_message_with_reply);
1260 if (g_cancellable_is_cancelled (cancellable))
1262 g_simple_async_result_set_error (simple,
1264 G_IO_ERROR_CANCELLED,
1265 _("Operation was cancelled"));
1266 g_simple_async_result_complete_in_idle (simple);
1267 g_object_unref (simple);
1271 if (connection->priv->closed)
1273 g_simple_async_result_set_error (simple,
1276 _("The connection is closed"));
1277 g_simple_async_result_complete_in_idle (simple);
1278 g_object_unref (simple);
1283 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1285 g_simple_async_result_set_from_error (simple, error);
1286 g_simple_async_result_complete_in_idle (simple);
1287 g_object_unref (simple);
1291 data = g_new0 (SendMessageData, 1);
1292 data->ref_count = 1;
1293 data->connection = g_object_ref (connection);
1294 data->simple = simple;
1295 data->serial = *out_serial;
1296 data->main_context = g_main_context_get_thread_default ();
1297 if (data->main_context != NULL)
1298 g_main_context_ref (data->main_context);
1300 if (cancellable != NULL)
1302 data->cancellable = g_object_ref (cancellable);
1303 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1304 G_CALLBACK (send_message_with_reply_cancelled_cb),
1305 send_message_data_ref (data),
1306 (GDestroyNotify) send_message_data_unref);
1307 g_object_set_data_full (G_OBJECT (simple),
1309 g_object_ref (cancellable),
1310 (GDestroyNotify) g_object_unref);
1313 data->timeout_source = g_timeout_source_new (timeout_msec);
1314 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1315 g_source_set_callback (data->timeout_source,
1316 send_message_with_reply_timeout_cb,
1317 send_message_data_ref (data),
1318 (GDestroyNotify) send_message_data_unref);
1319 g_source_attach (data->timeout_source, data->main_context);
1320 g_source_unref (data->timeout_source);
1322 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1323 GUINT_TO_POINTER (*out_serial),
1331 * g_dbus_connection_send_message_with_reply:
1332 * @connection: A #GDBusConnection.
1333 * @message: A #GDBusMessage.
1334 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1335 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1336 * @cancellable: A #GCancellable or %NULL.
1337 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1338 * care about the result.
1339 * @user_data: The data to pass to @callback.
1341 * Asynchronously sends @message to the peer represented by @connection.
1343 * If @out_serial is not %NULL, then the serial number assigned to
1344 * @message by @connection will be written to this location prior to
1345 * submitting the message to the underlying transport.
1347 * If @connection is closed then the operation will fail with
1348 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1349 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1350 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1352 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1353 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1354 * of the thread you are calling this method from. You can then call
1355 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1356 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1358 * See <xref linkend="gdbus-server"/> and <xref
1359 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1360 * low-level API to send and receive UNIX file descriptors.
1365 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1366 GDBusMessage *message,
1368 volatile guint32 *out_serial,
1369 GCancellable *cancellable,
1370 GAsyncReadyCallback callback,
1373 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1374 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1375 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1377 CONNECTION_LOCK (connection);
1378 g_dbus_connection_send_message_with_reply_unlocked (connection,
1385 CONNECTION_UNLOCK (connection);
1389 * g_dbus_connection_send_message_with_reply_finish:
1390 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1391 * @error: Return location for error or %NULL.
1393 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1395 * Note that @error is only set if a local in-process error
1396 * occured. That is to say that the returned #GDBusMessage object may
1397 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1398 * g_dbus_message_to_gerror() to transcode this to a #GError.
1400 * See <xref linkend="gdbus-server"/> and <xref
1401 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1402 * low-level API to send and receive UNIX file descriptors.
1404 * Returns: A #GDBusMessage or %NULL if @error is set.
1409 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1413 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1414 GDBusMessage *reply;
1415 GCancellable *cancellable;
1417 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1418 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1422 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1424 if (g_simple_async_result_propagate_error (simple, error))
1427 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1428 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1429 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1431 g_object_unref (reply);
1433 g_set_error_literal (error,
1435 G_IO_ERROR_CANCELLED,
1436 _("Operation was cancelled"));
1442 /* ---------------------------------------------------------------------------------------------------- */
1447 GMainContext *context;
1449 } SendMessageSyncData;
1452 send_message_with_reply_sync_cb (GDBusConnection *connection,
1456 SendMessageSyncData *data = user_data;
1457 data->res = g_object_ref (res);
1458 g_main_loop_quit (data->loop);
1462 * g_dbus_connection_send_message_with_reply_sync:
1463 * @connection: A #GDBusConnection.
1464 * @message: A #GDBusMessage.
1465 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1466 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1467 * @cancellable: A #GCancellable or %NULL.
1468 * @error: Return location for error or %NULL.
1470 * Synchronously sends @message to the peer represented by @connection
1471 * and blocks the calling thread until a reply is received or the
1472 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1473 * for the asynchronous version of this method.
1475 * If @out_serial is not %NULL, then the serial number assigned to
1476 * @message by @connection will be written to this location prior to
1477 * submitting the message to the underlying transport.
1479 * If @connection is closed then the operation will fail with
1480 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1481 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1482 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1484 * Note that @error is only set if a local in-process error
1485 * occured. That is to say that the returned #GDBusMessage object may
1486 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1487 * g_dbus_message_to_gerror() to transcode this to a #GError.
1489 * See <xref linkend="gdbus-server"/> and <xref
1490 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1491 * low-level API to send and receive UNIX file descriptors.
1493 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1498 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1499 GDBusMessage *message,
1501 volatile guint32 *out_serial,
1502 GCancellable *cancellable,
1505 SendMessageSyncData *data;
1506 GDBusMessage *reply;
1508 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1509 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1510 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1511 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1513 data = g_new0 (SendMessageSyncData, 1);
1514 data->context = g_main_context_new ();
1515 data->loop = g_main_loop_new (data->context, FALSE);
1517 g_main_context_push_thread_default (data->context);
1519 g_dbus_connection_send_message_with_reply (connection,
1524 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1526 g_main_loop_run (data->loop);
1527 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1531 g_main_context_pop_thread_default (data->context);
1533 g_main_context_unref (data->context);
1534 g_main_loop_unref (data->loop);
1535 g_object_unref (data->res);
1541 /* ---------------------------------------------------------------------------------------------------- */
1545 GDBusMessageFilterFunction func;
1552 GDBusMessageFilterFunction filter_function;
1554 GDestroyNotify user_data_free_func;
1557 /* Called in worker's thread - we must not block */
1559 on_worker_message_received (GDBusWorker *worker,
1560 GDBusMessage *message,
1563 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1564 FilterCallback *filters;
1565 gboolean consumed_by_filter;
1569 //g_debug ("in on_worker_message_received");
1571 g_object_ref (connection);
1573 /* First collect the set of callback functions */
1574 CONNECTION_LOCK (connection);
1575 num_filters = connection->priv->filters->len;
1576 filters = g_new0 (FilterCallback, num_filters);
1577 for (n = 0; n < num_filters; n++)
1579 FilterData *data = connection->priv->filters->pdata[n];
1580 filters[n].func = data->filter_function;
1581 filters[n].user_data = data->user_data;
1583 CONNECTION_UNLOCK (connection);
1585 /* the call the filters in order (without holding the lock) */
1586 consumed_by_filter = FALSE;
1587 for (n = 0; n < num_filters; n++)
1589 consumed_by_filter = filters[n].func (connection,
1591 filters[n].user_data);
1592 if (consumed_by_filter)
1596 /* Standard dispatch unless the filter ate the message */
1597 if (!consumed_by_filter)
1599 GDBusMessageType message_type;
1601 message_type = g_dbus_message_get_message_type (message);
1602 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1604 guint32 reply_serial;
1605 SendMessageData *send_message_data;
1607 reply_serial = g_dbus_message_get_reply_serial (message);
1608 CONNECTION_LOCK (connection);
1609 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1610 GUINT_TO_POINTER (reply_serial));
1611 if (send_message_data != NULL)
1613 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1614 send_message_data_deliver_reply_unlocked (send_message_data, message);
1618 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1620 CONNECTION_UNLOCK (connection);
1622 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1624 CONNECTION_LOCK (connection);
1625 distribute_signals (connection, message);
1626 CONNECTION_UNLOCK (connection);
1628 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1630 CONNECTION_LOCK (connection);
1631 distribute_method_call (connection, message);
1632 CONNECTION_UNLOCK (connection);
1636 g_object_unref (connection);
1640 /* Called in worker's thread - we must not block */
1642 on_worker_closed (GDBusWorker *worker,
1643 gboolean remote_peer_vanished,
1647 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1649 //g_debug ("in on_worker_closed: %s", error->message);
1651 CONNECTION_LOCK (connection);
1652 if (!connection->priv->closed)
1653 set_closed_unlocked (connection, remote_peer_vanished, error);
1654 CONNECTION_UNLOCK (connection);
1657 /* ---------------------------------------------------------------------------------------------------- */
1659 /* Determines the biggest set of capabilities we can support on this connection */
1660 static GDBusCapabilityFlags
1661 get_offered_capabilities_max (GDBusConnection *connection)
1663 GDBusCapabilityFlags ret;
1664 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1666 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1667 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1673 initable_init (GInitable *initable,
1674 GCancellable *cancellable,
1677 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1680 /* This method needs to be idempotent to work with the singleton
1681 * pattern. See the docs for g_initable_init(). We implement this by
1684 * Unfortunately we can't use the main lock since the on_worker_*()
1685 * callbacks above needs the lock during initialization (for message
1686 * bus connections we do a synchronous Hello() call on the bus).
1688 g_mutex_lock (connection->priv->init_lock);
1692 if (connection->priv->is_initialized)
1694 if (connection->priv->stream != NULL)
1697 g_assert (connection->priv->initialization_error != NULL);
1700 g_assert (connection->priv->initialization_error == NULL);
1702 /* The user can pass multiple (but mutally exclusive) construct
1705 * - stream (of type GIOStream)
1706 * - address (of type gchar*)
1708 * At the end of the day we end up with a non-NULL GIOStream
1709 * object in connection->priv->stream.
1711 if (connection->priv->address != NULL)
1713 g_assert (connection->priv->stream == NULL);
1715 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1716 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1718 g_set_error_literal (error,
1720 G_IO_ERROR_INVALID_ARGUMENT,
1721 _("Unsupported flags encountered when constructing a client-side connection"));
1725 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1726 NULL, /* TODO: out_guid */
1728 &connection->priv->initialization_error);
1729 if (connection->priv->stream == NULL)
1732 else if (connection->priv->stream != NULL)
1738 g_assert_not_reached ();
1741 /* Authenticate the connection */
1742 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1744 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1745 g_assert (connection->priv->guid != NULL);
1746 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1747 if (!_g_dbus_auth_run_server (connection->priv->auth,
1748 connection->priv->authentication_observer,
1749 connection->priv->guid,
1750 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1751 get_offered_capabilities_max (connection),
1752 &connection->priv->capabilities,
1753 &connection->priv->crendentials,
1755 &connection->priv->initialization_error))
1758 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1760 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1761 g_assert (connection->priv->guid == NULL);
1762 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1763 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1764 get_offered_capabilities_max (connection),
1765 &connection->priv->capabilities,
1767 &connection->priv->initialization_error);
1768 if (connection->priv->guid == NULL)
1772 if (connection->priv->authentication_observer != NULL)
1774 g_object_unref (connection->priv->authentication_observer);
1775 connection->priv->authentication_observer = NULL;
1778 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1780 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1784 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1788 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1790 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1793 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1794 connection->priv->capabilities,
1795 on_worker_message_received,
1799 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1800 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1802 GVariant *hello_result;
1805 hello_result = g_dbus_connection_invoke_method_sync (connection,
1806 "org.freedesktop.DBus", /* name */
1807 "/org/freedesktop/DBus", /* path */
1808 "org.freedesktop.DBus", /* interface */
1810 NULL, /* parameters */
1811 G_DBUS_INVOKE_METHOD_FLAGS_NONE,
1813 NULL, /* TODO: cancellable */
1814 &connection->priv->initialization_error);
1815 if (hello_result == NULL)
1818 g_variant_get (hello_result, "(s)", &s);
1819 connection->priv->bus_unique_name = g_strdup (s);
1820 g_variant_unref (hello_result);
1821 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1824 connection->priv->is_initialized = TRUE;
1830 g_assert (connection->priv->initialization_error != NULL);
1831 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1834 g_mutex_unlock (connection->priv->init_lock);
1840 initable_iface_init (GInitableIface *initable_iface)
1842 initable_iface->init = initable_init;
1845 /* ---------------------------------------------------------------------------------------------------- */
1848 async_init_thread (GSimpleAsyncResult *res,
1850 GCancellable *cancellable)
1852 GError *error = NULL;
1854 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1856 g_simple_async_result_set_from_error (res, error);
1857 g_error_free (error);
1862 async_initable_init_async (GAsyncInitable *initable,
1864 GCancellable *cancellable,
1865 GAsyncReadyCallback callback,
1868 GSimpleAsyncResult *res;
1870 g_return_if_fail (G_IS_INITABLE (initable));
1872 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1873 async_initable_init_async);
1874 g_simple_async_result_run_in_thread (res, async_init_thread,
1875 io_priority, cancellable);
1876 g_object_unref (res);
1880 async_initable_init_finish (GAsyncInitable *initable,
1884 return TRUE; /* Errors handled by base impl */
1888 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1890 /* We basically just want to use GIO's default implementation - though that one is
1891 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1893 async_initable_iface->init_async = async_initable_init_async;
1894 async_initable_iface->init_finish = async_initable_init_finish;
1897 /* ---------------------------------------------------------------------------------------------------- */
1900 * g_dbus_connection_new:
1901 * @stream: A #GIOStream.
1902 * @guid: The GUID to use if a authenticating as a server or %NULL.
1903 * @flags: Flags describing how to make the connection.
1904 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1905 * @cancellable: A #GCancellable or %NULL.
1906 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1907 * @user_data: The data to pass to @callback.
1909 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1910 * with the end represented by @stream.
1912 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1913 * @auth_observer (if not %NULL) is used to assist in the client
1914 * authentication process.
1916 * When the operation is finished, @callback will be invoked. You can
1917 * then call g_dbus_connection_new_finish() to get the result of the
1920 * This is a asynchronous failable constructor. See
1921 * g_dbus_connection_new_sync() for the synchronous
1927 g_dbus_connection_new (GIOStream *stream,
1929 GDBusConnectionFlags flags,
1930 GDBusAuthObserver *authentication_observer,
1931 GCancellable *cancellable,
1932 GAsyncReadyCallback callback,
1935 g_return_if_fail (G_IS_IO_STREAM (stream));
1936 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1944 "authentication-observer", authentication_observer,
1949 * g_dbus_connection_new_finish:
1950 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1951 * @error: Return location for error or %NULL.
1953 * Finishes an operation started with g_dbus_connection_new().
1955 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1960 g_dbus_connection_new_finish (GAsyncResult *res,
1964 GObject *source_object;
1966 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1967 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1969 source_object = g_async_result_get_source_object (res);
1970 g_assert (source_object != NULL);
1971 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1974 g_object_unref (source_object);
1976 return G_DBUS_CONNECTION (object);
1982 * g_dbus_connection_new_sync:
1983 * @stream: A #GIOStream.
1984 * @guid: The GUID to use if a authenticating as a server or %NULL.
1985 * @flags: Flags describing how to make the connection.
1986 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1987 * @cancellable: A #GCancellable or %NULL.
1988 * @error: Return location for error or %NULL.
1990 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1991 * with the end represented by @stream.
1993 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1994 * @auth_observer (if not %NULL) is used to assist in the client
1995 * authentication process.
1997 * This is a synchronous failable constructor. See
1998 * g_dbus_connection_new() for the asynchronous version.
2000 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2005 g_dbus_connection_new_sync (GIOStream *stream,
2007 GDBusConnectionFlags flags,
2008 GDBusAuthObserver *authentication_observer,
2009 GCancellable *cancellable,
2012 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2013 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2014 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2020 "authentication-observer", authentication_observer,
2024 /* ---------------------------------------------------------------------------------------------------- */
2027 * g_dbus_connection_new_for_address:
2028 * @address: A D-Bus address.
2029 * @flags: Flags describing how to make the connection.
2030 * @cancellable: A #GCancellable or %NULL.
2031 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2032 * @user_data: The data to pass to @callback.
2034 * Asynchronously connects and sets up a D-Bus client connection for
2035 * exchanging D-Bus messages with an endpoint specified by @address
2036 * which must be in the D-Bus address format.
2038 * This constructor can only be used to initiate client-side
2039 * connections - use g_dbus_connection_new() if you need to act as the
2040 * server. In particular, @flags cannot contain the
2041 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2042 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2044 * When the operation is finished, @callback will be invoked. You can
2045 * then call g_dbus_connection_new_finish() to get the result of the
2048 * This is a asynchronous failable constructor. See
2049 * g_dbus_connection_new_for_address_sync() for the synchronous
2055 g_dbus_connection_new_for_address (const gchar *address,
2056 GDBusConnectionFlags flags,
2057 GCancellable *cancellable,
2058 GAsyncReadyCallback callback,
2061 g_return_if_fail (address != NULL);
2062 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2073 * g_dbus_connection_new_for_address_finish:
2074 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2075 * @error: Return location for error or %NULL.
2077 * Finishes an operation started with g_dbus_connection_new_for_address().
2079 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2084 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2088 GObject *source_object;
2090 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2091 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2093 source_object = g_async_result_get_source_object (res);
2094 g_assert (source_object != NULL);
2095 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2098 g_object_unref (source_object);
2100 return G_DBUS_CONNECTION (object);
2106 * g_dbus_connection_new_for_address_sync:
2107 * @address: A D-Bus address.
2108 * @flags: Flags describing how to make the connection.
2109 * @cancellable: A #GCancellable or %NULL.
2110 * @error: Return location for error or %NULL.
2112 * Synchronously connects and sets up a D-Bus client connection for
2113 * exchanging D-Bus messages with an endpoint specified by @address
2114 * which must be in the D-Bus address format.
2116 * This constructor can only be used to initiate client-side
2117 * connections - use g_dbus_connection_new_sync() if you need to act
2118 * as the server. In particular, @flags cannot contain the
2119 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2120 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2122 * This is a synchronous failable constructor. See
2123 * g_dbus_connection_new_for_address() for the asynchronous version.
2125 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2130 g_dbus_connection_new_for_address_sync (const gchar *address,
2131 GDBusConnectionFlags flags,
2132 GCancellable *cancellable,
2135 g_return_val_if_fail (address != NULL, NULL);
2136 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2137 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2145 /* ---------------------------------------------------------------------------------------------------- */
2148 * g_dbus_connection_set_exit_on_close:
2149 * @connection: A #GDBusConnection.
2150 * @exit_on_close: Whether the process should be terminated
2151 * when @connection is closed by the remote peer.
2153 * Sets whether the process should be terminated when @connection is
2154 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2160 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2161 gboolean exit_on_close)
2163 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2164 connection->priv->exit_on_close = exit_on_close;
2168 * g_dbus_connection_get_exit_on_close:
2169 * @connection: A #GDBusConnection.
2171 * Gets whether the process is terminated when @connection is
2172 * closed by the remote peer. See
2173 * #GDBusConnection:exit-on-close for more details.
2175 * Returns: Whether the process is terminated when @connection is
2176 * closed by the remote peer.
2181 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2183 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2184 return connection->priv->exit_on_close;
2188 * g_dbus_connection_get_guid:
2189 * @connection: A #GDBusConnection.
2191 * The GUID of the peer performing the role of server when
2192 * authenticating. See #GDBusConnection:guid for more details.
2194 * Returns: The GUID. Do not free this string, it is owned by
2200 g_dbus_connection_get_guid (GDBusConnection *connection)
2202 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2203 return connection->priv->guid;
2207 * g_dbus_connection_get_unique_name:
2208 * @connection: A #GDBusConnection.
2210 * Gets the unique name of @connection as assigned by the message
2211 * bus. This can also be used to figure out if @connection is a
2212 * message bus connection.
2214 * Returns: The unique name or %NULL if @connection is not a message
2215 * bus connection. Do not free this string, it is owned by
2221 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2223 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2224 return connection->priv->bus_unique_name;
2228 * g_dbus_connection_get_peer_credentials:
2229 * @connection: A #GDBusConnection.
2231 * Gets the credentials of the authenticated peer. This will always
2232 * return %NULL unless @connection acted as a server
2233 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2234 * when set up and the client passed credentials as part of the
2235 * authentication process.
2237 * In a message bus setup, the message bus is always the server and
2238 * each application is a client. So this method will always return
2239 * %NULL for message bus clients.
2241 * Returns: A #GCredentials or %NULL if not available. Do not free
2242 * this object, it is owned by @connection.
2247 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2249 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2250 return connection->priv->crendentials;
2253 /* ---------------------------------------------------------------------------------------------------- */
2255 static guint _global_filter_id = 1;
2258 * g_dbus_connection_add_filter:
2259 * @connection: A #GDBusConnection.
2260 * @filter_function: A filter function.
2261 * @user_data: User data to pass to @filter_function.
2262 * @user_data_free_func: Function to free @user_data with when filter
2263 * is removed or %NULL.
2265 * Adds a message filter. Filters are handlers that are run on all
2266 * incoming messages, prior to standard dispatch. Filters are run in
2267 * the order that they were added. The same handler can be added as a
2268 * filter more than once, in which case it will be run more than once.
2269 * Filters added during a filter callback won't be run on the message
2272 * Note that filters are run in a dedicated message handling thread so
2273 * they can't block and, generally, can't do anything but signal a
2274 * worker thread. Also note that filters are rarely needed - use API
2275 * such as g_dbus_connection_send_message_with_reply(),
2276 * g_dbus_connection_signal_subscribe() or
2277 * g_dbus_connection_invoke_method() instead.
2279 * Returns: A filter identifier that can be used with
2280 * g_dbus_connection_remove_filter().
2285 g_dbus_connection_add_filter (GDBusConnection *connection,
2286 GDBusMessageFilterFunction filter_function,
2288 GDestroyNotify user_data_free_func)
2292 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2293 g_return_val_if_fail (filter_function != NULL, 0);
2295 CONNECTION_LOCK (connection);
2296 data = g_new0 (FilterData, 1);
2297 data->id = _global_filter_id++; /* TODO: overflow etc. */
2298 data->filter_function = filter_function;
2299 data->user_data = user_data;
2300 data->user_data_free_func = user_data_free_func;
2301 g_ptr_array_add (connection->priv->filters, data);
2302 CONNECTION_UNLOCK (connection);
2307 /* only called from finalize(), removes all filters */
2309 purge_all_filters (GDBusConnection *connection)
2312 for (n = 0; n < connection->priv->filters->len; n++)
2314 FilterData *data = connection->priv->filters->pdata[n];
2315 if (data->user_data_free_func != NULL)
2316 data->user_data_free_func (data->user_data);
2322 g_dbus_connection_remove_filter (GDBusConnection *connection,
2326 FilterData *to_destroy;
2328 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2330 CONNECTION_LOCK (connection);
2332 for (n = 0; n < connection->priv->filters->len; n++)
2334 FilterData *data = connection->priv->filters->pdata[n];
2335 if (data->id == filter_id)
2337 g_ptr_array_remove_index (connection->priv->filters, n);
2342 CONNECTION_UNLOCK (connection);
2344 /* do free without holding lock */
2345 if (to_destroy != NULL)
2347 if (to_destroy->user_data_free_func != NULL)
2348 to_destroy->user_data_free_func (to_destroy->user_data);
2349 g_free (to_destroy);
2353 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2357 /* ---------------------------------------------------------------------------------------------------- */
2363 gchar *interface_name;
2367 GArray *subscribers;
2372 GDBusSignalCallback callback;
2374 GDestroyNotify user_data_free_func;
2376 GMainContext *context;
2380 signal_data_free (SignalData *data)
2382 g_free (data->rule);
2383 g_free (data->sender);
2384 g_free (data->interface_name);
2385 g_free (data->member);
2386 g_free (data->object_path);
2387 g_free (data->arg0);
2388 g_array_free (data->subscribers, TRUE);
2393 args_to_rule (const gchar *sender,
2394 const gchar *interface_name,
2395 const gchar *member,
2396 const gchar *object_path,
2401 rule = g_string_new ("type='signal'");
2403 g_string_append_printf (rule, ",sender='%s'", sender);
2404 if (interface_name != NULL)
2405 g_string_append_printf (rule, ",interface='%s'", interface_name);
2407 g_string_append_printf (rule, ",member='%s'", member);
2408 if (object_path != NULL)
2409 g_string_append_printf (rule, ",path='%s'", object_path);
2411 g_string_append_printf (rule, ",arg0='%s'", arg0);
2413 return g_string_free (rule, FALSE);
2416 static guint _global_subscriber_id = 1;
2417 static guint _global_registration_id = 1;
2418 static guint _global_subtree_registration_id = 1;
2420 /* ---------------------------------------------------------------------------------------------------- */
2422 /* must hold lock when calling */
2424 add_match_rule (GDBusConnection *connection,
2425 const gchar *match_rule)
2428 GDBusMessage *message;
2430 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2431 "/org/freedesktop/DBus", /* path */
2432 "org.freedesktop.DBus", /* interface */
2434 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2437 if (!g_dbus_connection_send_message_unlocked (connection,
2442 g_critical ("Error while sending AddMatch() message: %s", error->message);
2443 g_error_free (error);
2445 g_object_unref (message);
2448 /* ---------------------------------------------------------------------------------------------------- */
2450 /* must hold lock when calling */
2452 remove_match_rule (GDBusConnection *connection,
2453 const gchar *match_rule)
2456 GDBusMessage *message;
2458 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2459 "/org/freedesktop/DBus", /* path */
2460 "org.freedesktop.DBus", /* interface */
2462 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2465 if (!g_dbus_connection_send_message_unlocked (connection,
2470 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2471 g_error_free (error);
2473 g_object_unref (message);
2476 /* ---------------------------------------------------------------------------------------------------- */
2479 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2481 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2482 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2483 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2484 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2485 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2488 /* ---------------------------------------------------------------------------------------------------- */
2491 * g_dbus_connection_signal_subscribe:
2492 * @connection: A #GDBusConnection.
2493 * @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.
2494 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2495 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2496 * @object_path: Object path to match on or %NULL to match on all object paths.
2497 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2498 * @callback: Callback to invoke when there is a signal matching the requested data.
2499 * @user_data: User data to pass to @callback.
2500 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2502 * Subscribes to signals on @connection and invokes @callback with a
2503 * whenever the signal is received. Note that @callback
2504 * will be invoked in the <link
2505 * linkend="g-main-context-push-thread-default">thread-default main
2506 * loop</link> of the thread you are calling this method from.
2508 * It is considered a programming error to use this function if @connection is closed.
2510 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2511 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2512 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2513 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2514 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2515 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2517 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2522 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2523 const gchar *sender,
2524 const gchar *interface_name,
2525 const gchar *member,
2526 const gchar *object_path,
2528 GDBusSignalCallback callback,
2530 GDestroyNotify user_data_free_func)
2533 SignalData *signal_data;
2534 SignalSubscriber subscriber;
2535 GPtrArray *signal_data_array;
2537 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2538 * an OOM condition. We might want to change that but that would involve making
2539 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2540 * handle that. And there's really no sensible way of handling this short of retrying
2541 * to add the match rule... and then there's the little thing that, hey, maybe there's
2542 * a reason the bus in an OOM condition.
2544 * Doable, but not really sure it's worth it...
2547 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2548 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2549 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2550 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2551 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2552 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2553 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2554 g_return_val_if_fail (callback != NULL, 0);
2556 CONNECTION_LOCK (connection);
2558 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2563 subscriber.callback = callback;
2564 subscriber.user_data = user_data;
2565 subscriber.user_data_free_func = user_data_free_func;
2566 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2567 subscriber.context = g_main_context_get_thread_default ();
2568 if (subscriber.context != NULL)
2569 g_main_context_ref (subscriber.context);
2571 /* see if we've already have this rule */
2572 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2573 if (signal_data != NULL)
2575 g_array_append_val (signal_data->subscribers, subscriber);
2580 signal_data = g_new0 (SignalData, 1);
2581 signal_data->rule = rule;
2582 signal_data->sender = g_strdup (sender);
2583 signal_data->interface_name = g_strdup (interface_name);
2584 signal_data->member = g_strdup (member);
2585 signal_data->object_path = g_strdup (object_path);
2586 signal_data->arg0 = g_strdup (arg0);
2587 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2588 g_array_append_val (signal_data->subscribers, subscriber);
2590 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2594 /* Add the match rule to the bus...
2596 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2597 * always send such messages to us.
2599 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2601 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2602 add_match_rule (connection, signal_data->rule);
2606 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2607 GUINT_TO_POINTER (subscriber.id),
2610 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2611 signal_data->sender);
2612 if (signal_data_array == NULL)
2614 signal_data_array = g_ptr_array_new ();
2615 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2616 g_strdup (signal_data->sender),
2619 g_ptr_array_add (signal_data_array, signal_data);
2621 CONNECTION_UNLOCK (connection);
2623 return subscriber.id;
2626 /* ---------------------------------------------------------------------------------------------------- */
2628 /* must hold lock when calling this */
2630 unsubscribe_id_internal (GDBusConnection *connection,
2631 guint subscription_id,
2632 GArray *out_removed_subscribers)
2634 SignalData *signal_data;
2635 GPtrArray *signal_data_array;
2638 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2639 GUINT_TO_POINTER (subscription_id));
2640 if (signal_data == NULL)
2642 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2646 for (n = 0; n < signal_data->subscribers->len; n++)
2648 SignalSubscriber *subscriber;
2650 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2651 if (subscriber->id != subscription_id)
2654 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2655 GUINT_TO_POINTER (subscription_id)));
2656 g_array_append_val (out_removed_subscribers, *subscriber);
2657 g_array_remove_index (signal_data->subscribers, n);
2659 if (signal_data->subscribers->len == 0)
2660 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2662 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2663 signal_data->sender);
2664 g_warn_if_fail (signal_data_array != NULL);
2665 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2667 if (signal_data_array->len == 0)
2669 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2671 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2672 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2674 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2675 remove_match_rule (connection, signal_data->rule);
2678 signal_data_free (signal_data);
2684 g_assert_not_reached ();
2691 * g_dbus_connection_signal_unsubscribe:
2692 * @connection: A #GDBusConnection.
2693 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2695 * Unsubscribes from signals.
2700 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2701 guint subscription_id)
2703 GArray *subscribers;
2706 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2708 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2710 CONNECTION_LOCK (connection);
2711 unsubscribe_id_internal (connection,
2714 CONNECTION_UNLOCK (connection);
2717 g_assert (subscribers->len == 0 || subscribers->len == 1);
2719 /* call GDestroyNotify without lock held */
2720 for (n = 0; n < subscribers->len; n++)
2722 SignalSubscriber *subscriber;
2723 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2724 if (subscriber->user_data_free_func != NULL)
2725 subscriber->user_data_free_func (subscriber->user_data);
2726 if (subscriber->context != NULL)
2727 g_main_context_unref (subscriber->context);
2730 g_array_free (subscribers, TRUE);
2733 /* ---------------------------------------------------------------------------------------------------- */
2737 guint subscription_id;
2738 GDBusSignalCallback callback;
2740 GDBusMessage *message;
2741 GDBusConnection *connection;
2742 const gchar *sender;
2744 const gchar *interface;
2745 const gchar *member;
2748 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2752 emit_signal_instance_in_idle_cb (gpointer data)
2754 SignalInstance *signal_instance = data;
2755 GVariant *parameters;
2756 gboolean has_subscription;
2758 parameters = g_dbus_message_get_body (signal_instance->message);
2759 if (parameters == NULL)
2761 parameters = g_variant_new ("()");
2762 g_variant_ref_sink (parameters);
2766 g_variant_ref_sink (parameters);
2770 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2771 signal_instance->sender,
2772 signal_instance->path,
2773 signal_instance->interface,
2774 signal_instance->member,
2775 g_variant_print (parameters, TRUE));
2778 /* Careful here, don't do the callback if we no longer has the subscription */
2779 CONNECTION_LOCK (signal_instance->connection);
2780 has_subscription = FALSE;
2781 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2782 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2783 has_subscription = TRUE;
2784 CONNECTION_UNLOCK (signal_instance->connection);
2786 if (has_subscription)
2787 signal_instance->callback (signal_instance->connection,
2788 signal_instance->sender,
2789 signal_instance->path,
2790 signal_instance->interface,
2791 signal_instance->member,
2793 signal_instance->user_data);
2795 if (parameters != NULL)
2796 g_variant_unref (parameters);
2802 signal_instance_free (SignalInstance *signal_instance)
2804 g_object_unref (signal_instance->message);
2805 g_object_unref (signal_instance->connection);
2806 g_free (signal_instance);
2809 /* called in message handler thread WITH lock held */
2811 schedule_callbacks (GDBusConnection *connection,
2812 GPtrArray *signal_data_array,
2813 GDBusMessage *message,
2814 const gchar *sender)
2817 const gchar *interface;
2818 const gchar *member;
2827 interface = g_dbus_message_get_interface (message);
2828 member = g_dbus_message_get_member (message);
2829 path = g_dbus_message_get_path (message);
2830 arg0 = g_dbus_message_get_arg0 (message);
2833 g_debug ("sender = `%s'", sender);
2834 g_debug ("interface = `%s'", interface);
2835 g_debug ("member = `%s'", member);
2836 g_debug ("path = `%s'", path);
2837 g_debug ("arg0 = `%s'", arg0);
2840 /* TODO: if this is slow, then we can change signal_data_array into
2841 * map_object_path_to_signal_data_array or something.
2843 for (n = 0; n < signal_data_array->len; n++)
2845 SignalData *signal_data = signal_data_array->pdata[n];
2847 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2850 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2853 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2856 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2859 for (m = 0; m < signal_data->subscribers->len; m++)
2861 SignalSubscriber *subscriber;
2862 GSource *idle_source;
2863 SignalInstance *signal_instance;
2865 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2867 signal_instance = g_new0 (SignalInstance, 1);
2868 signal_instance->subscription_id = subscriber->id;
2869 signal_instance->callback = subscriber->callback;
2870 signal_instance->user_data = subscriber->user_data;
2871 signal_instance->message = g_object_ref (message);
2872 signal_instance->connection = g_object_ref (connection);
2873 signal_instance->sender = sender;
2874 signal_instance->path = path;
2875 signal_instance->interface = interface;
2876 signal_instance->member = member;
2878 idle_source = g_idle_source_new ();
2879 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2880 g_source_set_callback (idle_source,
2881 emit_signal_instance_in_idle_cb,
2883 (GDestroyNotify) signal_instance_free);
2884 g_source_attach (idle_source, subscriber->context);
2885 g_source_unref (idle_source);
2890 /* called in message handler thread with lock held */
2892 distribute_signals (GDBusConnection *connection,
2893 GDBusMessage *message)
2895 GPtrArray *signal_data_array;
2896 const gchar *sender;
2898 sender = g_dbus_message_get_sender (message);
2900 /* collect subscribers that match on sender */
2903 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2904 if (signal_data_array != NULL)
2905 schedule_callbacks (connection, signal_data_array, message, sender);
2908 /* collect subscribers not matching on sender */
2909 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2910 if (signal_data_array != NULL)
2911 schedule_callbacks (connection, signal_data_array, message, sender);
2914 /* ---------------------------------------------------------------------------------------------------- */
2916 /* only called from finalize(), removes all subscriptions */
2918 purge_all_signal_subscriptions (GDBusConnection *connection)
2920 GHashTableIter iter;
2923 GArray *subscribers;
2926 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2927 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2928 while (g_hash_table_iter_next (&iter, &key, NULL))
2930 guint subscription_id = GPOINTER_TO_UINT (key);
2931 g_array_append_val (ids, subscription_id);
2934 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2935 for (n = 0; n < ids->len; n++)
2937 guint subscription_id = g_array_index (ids, guint, n);
2938 unsubscribe_id_internal (connection,
2942 g_array_free (ids, TRUE);
2944 /* call GDestroyNotify without lock held */
2945 for (n = 0; n < subscribers->len; n++)
2947 SignalSubscriber *subscriber;
2948 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2949 if (subscriber->user_data_free_func != NULL)
2950 subscriber->user_data_free_func (subscriber->user_data);
2951 if (subscriber->context != NULL)
2952 g_main_context_unref (subscriber->context);
2955 g_array_free (subscribers, TRUE);
2958 /* ---------------------------------------------------------------------------------------------------- */
2960 struct ExportedObject
2963 GDBusConnection *connection;
2965 /* maps gchar* -> ExportedInterface* */
2966 GHashTable *map_if_name_to_ei;
2969 /* only called with lock held */
2971 exported_object_free (ExportedObject *eo)
2973 g_free (eo->object_path);
2974 g_hash_table_unref (eo->map_if_name_to_ei);
2983 gchar *interface_name;
2984 const GDBusInterfaceVTable *vtable;
2985 const GDBusInterfaceInfo *introspection_data;
2987 GMainContext *context;
2989 GDestroyNotify user_data_free_func;
2990 } ExportedInterface;
2992 /* called with lock held */
2994 exported_interface_free (ExportedInterface *ei)
2996 if (ei->user_data_free_func != NULL)
2997 /* TODO: push to thread-default mainloop */
2998 ei->user_data_free_func (ei->user_data);
3000 if (ei->context != NULL)
3001 g_main_context_unref (ei->context);
3003 g_free (ei->interface_name);
3007 /* ---------------------------------------------------------------------------------------------------- */
3011 GDBusConnection *connection;
3012 GDBusMessage *message;
3014 const char *property_name;
3015 const GDBusInterfaceVTable *vtable;
3016 const GDBusInterfaceInfo *interface_info;
3017 const GDBusPropertyInfo *property_info;
3021 property_data_free (PropertyData *data)
3023 g_object_unref (data->connection);
3024 g_object_unref (data->message);
3028 /* called in thread where object was registered - no locks held */
3030 invoke_get_property_in_idle_cb (gpointer _data)
3032 PropertyData *data = _data;
3035 GDBusMessage *reply;
3038 value = data->vtable->get_property (data->connection,
3039 g_dbus_message_get_sender (data->message),
3040 g_dbus_message_get_path (data->message),
3041 data->interface_info->name,
3042 data->property_name,
3049 g_assert_no_error (error);
3051 g_variant_ref_sink (value);
3052 reply = g_dbus_message_new_method_reply (data->message);
3053 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3054 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3055 g_variant_unref (value);
3056 g_object_unref (reply);
3060 gchar *dbus_error_name;
3062 g_assert (error != NULL);
3064 dbus_error_name = g_dbus_error_encode_gerror (error);
3065 reply = g_dbus_message_new_method_error_literal (data->message,
3068 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3069 g_free (dbus_error_name);
3070 g_error_free (error);
3071 g_object_unref (reply);
3077 /* called in thread where object was registered - no locks held */
3079 invoke_set_property_in_idle_cb (gpointer _data)
3081 PropertyData *data = _data;
3083 GDBusMessage *reply;
3089 g_variant_get (g_dbus_message_get_body (data->message),
3095 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3096 * of the given value is wrong
3098 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3100 reply = g_dbus_message_new_method_error (data->message,
3101 "org.freedesktop.DBus.Error.InvalidArgs",
3102 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3103 data->property_info->name,
3104 data->property_info->signature,
3105 g_variant_get_type_string (value));
3109 if (!data->vtable->set_property (data->connection,
3110 g_dbus_message_get_sender (data->message),
3111 g_dbus_message_get_path (data->message),
3112 data->interface_info->name,
3113 data->property_name,
3118 gchar *dbus_error_name;
3119 g_assert (error != NULL);
3120 dbus_error_name = g_dbus_error_encode_gerror (error);
3121 reply = g_dbus_message_new_method_error_literal (data->message,
3124 g_free (dbus_error_name);
3125 g_error_free (error);
3129 reply = g_dbus_message_new_method_reply (data->message);
3133 g_assert (reply != NULL);
3134 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3135 g_object_unref (reply);
3140 /* called with lock held */
3142 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3143 GDBusMessage *message,
3145 const GDBusInterfaceInfo *introspection_data,
3146 const GDBusInterfaceVTable *vtable,
3147 GMainContext *main_context,
3151 const char *interface_name;
3152 const char *property_name;
3153 const GDBusPropertyInfo *property_info;
3154 GSource *idle_source;
3155 PropertyData *property_data;
3156 GDBusMessage *reply;
3161 g_variant_get (g_dbus_message_get_body (message),
3166 g_variant_get (g_dbus_message_get_body (message),
3175 if (vtable == NULL || vtable->get_property == NULL)
3180 if (vtable == NULL || vtable->set_property == NULL)
3184 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3186 property_info = NULL;
3188 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3189 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3190 if (property_info == NULL)
3192 reply = g_dbus_message_new_method_error (message,
3193 "org.freedesktop.DBus.Error.InvalidArgs",
3194 _("No such property `%s'"),
3196 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3197 g_object_unref (reply);
3202 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3204 reply = g_dbus_message_new_method_error (message,
3205 "org.freedesktop.DBus.Error.InvalidArgs",
3206 _("Property `%s' is not readable"),
3208 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3209 g_object_unref (reply);
3213 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3215 reply = g_dbus_message_new_method_error (message,
3216 "org.freedesktop.DBus.Error.InvalidArgs",
3217 _("Property `%s' is not writable"),
3219 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3220 g_object_unref (reply);
3225 /* ok, got the property info - call user code in an idle handler */
3226 property_data = g_new0 (PropertyData, 1);
3227 property_data->connection = g_object_ref (connection);
3228 property_data->message = g_object_ref (message);
3229 property_data->user_data = user_data;
3230 property_data->property_name = property_name;
3231 property_data->vtable = vtable;
3232 property_data->interface_info = introspection_data;
3233 property_data->property_info = property_info;
3235 idle_source = g_idle_source_new ();
3236 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3237 g_source_set_callback (idle_source,
3238 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3240 (GDestroyNotify) property_data_free);
3241 g_source_attach (idle_source, main_context);
3242 g_source_unref (idle_source);
3250 /* called with lock held */
3252 handle_getset_property (GDBusConnection *connection,
3254 GDBusMessage *message,
3257 ExportedInterface *ei;
3259 const char *interface_name;
3260 const char *property_name;
3265 g_variant_get (g_dbus_message_get_body (message),
3270 g_variant_get (g_dbus_message_get_body (message),
3276 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3277 * no such interface registered
3279 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3282 GDBusMessage *reply;
3283 reply = g_dbus_message_new_method_error (message,
3284 "org.freedesktop.DBus.Error.InvalidArgs",
3285 _("No such interface `%s'"),
3287 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3288 g_object_unref (reply);
3293 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3296 ei->introspection_data,
3304 /* ---------------------------------------------------------------------------------------------------- */
3308 GDBusConnection *connection;
3309 GDBusMessage *message;
3311 const GDBusInterfaceVTable *vtable;
3312 const GDBusInterfaceInfo *interface_info;
3313 } PropertyGetAllData;
3316 property_get_all_data_free (PropertyData *data)
3318 g_object_unref (data->connection);
3319 g_object_unref (data->message);
3323 /* called in thread where object was registered - no locks held */
3325 invoke_get_all_properties_in_idle_cb (gpointer _data)
3327 PropertyGetAllData *data = _data;
3328 GVariantBuilder *builder;
3332 GDBusMessage *reply;
3337 /* TODO: Right now we never fail this call - we just omit values if
3338 * a get_property() call is failing.
3340 * We could fail the whole call if just a single get_property() call
3341 * returns an error. We need clarification in the D-Bus spec about this.
3343 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3344 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3346 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3349 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3352 value = data->vtable->get_property (data->connection,
3353 g_dbus_message_get_sender (data->message),
3354 g_dbus_message_get_path (data->message),
3355 data->interface_info->name,
3356 property_info->name,
3363 g_variant_ref_sink (value);
3364 g_variant_builder_add (builder,
3366 property_info->name,
3368 g_variant_unref (value);
3370 result = g_variant_builder_end (builder);
3372 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3373 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3374 packed = g_variant_builder_end (builder);
3376 reply = g_dbus_message_new_method_reply (data->message);
3377 g_dbus_message_set_body (reply, packed);
3378 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3379 g_object_unref (reply);
3384 /* called with lock held */
3386 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3387 GDBusMessage *message,
3388 const GDBusInterfaceInfo *introspection_data,
3389 const GDBusInterfaceVTable *vtable,
3390 GMainContext *main_context,
3394 const char *interface_name;
3395 GSource *idle_source;
3396 PropertyGetAllData *property_get_all_data;
3400 g_variant_get (g_dbus_message_get_body (message),
3404 if (vtable == NULL || vtable->get_property == NULL)
3407 /* ok, got the property info - call user in an idle handler */
3408 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3409 property_get_all_data->connection = g_object_ref (connection);
3410 property_get_all_data->message = g_object_ref (message);
3411 property_get_all_data->user_data = user_data;
3412 property_get_all_data->vtable = vtable;
3413 property_get_all_data->interface_info = introspection_data;
3415 idle_source = g_idle_source_new ();
3416 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3417 g_source_set_callback (idle_source,
3418 invoke_get_all_properties_in_idle_cb,
3419 property_get_all_data,
3420 (GDestroyNotify) property_get_all_data_free);
3421 g_source_attach (idle_source, main_context);
3422 g_source_unref (idle_source);
3430 /* called with lock held */
3432 handle_get_all_properties (GDBusConnection *connection,
3434 GDBusMessage *message)
3436 ExportedInterface *ei;
3438 const char *interface_name;
3442 g_variant_get (g_dbus_message_get_body (message),
3446 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3447 * no such interface registered
3449 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3452 GDBusMessage *reply;
3453 reply = g_dbus_message_new_method_error (message,
3454 "org.freedesktop.DBus.Error.InvalidArgs",
3455 _("No such interface"),
3457 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3458 g_object_unref (reply);
3463 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3465 ei->introspection_data,
3473 /* ---------------------------------------------------------------------------------------------------- */
3475 static const gchar introspect_header[] =
3476 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3477 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3478 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3481 static const gchar introspect_tail[] =
3484 static const gchar introspect_standard_interfaces[] =
3485 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3486 " <method name=\"Get\">\n"
3487 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3488 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3489 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3491 " <method name=\"GetAll\">\n"
3492 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3493 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3495 " <method name=\"Set\">\n"
3496 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3497 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3498 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3500 " <signal name=\"PropertiesChanged\">\n"
3501 " <arg type=\"s\" name=\"interface_name\"/>\n"
3502 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3505 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3506 " <method name=\"Introspect\">\n"
3507 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3510 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3511 " <method name=\"Ping\"/>\n"
3512 " <method name=\"GetMachineId\">\n"
3513 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3518 introspect_append_header (GString *s)
3520 g_string_append (s, introspect_header);
3524 introspect_append_standard_interfaces (GString *s)
3526 g_string_append (s, introspect_standard_interfaces);
3530 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3532 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3538 begin = object_path + path_len;
3539 end = strchr (begin, '/');
3542 s = g_strndup (begin, end - begin);
3544 s = g_strdup (begin);
3546 if (g_hash_table_lookup (set, s) == NULL)
3547 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3553 /* TODO: we want a nicer public interface for this */
3555 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3560 GHashTableIter hash_iter;
3561 const gchar *object_path;
3567 CONNECTION_ENSURE_LOCK (connection);
3569 path_len = strlen (path);
3573 set = g_hash_table_new (g_str_hash, g_str_equal);
3575 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3576 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3577 maybe_add_path (path, path_len, object_path, set);
3579 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3580 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3581 maybe_add_path (path, path_len, object_path, set);
3583 p = g_ptr_array_new ();
3584 keys = g_hash_table_get_keys (set);
3585 for (l = keys; l != NULL; l = l->next)
3586 g_ptr_array_add (p, l->data);
3587 g_hash_table_unref (set);
3590 g_ptr_array_add (p, NULL);
3591 ret = (gchar **) g_ptr_array_free (p, FALSE);
3596 g_dbus_connection_list_registered (GDBusConnection *connection,
3600 CONNECTION_LOCK (connection);
3601 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3602 CONNECTION_UNLOCK (connection);
3606 /* called in message handler thread with lock held */
3608 handle_introspect (GDBusConnection *connection,
3610 GDBusMessage *message)
3614 GDBusMessage *reply;
3615 GHashTableIter hash_iter;
3616 ExportedInterface *ei;
3619 /* first the header with the standard interfaces */
3620 s = g_string_sized_new (sizeof (introspect_header) +
3621 sizeof (introspect_standard_interfaces) +
3622 sizeof (introspect_tail));
3623 introspect_append_header (s);
3624 introspect_append_standard_interfaces (s);
3626 /* then include the registered interfaces */
3627 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3628 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3629 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3631 /* finally include nodes registered below us */
3632 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3633 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3634 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3635 g_strfreev (registered);
3636 g_string_append (s, introspect_tail);
3638 reply = g_dbus_message_new_method_reply (message);
3639 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3640 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3641 g_object_unref (reply);
3642 g_string_free (s, TRUE);
3647 /* called in thread where object was registered - no locks held */
3649 invoke_method_in_idle_cb (gpointer user_data)
3651 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3652 GDBusInterfaceVTable *vtable;
3654 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3655 g_assert (vtable != NULL && vtable->method_call != NULL);
3657 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3658 g_dbus_method_invocation_get_sender (invocation),
3659 g_dbus_method_invocation_get_object_path (invocation),
3660 g_dbus_method_invocation_get_interface_name (invocation),
3661 g_dbus_method_invocation_get_method_name (invocation),
3662 g_dbus_method_invocation_get_parameters (invocation),
3663 g_object_ref (invocation),
3664 g_dbus_method_invocation_get_user_data (invocation));
3669 /* called in message handler thread with lock held */
3671 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3672 GDBusMessage *message,
3673 const GDBusInterfaceInfo *introspection_data,
3674 const GDBusInterfaceVTable *vtable,
3675 GMainContext *main_context,
3678 GDBusMethodInvocation *invocation;
3679 const GDBusMethodInfo *method_info;
3680 GDBusMessage *reply;
3681 GVariant *parameters;
3682 GSource *idle_source;
3684 gchar *in_signature;
3688 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3689 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3691 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3692 * error to the caller
3694 if (method_info == NULL)
3696 reply = g_dbus_message_new_method_error (message,
3697 "org.freedesktop.DBus.Error.UnknownMethod",
3698 _("No such method `%s'"),
3699 g_dbus_message_get_member (message));
3700 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3701 g_object_unref (reply);
3706 /* Check that the incoming args are of the right type - if they are not, return
3707 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3709 * TODO: might also be worth caching the combined signature.
3711 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3712 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3714 reply = g_dbus_message_new_method_error (message,
3715 "org.freedesktop.DBus.Error.InvalidArgs",
3716 _("Signature of message, `%s', does not match expected signature `%s'"),
3717 g_dbus_message_get_signature (message),
3719 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3720 g_object_unref (reply);
3721 g_free (in_signature);
3725 g_free (in_signature);
3727 parameters = g_dbus_message_get_body (message);
3728 if (parameters == NULL)
3730 parameters = g_variant_new ("()");
3731 g_variant_ref_sink (parameters);
3735 g_variant_ref (parameters);
3738 /* schedule the call in idle */
3739 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3740 g_dbus_message_get_path (message),
3741 g_dbus_message_get_interface (message),
3742 g_dbus_message_get_member (message),
3748 g_variant_unref (parameters);
3749 g_object_set_data (G_OBJECT (invocation),
3750 "g-dbus-interface-vtable",
3753 idle_source = g_idle_source_new ();
3754 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3755 g_source_set_callback (idle_source,
3756 invoke_method_in_idle_cb,
3759 g_source_attach (idle_source, main_context);
3760 g_source_unref (idle_source);
3768 /* ---------------------------------------------------------------------------------------------------- */
3770 /* called in message handler thread with lock held */
3772 obj_message_func (GDBusConnection *connection,
3774 GDBusMessage *message)
3776 const gchar *interface_name;
3777 const gchar *member;
3778 const gchar *signature;
3783 interface_name = g_dbus_message_get_interface (message);
3784 member = g_dbus_message_get_member (message);
3785 signature = g_dbus_message_get_signature (message);
3787 /* see if we have an interface for handling this call */
3788 if (interface_name != NULL)
3790 ExportedInterface *ei;
3791 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3794 /* we do - invoke the handler in idle in the right thread */
3796 /* handle no vtable or handler being present */
3797 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3800 handled = validate_and_maybe_schedule_method_call (connection,
3802 ei->introspection_data,
3810 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3811 g_strcmp0 (member, "Introspect") == 0 &&
3812 g_strcmp0 (signature, "") == 0)
3814 handled = handle_introspect (connection, eo, message);
3817 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3818 g_strcmp0 (member, "Get") == 0 &&
3819 g_strcmp0 (signature, "ss") == 0)
3821 handled = handle_getset_property (connection, eo, message, TRUE);
3824 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3825 g_strcmp0 (member, "Set") == 0 &&
3826 g_strcmp0 (signature, "ssv") == 0)
3828 handled = handle_getset_property (connection, eo, message, FALSE);
3831 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3832 g_strcmp0 (member, "GetAll") == 0 &&
3833 g_strcmp0 (signature, "s") == 0)
3835 handled = handle_get_all_properties (connection, eo, message);
3844 * g_dbus_connection_register_object:
3845 * @connection: A #GDBusConnection.
3846 * @object_path: The object path to register at.
3847 * @interface_name: The D-Bus interface to register.
3848 * @introspection_data: Introspection data for the interface.
3849 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3850 * @user_data: Data to pass to functions in @vtable.
3851 * @user_data_free_func: Function to call when the object path is unregistered.
3852 * @error: Return location for error or %NULL.
3854 * Registers callbacks for exported objects at @object_path with the
3855 * D-Bus interface @interface_name.
3857 * Calls to functions in @vtable (and @user_data_free_func) will
3858 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3859 * loop</link> of the thread you are calling this method from.
3861 * Note that all #GVariant values passed to functions in @vtable will match
3862 * the signature given in @introspection_data - if a remote caller passes
3863 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3864 * is returned to the remote caller.
3866 * Additionally, if the remote caller attempts to invoke methods or
3867 * access properties not mentioned in @introspection_data the
3868 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3869 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3870 * are returned to the caller.
3872 * It is considered a programming error if the
3873 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3874 * #GVariant of incorrect type.
3876 * If an existing callback is already registered at @object_path and
3877 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3879 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3881 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3882 * that can be used with g_dbus_connection_unregister_object() .
3887 g_dbus_connection_register_object (GDBusConnection *connection,
3888 const gchar *object_path,
3889 const gchar *interface_name,
3890 const GDBusInterfaceInfo *introspection_data,
3891 const GDBusInterfaceVTable *vtable,
3893 GDestroyNotify user_data_free_func,
3897 ExportedInterface *ei;
3900 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3901 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3902 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3903 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3904 g_return_val_if_fail (introspection_data != NULL, 0);
3905 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3909 CONNECTION_LOCK (connection);
3911 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3914 eo = g_new0 (ExportedObject, 1);
3915 eo->object_path = g_strdup (object_path);
3916 eo->connection = connection;
3917 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3920 (GDestroyNotify) exported_interface_free);
3921 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3924 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3930 _("An object is already exported for the interface %s at %s"),
3936 ei = g_new0 (ExportedInterface, 1);
3937 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3939 ei->user_data = user_data;
3940 ei->user_data_free_func = user_data_free_func;
3941 ei->vtable = vtable;
3942 ei->introspection_data = introspection_data;
3943 ei->interface_name = g_strdup (interface_name);
3944 ei->context = g_main_context_get_thread_default ();
3945 if (ei->context != NULL)
3946 g_main_context_ref (ei->context);
3948 g_hash_table_insert (eo->map_if_name_to_ei,
3949 (gpointer) ei->interface_name,
3951 g_hash_table_insert (connection->priv->map_id_to_ei,
3952 GUINT_TO_POINTER (ei->id),
3958 CONNECTION_UNLOCK (connection);
3964 * g_dbus_connection_unregister_object:
3965 * @connection: A #GDBusConnection.
3966 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3968 * Unregisters an object.
3970 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3975 g_dbus_connection_unregister_object (GDBusConnection *connection,
3976 guint registration_id)
3978 ExportedInterface *ei;
3982 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3986 CONNECTION_LOCK (connection);
3988 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
3989 GUINT_TO_POINTER (registration_id));
3995 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
3996 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
3997 /* unregister object path if we have no more exported interfaces */
3998 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
3999 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4005 CONNECTION_UNLOCK (connection);
4010 /* ---------------------------------------------------------------------------------------------------- */
4013 * g_dbus_connection_emit_signal:
4014 * @connection: A #GDBusConnection.
4015 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4016 * @object_path: Path of remote object.
4017 * @interface_name: D-Bus interface to emit a signal on.
4018 * @signal_name: The name of the signal to emit.
4019 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4020 * @error: Return location for error or %NULL.
4024 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4026 * Returns: %TRUE unless @error is set.
4031 g_dbus_connection_emit_signal (GDBusConnection *connection,
4032 const gchar *destination_bus_name,
4033 const gchar *object_path,
4034 const gchar *interface_name,
4035 const gchar *signal_name,
4036 GVariant *parameters,
4039 GDBusMessage *message;
4045 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4046 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4047 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4048 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4049 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4050 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4052 message = g_dbus_message_new_signal (object_path,
4056 if (destination_bus_name != NULL)
4057 g_dbus_message_set_header (message,
4058 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4059 g_variant_new_string (destination_bus_name));
4061 if (parameters != NULL)
4062 g_dbus_message_set_body (message, parameters);
4064 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4065 g_object_unref (message);
4071 add_invoke_method_flags (GDBusMessage *message,
4072 GDBusInvokeMethodFlags flags)
4074 if (flags & G_DBUS_INVOKE_METHOD_FLAGS_NO_AUTO_START)
4075 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4079 * g_dbus_connection_invoke_method:
4080 * @connection: A #GDBusConnection.
4081 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4082 * @object_path: Path of remote object.
4083 * @interface_name: D-Bus interface to invoke method on.
4084 * @method_name: The name of the method to invoke.
4085 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4086 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4087 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4088 * @cancellable: A #GCancellable or %NULL.
4089 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4090 * care about the result of the method invocation.
4091 * @user_data: The data to pass to @callback.
4093 * Asynchronously invokes the @method_name method on the
4094 * @interface_name D-Bus interface on the remote object at
4095 * @object_path owned by @bus_name.
4097 * If @connection is closed then the operation will fail with
4098 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4099 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4100 * not compatible with the D-Bus protocol, the operation fails with
4101 * %G_IO_ERROR_INVALID_ARGUMENT.
4103 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4104 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4105 * of the thread you are calling this method from. You can then call
4106 * g_dbus_connection_invoke_method_finish() to get the result of the operation.
4107 * See g_dbus_connection_invoke_method_sync() for the synchronous version of this
4113 g_dbus_connection_invoke_method (GDBusConnection *connection,
4114 const gchar *bus_name,
4115 const gchar *object_path,
4116 const gchar *interface_name,
4117 const gchar *method_name,
4118 GVariant *parameters,
4119 GDBusInvokeMethodFlags flags,
4121 GCancellable *cancellable,
4122 GAsyncReadyCallback callback,
4125 GDBusMessage *message;
4127 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4128 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4129 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4130 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4131 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4132 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4133 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4135 message = g_dbus_message_new_method_call (bus_name,
4139 add_invoke_method_flags (message, flags);
4140 if (parameters != NULL)
4141 g_dbus_message_set_body (message, parameters);
4143 g_dbus_connection_send_message_with_reply (connection,
4146 NULL, /* volatile guint32 *out_serial */
4151 if (message != NULL)
4152 g_object_unref (message);
4156 decode_method_reply (GDBusMessage *reply,
4162 switch (g_dbus_message_get_message_type (reply))
4164 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4165 result = g_dbus_message_get_body (reply);
4168 result = g_variant_new ("()");
4169 g_variant_ref_sink (result);
4173 g_variant_ref (result);
4177 case G_DBUS_MESSAGE_TYPE_ERROR:
4178 g_dbus_message_to_gerror (reply, error);
4182 g_assert_not_reached ();
4190 * g_dbus_connection_invoke_method_finish:
4191 * @connection: A #GDBusConnection.
4192 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_invoke_method().
4193 * @error: Return location for error or %NULL.
4195 * Finishes an operation started with g_dbus_connection_invoke_method().
4197 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4198 * return values. Free with g_variant_unref().
4203 g_dbus_connection_invoke_method_finish (GDBusConnection *connection,
4207 GDBusMessage *reply;
4210 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4211 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4212 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4216 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4220 result = decode_method_reply (reply, error);
4222 g_object_unref (reply);
4228 /* ---------------------------------------------------------------------------------------------------- */
4231 * g_dbus_connection_invoke_method_sync:
4232 * @connection: A #GDBusConnection.
4233 * @bus_name: A unique or well-known bus name.
4234 * @object_path: Path of remote object.
4235 * @interface_name: D-Bus interface to invoke method on.
4236 * @method_name: The name of the method to invoke.
4237 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4238 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4239 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4240 * @cancellable: A #GCancellable or %NULL.
4241 * @error: Return location for error or %NULL.
4243 * Synchronously invokes the @method_name method on the
4244 * @interface_name D-Bus interface on the remote object at
4245 * @object_path owned by @bus_name.
4247 * If @connection is closed then the operation will fail with
4248 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4249 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4250 * contains a value not compatible with the D-Bus protocol, the operation
4251 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4253 * The calling thread is blocked until a reply is received. See
4254 * g_dbus_connection_invoke_method() for the asynchronous version of
4257 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4258 * return values. Free with g_variant_unref().
4263 g_dbus_connection_invoke_method_sync (GDBusConnection *connection,
4264 const gchar *bus_name,
4265 const gchar *object_path,
4266 const gchar *interface_name,
4267 const gchar *method_name,
4268 GVariant *parameters,
4269 GDBusInvokeMethodFlags flags,
4271 GCancellable *cancellable,
4274 GDBusMessage *message;
4275 GDBusMessage *reply;
4282 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4283 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4284 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4285 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4286 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4287 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4288 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4290 message = g_dbus_message_new_method_call (bus_name,
4294 add_invoke_method_flags (message, flags);
4295 if (parameters != NULL)
4296 g_dbus_message_set_body (message, parameters);
4298 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4301 NULL, /* volatile guint32 *out_serial */
4308 result = decode_method_reply (reply, error);
4311 if (message != NULL)
4312 g_object_unref (message);
4314 g_object_unref (reply);
4319 /* ---------------------------------------------------------------------------------------------------- */
4321 struct ExportedSubtree
4325 GDBusConnection *connection;
4326 const GDBusSubtreeVTable *vtable;
4327 GDBusSubtreeFlags flags;
4329 GMainContext *context;
4331 GDestroyNotify user_data_free_func;
4335 exported_subtree_free (ExportedSubtree *es)
4337 if (es->user_data_free_func != NULL)
4338 /* TODO: push to thread-default mainloop */
4339 es->user_data_free_func (es->user_data);
4341 if (es->context != NULL)
4342 g_main_context_unref (es->context);
4344 g_free (es->object_path);
4348 /* called without lock held */
4350 handle_subtree_introspect (GDBusConnection *connection,
4351 ExportedSubtree *es,
4352 GDBusMessage *message)
4356 GDBusMessage *reply;
4359 const gchar *sender;
4360 const gchar *requested_object_path;
4361 const gchar *requested_node;
4362 GPtrArray *interfaces;
4364 gchar **subnode_paths;
4368 requested_object_path = g_dbus_message_get_path (message);
4369 sender = g_dbus_message_get_sender (message);
4370 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4372 s = g_string_new (NULL);
4373 introspect_append_header (s);
4375 /* Strictly we don't need the children in dynamic mode, but we avoid the
4376 * conditionals to preserve code clarity
4378 children = es->vtable->enumerate (es->connection,
4385 requested_node = strrchr (requested_object_path, '/') + 1;
4387 /* Assert existence of object if we are not dynamic */
4388 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4389 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4394 requested_node = "/";
4397 interfaces = es->vtable->introspect (es->connection,
4402 if (interfaces != NULL)
4404 if (interfaces->len > 0)
4406 /* we're in business */
4407 introspect_append_standard_interfaces (s);
4409 for (n = 0; n < interfaces->len; n++)
4411 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4412 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4415 g_ptr_array_unref (interfaces);
4418 /* then include <node> entries from the Subtree for the root */
4421 for (n = 0; children != NULL && children[n] != NULL; n++)
4422 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4425 /* finally include nodes registered below us */
4426 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4427 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4428 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4429 g_strfreev (subnode_paths);
4431 g_string_append (s, "</node>\n");
4433 reply = g_dbus_message_new_method_reply (message);
4434 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4435 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4436 g_object_unref (reply);
4441 g_string_free (s, TRUE);
4442 g_strfreev (children);
4446 /* called without lock held */
4448 handle_subtree_method_invocation (GDBusConnection *connection,
4449 ExportedSubtree *es,
4450 GDBusMessage *message)
4453 const gchar *sender;
4454 const gchar *interface_name;
4455 const gchar *member;
4456 const gchar *signature;
4457 const gchar *requested_object_path;
4458 const gchar *requested_node;
4461 const GDBusInterfaceInfo *introspection_data;
4462 const GDBusInterfaceVTable *interface_vtable;
4463 gpointer interface_user_data;
4465 GPtrArray *interfaces;
4466 gboolean is_property_get;
4467 gboolean is_property_set;
4468 gboolean is_property_get_all;
4473 requested_object_path = g_dbus_message_get_path (message);
4474 sender = g_dbus_message_get_sender (message);
4475 interface_name = g_dbus_message_get_interface (message);
4476 member = g_dbus_message_get_member (message);
4477 signature = g_dbus_message_get_signature (message);
4478 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4480 is_property_get = FALSE;
4481 is_property_set = FALSE;
4482 is_property_get_all = FALSE;
4483 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4485 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4486 is_property_get = TRUE;
4487 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4488 is_property_set = TRUE;
4489 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4490 is_property_get_all = TRUE;
4493 children = es->vtable->enumerate (es->connection,
4500 requested_node = strrchr (requested_object_path, '/') + 1;
4502 /* If not dynamic, skip if requested node is not part of children */
4503 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4504 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4509 requested_node = "/";
4512 /* get introspection data for the node */
4513 interfaces = es->vtable->introspect (es->connection,
4515 requested_object_path,
4518 g_assert (interfaces != NULL);
4519 introspection_data = NULL;
4520 for (n = 0; n < interfaces->len; n++)
4522 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4523 if (g_strcmp0 (id_n->name, interface_name) == 0)
4524 introspection_data = id_n;
4527 /* dispatch the call if the user wants to handle it */
4528 if (introspection_data != NULL)
4530 /* figure out where to dispatch the method call */
4531 interface_user_data = NULL;
4532 interface_vtable = es->vtable->dispatch (es->connection,
4537 &interface_user_data,
4539 if (interface_vtable == NULL)
4542 CONNECTION_LOCK (connection);
4543 handled = validate_and_maybe_schedule_method_call (es->connection,
4548 interface_user_data);
4549 CONNECTION_UNLOCK (connection);
4551 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4552 else if (is_property_get || is_property_set || is_property_get_all)
4554 if (is_property_get)
4555 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4556 else if (is_property_set)
4557 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4558 else if (is_property_get_all)
4559 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4561 g_assert_not_reached ();
4563 /* see if the object supports this interface at all */
4564 for (n = 0; n < interfaces->len; n++)
4566 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4567 if (g_strcmp0 (id_n->name, interface_name) == 0)
4568 introspection_data = id_n;
4571 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4572 * claims it won't support the interface
4574 if (introspection_data == NULL)
4576 GDBusMessage *reply;
4577 reply = g_dbus_message_new_method_error (message,
4578 "org.freedesktop.DBus.Error.InvalidArgs",
4579 _("No such interface `%s'"),
4581 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4582 g_object_unref (reply);
4587 /* figure out where to dispatch the property get/set/getall calls */
4588 interface_user_data = NULL;
4589 interface_vtable = es->vtable->dispatch (es->connection,
4594 &interface_user_data,
4596 if (interface_vtable == NULL)
4599 if (is_property_get || is_property_set)
4601 CONNECTION_LOCK (connection);
4602 handled = validate_and_maybe_schedule_property_getset (es->connection,
4608 interface_user_data);
4609 CONNECTION_UNLOCK (connection);
4611 else if (is_property_get_all)
4613 CONNECTION_LOCK (connection);
4614 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4619 interface_user_data);
4620 CONNECTION_UNLOCK (connection);
4625 if (interfaces != NULL)
4626 g_ptr_array_unref (interfaces);
4627 g_strfreev (children);
4633 GDBusMessage *message;
4634 ExportedSubtree *es;
4635 } SubtreeDeferredData;
4638 subtree_deferred_data_free (SubtreeDeferredData *data)
4640 g_object_unref (data->message);
4644 /* called without lock held in the thread where the caller registered the subtree */
4646 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4648 SubtreeDeferredData *data = _data;
4653 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4654 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4655 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4656 handled = handle_subtree_introspect (data->es->connection,
4660 handled = handle_subtree_method_invocation (data->es->connection,
4666 CONNECTION_LOCK (data->es->connection);
4667 handled = handle_generic_unlocked (data->es->connection, data->message);
4668 CONNECTION_UNLOCK (data->es->connection);
4671 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4674 GDBusMessage *reply;
4675 reply = g_dbus_message_new_method_error (data->message,
4676 "org.freedesktop.DBus.Error.UnknownMethod",
4677 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4678 g_dbus_message_get_member (data->message),
4679 g_dbus_message_get_interface (data->message),
4680 g_dbus_message_get_signature (data->message));
4681 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4682 g_object_unref (reply);
4688 /* called in message handler thread with lock held */
4690 subtree_message_func (GDBusConnection *connection,
4691 ExportedSubtree *es,
4692 GDBusMessage *message)
4694 GSource *idle_source;
4695 SubtreeDeferredData *data;
4697 data = g_new0 (SubtreeDeferredData, 1);
4698 data->message = g_object_ref (message);
4701 /* defer this call to an idle handler in the right thread */
4702 idle_source = g_idle_source_new ();
4703 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4704 g_source_set_callback (idle_source,
4705 process_subtree_vtable_message_in_idle_cb,
4707 (GDestroyNotify) subtree_deferred_data_free);
4708 g_source_attach (idle_source, es->context);
4709 g_source_unref (idle_source);
4711 /* since we own the entire subtree, handlers for objects not in the subtree have been
4712 * tried already by libdbus-1 - so we just need to ensure that we're always going
4713 * to reply to the message
4719 * g_dbus_connection_register_subtree:
4720 * @connection: A #GDBusConnection.
4721 * @object_path: The object path to register the subtree at.
4722 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4723 * @flags: Flags used to fine tune the behavior of the subtree.
4724 * @user_data: Data to pass to functions in @vtable.
4725 * @user_data_free_func: Function to call when the subtree is unregistered.
4726 * @error: Return location for error or %NULL.
4728 * Registers a whole subtree of <quote>dynamic</quote> objects.
4730 * The @enumerate and @introspection functions in @vtable are used to
4731 * convey, to remote callers, what nodes exist in the subtree rooted
4734 * When handling remote calls into any node in the subtree, first the
4735 * @enumerate function is used to check if the node exists. If the node exists
4736 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4737 * the @introspection function is used to check if the node supports the
4738 * requested method. If so, the @dispatch function is used to determine
4739 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4740 * #gpointer will be used to call into the interface vtable for processing
4743 * All calls into user-provided code will be invoked in the <link
4744 * linkend="g-main-context-push-thread-default">thread-default main
4745 * loop</link> of the thread you are calling this method from.
4747 * If an existing subtree is already registered at @object_path or
4748 * then @error is set to #G_IO_ERROR_EXISTS.
4750 * Note that it is valid to register regular objects (using
4751 * g_dbus_connection_register_object()) in a subtree registered with
4752 * g_dbus_connection_register_subtree() - if so, the subtree handler
4753 * is tried as the last resort. One way to think about a subtree
4754 * handler is to consider it a <quote>fallback handler</quote>
4755 * for object paths not registered via g_dbus_connection_register_object()
4756 * or other bindings.
4758 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4760 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4761 * that can be used with g_dbus_connection_unregister_subtree() .
4766 g_dbus_connection_register_subtree (GDBusConnection *connection,
4767 const gchar *object_path,
4768 const GDBusSubtreeVTable *vtable,
4769 GDBusSubtreeFlags flags,
4771 GDestroyNotify user_data_free_func,
4775 ExportedSubtree *es;
4777 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4778 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4779 g_return_val_if_fail (vtable != NULL, 0);
4780 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4784 CONNECTION_LOCK (connection);
4786 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4792 _("A subtree is already exported for %s"),
4797 es = g_new0 (ExportedSubtree, 1);
4798 es->object_path = g_strdup (object_path);
4799 es->connection = connection;
4801 es->vtable = vtable;
4803 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4804 es->user_data = user_data;
4805 es->user_data_free_func = user_data_free_func;
4806 es->context = g_main_context_get_thread_default ();
4807 if (es->context != NULL)
4808 g_main_context_ref (es->context);
4810 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4811 g_hash_table_insert (connection->priv->map_id_to_es,
4812 GUINT_TO_POINTER (es->id),
4818 CONNECTION_UNLOCK (connection);
4823 /* ---------------------------------------------------------------------------------------------------- */
4826 * g_dbus_connection_unregister_subtree:
4827 * @connection: A #GDBusConnection.
4828 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4830 * Unregisters a subtree.
4832 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4837 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4838 guint registration_id)
4840 ExportedSubtree *es;
4843 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4847 CONNECTION_LOCK (connection);
4849 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4850 GUINT_TO_POINTER (registration_id));
4854 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4855 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4860 CONNECTION_UNLOCK (connection);
4865 /* ---------------------------------------------------------------------------------------------------- */
4867 /* must be called with lock held */
4869 handle_generic_ping_unlocked (GDBusConnection *connection,
4870 const gchar *object_path,
4871 GDBusMessage *message)
4873 GDBusMessage *reply;
4874 reply = g_dbus_message_new_method_reply (message);
4875 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4876 g_object_unref (reply);
4879 /* must be called with lock held */
4881 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4882 const gchar *object_path,
4883 GDBusMessage *message)
4885 GDBusMessage *reply;
4888 if (connection->priv->machine_id == NULL)
4892 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4893 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4894 &connection->priv->machine_id,
4898 reply = g_dbus_message_new_method_error (message,
4899 "org.freedesktop.DBus.Error.Failed",
4900 _("Unable to load /var/lib/dbus/machine-id: %s"),
4902 g_error_free (error);
4906 g_strstrip (connection->priv->machine_id);
4907 /* TODO: validate value */
4913 reply = g_dbus_message_new_method_reply (message);
4914 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4916 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4917 g_object_unref (reply);
4920 /* must be called with lock held */
4922 handle_generic_introspect_unlocked (GDBusConnection *connection,
4923 const gchar *object_path,
4924 GDBusMessage *message)
4929 GDBusMessage *reply;
4931 /* first the header */
4932 s = g_string_new (NULL);
4933 introspect_append_header (s);
4935 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4936 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4937 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4938 g_strfreev (registered);
4939 g_string_append (s, "</node>\n");
4941 reply = g_dbus_message_new_method_reply (message);
4942 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4943 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4944 g_object_unref (reply);
4945 g_string_free (s, TRUE);
4948 /* must be called with lock held */
4950 handle_generic_unlocked (GDBusConnection *connection,
4951 GDBusMessage *message)
4954 const gchar *interface_name;
4955 const gchar *member;
4956 const gchar *signature;
4959 CONNECTION_ENSURE_LOCK (connection);
4963 interface_name = g_dbus_message_get_interface (message);
4964 member = g_dbus_message_get_member (message);
4965 signature = g_dbus_message_get_signature (message);
4966 path = g_dbus_message_get_path (message);
4968 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4969 g_strcmp0 (member, "Introspect") == 0 &&
4970 g_strcmp0 (signature, "") == 0)
4972 handle_generic_introspect_unlocked (connection, path, message);
4975 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4976 g_strcmp0 (member, "Ping") == 0 &&
4977 g_strcmp0 (signature, "") == 0)
4979 handle_generic_ping_unlocked (connection, path, message);
4982 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4983 g_strcmp0 (member, "GetMachineId") == 0 &&
4984 g_strcmp0 (signature, "") == 0)
4986 handle_generic_get_machine_id_unlocked (connection, path, message);
4993 /* ---------------------------------------------------------------------------------------------------- */
4995 /* called in message handler thread with lock held */
4997 distribute_method_call (GDBusConnection *connection,
4998 GDBusMessage *message)
5001 ExportedSubtree *es;
5002 const gchar *object_path;
5003 const gchar *interface_name;
5004 const gchar *member;
5005 const gchar *signature;
5007 gchar *subtree_path;
5010 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5012 interface_name = g_dbus_message_get_interface (message);
5013 member = g_dbus_message_get_member (message);
5014 signature = g_dbus_message_get_signature (message);
5015 path = g_dbus_message_get_path (message);
5016 subtree_path = g_strdup (path);
5017 needle = strrchr (subtree_path, '/');
5018 if (needle != NULL && needle != subtree_path)
5024 g_free (subtree_path);
5025 subtree_path = NULL;
5029 g_debug ("interface = `%s'", interface_name);
5030 g_debug ("member = `%s'", member);
5031 g_debug ("signature = `%s'", signature);
5032 g_debug ("path = `%s'", path);
5033 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5036 object_path = g_dbus_message_get_path (message);
5037 g_assert (object_path != NULL);
5039 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5042 if (obj_message_func (connection, eo, message))
5046 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5049 if (subtree_message_func (connection, es, message))
5053 if (subtree_path != NULL)
5055 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5058 if (subtree_message_func (connection, es, message))
5063 if (handle_generic_unlocked (connection, message))
5066 /* if we end up here, the message has not been not handled */
5069 g_free (subtree_path);
5072 /* ---------------------------------------------------------------------------------------------------- */
5074 static GDBusConnection **
5075 message_bus_get_singleton (GBusType bus_type,
5078 GDBusConnection **ret;
5079 const gchar *starter_bus;
5085 case G_BUS_TYPE_SESSION:
5086 ret = &the_session_bus;
5089 case G_BUS_TYPE_SYSTEM:
5090 ret = &the_system_bus;
5093 case G_BUS_TYPE_STARTER:
5094 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5095 if (g_strcmp0 (starter_bus, "session") == 0)
5097 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5100 else if (g_strcmp0 (starter_bus, "system") == 0)
5102 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5107 if (starter_bus != NULL)
5111 G_IO_ERROR_INVALID_ARGUMENT,
5112 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5113 " - unknown value `%s'"),
5118 g_set_error_literal (error,
5120 G_IO_ERROR_INVALID_ARGUMENT,
5121 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5122 "variable is not set"));
5128 g_assert_not_reached ();
5136 static GDBusConnection *
5137 get_uninitialized_connection (GBusType bus_type,
5138 GCancellable *cancellable,
5141 GDBusConnection **singleton;
5142 GDBusConnection *ret;
5146 G_LOCK (message_bus_lock);
5147 singleton = message_bus_get_singleton (bus_type, error);
5148 if (singleton == NULL)
5151 if (*singleton == NULL)
5154 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5155 if (address == NULL)
5157 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5159 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5160 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5161 "exit-on-close", TRUE,
5166 ret = g_object_ref (*singleton);
5169 g_assert (ret != NULL);
5172 G_UNLOCK (message_bus_lock);
5178 * @bus_type: A #GBusType.
5179 * @cancellable: A #GCancellable or %NULL.
5180 * @error: Return location for error or %NULL.
5182 * Synchronously connects to the message bus specified by @bus_type.
5183 * Note that the returned object may shared with other callers,
5184 * e.g. if two separate parts of a process calls this function with
5185 * the same @bus_type, they will share the same object.
5187 * This is a synchronous failable function. See g_bus_get() and
5188 * g_bus_get_finish() for the asynchronous version.
5190 * The returned object is a singleton, that is, shared with other
5191 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5192 * event that you need a private message bus connection, use
5193 * g_dbus_address_get_for_bus() and
5194 * g_dbus_connection_new_for_address().
5196 * Note that the returned #GDBusConnection object will (usually) have
5197 * the #GDBusConnection:exit-on-close property set to %TRUE.
5199 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5204 g_bus_get_sync (GBusType bus_type,
5205 GCancellable *cancellable,
5208 GDBusConnection *connection;
5210 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5212 connection = get_uninitialized_connection (bus_type, cancellable, error);
5213 if (connection == NULL)
5216 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5218 g_object_unref (connection);
5227 bus_get_async_initable_cb (GObject *source_object,
5231 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5235 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5239 g_assert (error != NULL);
5240 g_simple_async_result_set_from_error (simple, error);
5241 g_error_free (error);
5242 g_object_unref (source_object);
5246 g_simple_async_result_set_op_res_gpointer (simple,
5250 g_simple_async_result_complete_in_idle (simple);
5251 g_object_unref (simple);
5256 * @bus_type: A #GBusType.
5257 * @cancellable: A #GCancellable or %NULL.
5258 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5259 * @user_data: The data to pass to @callback.
5261 * Asynchronously connects to the message bus specified by @bus_type.
5263 * When the operation is finished, @callback will be invoked. You can
5264 * then call g_bus_get_finish() to get the result of the operation.
5266 * This is a asynchronous failable function. See g_bus_get_sync() for
5267 * the synchronous version.
5272 g_bus_get (GBusType bus_type,
5273 GCancellable *cancellable,
5274 GAsyncReadyCallback callback,
5277 GDBusConnection *connection;
5278 GSimpleAsyncResult *simple;
5281 simple = g_simple_async_result_new (NULL,
5287 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5288 if (connection == NULL)
5290 g_assert (error != NULL);
5291 g_simple_async_result_set_from_error (simple, error);
5292 g_error_free (error);
5293 g_simple_async_result_complete_in_idle (simple);
5294 g_object_unref (simple);
5298 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5301 bus_get_async_initable_cb,
5308 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5309 * @error: Return location for error or %NULL.
5311 * Finishes an operation started with g_bus_get().
5313 * The returned object is a singleton, that is, shared with other
5314 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5315 * event that you need a private message bus connection, use
5316 * g_dbus_address_get_for_bus() and
5317 * g_dbus_connection_new_for_address().
5319 * Note that the returned #GDBusConnection object will (usually) have
5320 * the #GDBusConnection:exit-on-close property set to %TRUE.
5322 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5327 g_bus_get_finish (GAsyncResult *res,
5330 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5332 GDBusConnection *ret;
5334 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5336 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5340 if (g_simple_async_result_propagate_error (simple, error))
5343 object = g_simple_async_result_get_op_res_gpointer (simple);
5344 g_assert (object != NULL);
5345 ret = g_object_ref (G_DBUS_CONNECTION (object));
5351 /* ---------------------------------------------------------------------------------------------------- */
5353 #define __G_DBUS_CONNECTION_C__
5354 #include "gioaliasdef.c"