1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2009 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 expose an extension point for resolving D-Bus address and
29 * turning them into GIOStream objects. This will allow us to implement
30 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
32 * - see g_dbus_address_connect() in gdbusaddress.c
34 * - would be cute to use kernel-specific APIs to resolve fds for
35 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
37 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
39 * maybe we can show more information about what fd 21 really is.
40 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
41 * Initial experiments on Linux 2.6 suggests that the symlink looks
46 * e.g. not of much use.
54 #include "gdbusauth.h"
55 #include "gdbusutils.h"
56 #include "gdbusaddress.h"
57 #include "gdbusmessage.h"
58 #include "gdbusconnection.h"
59 #include "gdbuserror.h"
60 #include "gioenumtypes.h"
61 #include "gdbusintrospection.h"
62 #include "gdbusmethodinvocation.h"
63 #include "gdbusprivate.h"
64 #include "gdbusauthobserver.h"
65 #include "gio-marshal.h"
66 #include "ginitable.h"
67 #include "gasyncinitable.h"
68 #include "giostream.h"
69 #include "gasyncresult.h"
70 #include "gsimpleasyncresult.h"
73 #include <gio/gunixconnection.h>
74 #include <gio/gunixfdmessage.h>
76 #include <sys/types.h>
82 * SECTION:gdbusconnection
83 * @short_description: D-Bus Connections
87 * This class is rarely used directly in D-Bus clients. If you are
88 * writing an D-Bus client, it is often easier to use the
89 * g_bus_own_name(), g_bus_watch_name() or g_bus_watch_proxy() APIs.
92 * The #GDBusConnection type is used for D-Bus connections to remote
93 * peers such as a message buses.
95 * <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>
97 * <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>
99 * <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>
102 /* ---------------------------------------------------------------------------------------------------- */
104 G_LOCK_DEFINE_STATIC (message_bus_lock);
106 static GDBusConnection *the_session_bus = NULL;
107 static GDBusConnection *the_system_bus = NULL;
109 /* ---------------------------------------------------------------------------------------------------- */
112 _g_strv_has_string (const gchar* const * haystack,
117 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
119 if (g_strcmp0 (haystack[n], needle) == 0)
125 /* ---------------------------------------------------------------------------------------------------- */
128 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
130 // TODO: for some reason this doesn't work on Windows
131 #define CONNECTION_ENSURE_LOCK(obj) do { \
132 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
134 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
135 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
140 #define CONNECTION_LOCK(obj) do { \
141 g_mutex_lock ((obj)->priv->lock); \
144 #define CONNECTION_UNLOCK(obj) do { \
145 g_mutex_unlock ((obj)->priv->lock); \
148 struct _GDBusConnectionPrivate
150 /* ------------------------------------------------------------------------ */
151 /* -- General object state ------------------------------------------------ */
152 /* ------------------------------------------------------------------------ */
154 /* object-wide lock */
157 /* A lock used in the init() method of the GInitable interface - see comments
158 * in initable_init() for why a separate lock is needed
162 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
163 * someone calls org.freedesktop.DBus.GetMachineId()
167 /* The underlying stream used for communication */
170 /* The object used for authentication (if any) */
173 /* Set to TRUE if the connection has been closed */
176 /* Last serial used */
179 /* The object used to send/receive message */
182 /* If connected to a message bus, this contains the unique name assigned to
183 * us by the bus (e.g. ":1.42")
185 gchar *bus_unique_name;
187 /* The GUID returned by the other side if we authenticed as a client or
188 * the GUID to use if authenticating as a server
192 /* set to TRUE exactly when initable_init() has finished running */
193 gboolean is_initialized;
195 /* If the connection could not be established during initable_init(), this GError will set */
196 GError *initialization_error;
198 /* The result of g_main_context_get_thread_default() when the object
199 * was created (the GObject _init() function) - this is used for delivery
200 * of the :closed GObject signal.
202 GMainContext *main_context_at_construction;
204 /* construct properties */
206 GDBusConnectionFlags flags;
208 /* Map used for managing method replies */
209 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
211 /* Maps used for managing signal subscription */
212 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
213 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
214 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
216 /* Maps used for managing exported objects and subtrees */
217 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
218 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
219 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
220 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
222 /* Structure used for message filters */
225 /* Whether to exit on close */
226 gboolean exit_on_close;
228 /* Capabilities negotiated during authentication */
229 GDBusCapabilityFlags capabilities;
231 GDBusAuthObserver *authentication_observer;
232 GCredentials *crendentials;
235 typedef struct ExportedObject ExportedObject;
236 static void exported_object_free (ExportedObject *eo);
238 typedef struct ExportedSubtree ExportedSubtree;
239 static void exported_subtree_free (ExportedSubtree *es);
257 PROP_CAPABILITY_FLAGS,
258 PROP_AUTHENTICATION_OBSERVER,
261 static void distribute_signals (GDBusConnection *connection,
262 GDBusMessage *message);
264 static void distribute_method_call (GDBusConnection *connection,
265 GDBusMessage *message);
267 static gboolean handle_generic_unlocked (GDBusConnection *connection,
268 GDBusMessage *message);
271 static void purge_all_signal_subscriptions (GDBusConnection *connection);
272 static void purge_all_filters (GDBusConnection *connection);
274 #define _G_ENSURE_LOCK(name) do { \
275 if (G_UNLIKELY (G_TRYLOCK(name))) \
277 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
278 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
282 static guint signals[LAST_SIGNAL] = { 0 };
284 static void initable_iface_init (GInitableIface *initable_iface);
285 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
287 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
288 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
289 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
293 g_dbus_connection_dispose (GObject *object)
295 GDBusConnection *connection = G_DBUS_CONNECTION (object);
297 G_LOCK (message_bus_lock);
298 //g_debug ("disposing %p", connection);
299 if (connection == the_session_bus)
301 the_session_bus = NULL;
303 else if (connection == the_system_bus)
305 the_system_bus = NULL;
307 if (connection->priv->worker != NULL)
309 _g_dbus_worker_stop (connection->priv->worker);
310 connection->priv->worker = NULL;
312 G_UNLOCK (message_bus_lock);
314 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
315 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
319 g_dbus_connection_finalize (GObject *object)
321 GDBusConnection *connection = G_DBUS_CONNECTION (object);
323 if (connection->priv->authentication_observer != NULL)
324 g_object_unref (connection->priv->authentication_observer);
326 if (connection->priv->auth != NULL)
327 g_object_unref (connection->priv->auth);
329 //g_debug ("finalizing %p", connection);
330 if (connection->priv->stream != NULL)
332 /* We don't really care if closing the stream succeeds or not */
333 g_io_stream_close_async (connection->priv->stream,
335 NULL, /* GCancellable */
336 NULL, /* GAsyncReadyCallback */
337 NULL); /* userdata */
338 g_object_unref (connection->priv->stream);
339 connection->priv->stream = NULL;
342 g_free (connection->priv->address);
344 g_free (connection->priv->guid);
345 g_free (connection->priv->bus_unique_name);
347 if (connection->priv->initialization_error != NULL)
348 g_error_free (connection->priv->initialization_error);
350 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
352 purge_all_signal_subscriptions (connection);
353 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
354 g_hash_table_unref (connection->priv->map_id_to_signal_data);
355 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
357 g_hash_table_unref (connection->priv->map_id_to_ei);
358 g_hash_table_unref (connection->priv->map_object_path_to_eo);
359 g_hash_table_unref (connection->priv->map_id_to_es);
360 g_hash_table_unref (connection->priv->map_object_path_to_es);
362 purge_all_filters (connection);
363 g_ptr_array_unref (connection->priv->filters);
365 if (connection->priv->main_context_at_construction != NULL)
366 g_main_context_unref (connection->priv->main_context_at_construction);
368 g_free (connection->priv->machine_id);
370 g_mutex_free (connection->priv->init_lock);
371 g_mutex_free (connection->priv->lock);
373 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize != NULL)
374 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
378 g_dbus_connection_get_property (GObject *object,
383 GDBusConnection *connection = G_DBUS_CONNECTION (object);
388 g_value_set_object (value, g_dbus_connection_get_stream (connection));
392 g_value_set_string (value, g_dbus_connection_get_guid (connection));
395 case PROP_UNIQUE_NAME:
396 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
400 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
403 case PROP_EXIT_ON_CLOSE:
404 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
407 case PROP_CAPABILITY_FLAGS:
408 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
412 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
418 g_dbus_connection_set_property (GObject *object,
423 GDBusConnection *connection = G_DBUS_CONNECTION (object);
428 connection->priv->stream = g_value_dup_object (value);
432 connection->priv->guid = g_value_dup_string (value);
436 connection->priv->address = g_value_dup_string (value);
440 connection->priv->flags = g_value_get_flags (value);
443 case PROP_EXIT_ON_CLOSE:
444 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
447 case PROP_AUTHENTICATION_OBSERVER:
448 connection->priv->authentication_observer = g_value_dup_object (value);
452 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
458 g_dbus_connection_real_closed (GDBusConnection *connection,
459 gboolean remote_peer_vanished,
462 if (remote_peer_vanished && connection->priv->exit_on_close)
464 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
470 g_dbus_connection_class_init (GDBusConnectionClass *klass)
472 GObjectClass *gobject_class;
474 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
476 gobject_class = G_OBJECT_CLASS (klass);
478 gobject_class->finalize = g_dbus_connection_finalize;
479 gobject_class->dispose = g_dbus_connection_dispose;
480 gobject_class->set_property = g_dbus_connection_set_property;
481 gobject_class->get_property = g_dbus_connection_get_property;
483 klass->closed = g_dbus_connection_real_closed;
486 * GDBusConnection:stream:
488 * The underlying #GIOStream used for I/O.
492 g_object_class_install_property (gobject_class,
494 g_param_spec_object ("stream",
496 _("The underlying streams used for I/O"),
500 G_PARAM_CONSTRUCT_ONLY |
501 G_PARAM_STATIC_NAME |
502 G_PARAM_STATIC_BLURB |
503 G_PARAM_STATIC_NICK));
506 * GDBusConnection:address:
508 * A D-Bus address specifying potential endpoints that can be used
509 * when establishing the connection.
513 g_object_class_install_property (gobject_class,
515 g_param_spec_string ("address",
517 _("D-Bus address specifying potential socket endpoints"),
520 G_PARAM_CONSTRUCT_ONLY |
521 G_PARAM_STATIC_NAME |
522 G_PARAM_STATIC_BLURB |
523 G_PARAM_STATIC_NICK));
526 * GDBusConnection:flags:
528 * Flags from the #GDBusConnectionFlags enumeration.
532 g_object_class_install_property (gobject_class,
534 g_param_spec_flags ("flags",
537 G_TYPE_DBUS_CONNECTION_FLAGS,
538 G_DBUS_CONNECTION_FLAGS_NONE,
540 G_PARAM_CONSTRUCT_ONLY |
541 G_PARAM_STATIC_NAME |
542 G_PARAM_STATIC_BLURB |
543 G_PARAM_STATIC_NICK));
546 * GDBusConnection:guid:
548 * The GUID of the peer performing the role of server when
551 * If you are constructing a #GDBusConnection and pass
552 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
553 * #GDBusConnection:flags property then you MUST also set this
554 * property to a valid guid.
556 * If you are constructing a #GDBusConnection and pass
557 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
558 * #GDBusConnection:flags property you will be able to read the GUID
559 * of the other peer here after the connection has been succesfully
564 g_object_class_install_property (gobject_class,
566 g_param_spec_string ("guid",
568 _("GUID of the server peer"),
572 G_PARAM_CONSTRUCT_ONLY |
573 G_PARAM_STATIC_NAME |
574 G_PARAM_STATIC_BLURB |
575 G_PARAM_STATIC_NICK));
578 * GDBusConnection:unique-name:
580 * The unique name as assigned by the message bus or %NULL if the
581 * connection is not open or not a message bus connection.
585 g_object_class_install_property (gobject_class,
587 g_param_spec_string ("unique-name",
589 _("Unique name of bus connection"),
592 G_PARAM_STATIC_NAME |
593 G_PARAM_STATIC_BLURB |
594 G_PARAM_STATIC_NICK));
597 * GDBusConnection:closed:
599 * A boolean specifying whether the connection has been closed.
603 g_object_class_install_property (gobject_class,
605 g_param_spec_boolean ("closed",
607 _("Whether the connection is closed"),
610 G_PARAM_STATIC_NAME |
611 G_PARAM_STATIC_BLURB |
612 G_PARAM_STATIC_NICK));
615 * GDBusConnection:exit-on-close:
617 * A boolean specifying whether the process will be terminated (by
618 * calling <literal>raise(SIGTERM)</literal>) if the connection
619 * is closed by the remote peer.
623 g_object_class_install_property (gobject_class,
625 g_param_spec_boolean ("exit-on-close",
627 _("Whether the process is terminated when the connection is closed"),
631 G_PARAM_STATIC_NAME |
632 G_PARAM_STATIC_BLURB |
633 G_PARAM_STATIC_NICK));
636 * GDBusConnection:capabilities:
638 * Flags from the #GDBusCapabilityFlags enumeration
639 * representing connection features negotiated with the other peer.
643 g_object_class_install_property (gobject_class,
644 PROP_CAPABILITY_FLAGS,
645 g_param_spec_flags ("capabilities",
648 G_TYPE_DBUS_CAPABILITY_FLAGS,
649 G_DBUS_CAPABILITY_FLAGS_NONE,
651 G_PARAM_STATIC_NAME |
652 G_PARAM_STATIC_BLURB |
653 G_PARAM_STATIC_NICK));
656 * GDBusConnection:authentication-observer:
658 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
662 g_object_class_install_property (gobject_class,
663 PROP_AUTHENTICATION_OBSERVER,
664 g_param_spec_object ("authentication-observer",
665 _("Authentication Observer"),
666 _("Object used to assist in the authentication process"),
667 G_TYPE_DBUS_AUTH_OBSERVER,
669 G_PARAM_CONSTRUCT_ONLY |
670 G_PARAM_STATIC_NAME |
671 G_PARAM_STATIC_BLURB |
672 G_PARAM_STATIC_NICK));
675 * GDBusConnection::closed:
676 * @connection: The #GDBusConnection emitting the signal.
677 * @remote_peer_vanished: %TRUE if @connection is closed because the
678 * remote peer closed its end of the connection.
679 * @error: A #GError with more details about the event or %NULL.
681 * Emitted when the connection is closed.
683 * The cause of this event can be
686 * If g_dbus_connection_close() is called. In this case
687 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
690 * If the remote peer closes the connection. In this case
691 * @remote_peer_vanished is set to %TRUE and @error is set.
694 * If the remote peer sends invalid or malformed data. In this
695 * case @remote_peer_vanished is set to %FALSE and @error
700 * Upon receiving this signal, you should give up your reference to
701 * @connection. You are guaranteed that this signal is emitted only
706 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
707 G_TYPE_DBUS_CONNECTION,
709 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
712 _gio_marshal_VOID__BOOLEAN_BOXED,
720 g_dbus_connection_init (GDBusConnection *connection)
722 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
724 connection->priv->lock = g_mutex_new ();
725 connection->priv->init_lock = g_mutex_new ();
727 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
729 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
731 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
733 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
738 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
741 (GDestroyNotify) exported_object_free);
743 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
746 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
749 (GDestroyNotify) exported_subtree_free);
751 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
754 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
755 if (connection->priv->main_context_at_construction != NULL)
756 g_main_context_ref (connection->priv->main_context_at_construction);
758 connection->priv->filters = g_ptr_array_new ();
762 g_dbus_connection_get_stream (GDBusConnection *connection)
764 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
765 return connection->priv->stream;
770 * g_dbus_connection_is_closed:
771 * @connection: A #GDBusConnection.
773 * Gets whether @connection is closed.
775 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
780 g_dbus_connection_is_closed (GDBusConnection *connection)
782 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
783 return connection->priv->closed;
787 * g_dbus_connection_get_capabilities:
788 * @connection: A #GDBusConnection.
790 * Gets the capabilities negotiated with the remote peer
792 * Returns: One or more flags from the #GDBusCapabilityFlags enumeration.
797 g_dbus_connection_get_capabilities (GDBusConnection *connection)
799 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
800 return connection->priv->capabilities;
804 /* ---------------------------------------------------------------------------------------------------- */
808 GDBusConnection *connection;
810 gboolean remote_peer_vanished;
814 emit_closed_data_free (EmitClosedData *data)
816 g_object_unref (data->connection);
817 if (data->error != NULL)
818 g_error_free (data->error);
823 emit_closed_in_idle (gpointer user_data)
825 EmitClosedData *data = user_data;
828 g_object_notify (G_OBJECT (data->connection), "closed");
829 g_signal_emit (data->connection,
830 signals[CLOSED_SIGNAL],
832 data->remote_peer_vanished,
838 /* Can be called from any thread, must hold lock */
840 set_closed_unlocked (GDBusConnection *connection,
841 gboolean remote_peer_vanished,
844 GSource *idle_source;
845 EmitClosedData *data;
847 CONNECTION_ENSURE_LOCK (connection);
849 g_assert (!connection->priv->closed);
851 connection->priv->closed = TRUE;
853 data = g_new0 (EmitClosedData, 1);
854 data->connection = g_object_ref (connection);
855 data->remote_peer_vanished = remote_peer_vanished;
856 data->error = error != NULL ? g_error_copy (error) : NULL;
858 idle_source = g_idle_source_new ();
859 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
860 g_source_set_callback (idle_source,
863 (GDestroyNotify) emit_closed_data_free);
864 g_source_attach (idle_source, connection->priv->main_context_at_construction);
865 g_source_unref (idle_source);
868 /* ---------------------------------------------------------------------------------------------------- */
871 * g_dbus_connection_close:
872 * @connection: A #GDBusConnection.
874 * Closes @connection. Note that this never causes the process to
875 * exit (this might only happen if the other end of a shared message
876 * bus connection disconnects).
878 * If @connection is already closed, this method does nothing.
883 g_dbus_connection_close (GDBusConnection *connection)
885 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
887 CONNECTION_LOCK (connection);
888 if (!connection->priv->closed)
890 GError *error = NULL;
892 /* TODO: do this async */
893 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
894 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
896 g_warning ("Error closing stream: %s", error->message);
897 g_error_free (error);
900 set_closed_unlocked (connection, FALSE, NULL);
902 CONNECTION_UNLOCK (connection);
905 /* ---------------------------------------------------------------------------------------------------- */
908 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
909 GDBusMessage *message,
910 volatile guint32 *out_serial,
915 guint32 serial_to_use;
918 CONNECTION_ENSURE_LOCK (connection);
920 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
921 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
923 /* TODO: check all necessary headers are present */
928 if (out_serial != NULL)
931 if (connection->priv->closed)
933 g_set_error_literal (error,
936 _("The connection is closed"));
940 blob = g_dbus_message_to_blob (message,
946 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
951 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
954 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
957 g_assert_not_reached ();
962 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
963 blob_size, serial_to_use, connection);
964 g_printerr ("----\n");
965 hexdump (blob, blob_size);
966 g_printerr ("----\n");
969 /* TODO: use connection->priv->auth to encode the blob */
971 if (out_serial != NULL)
973 *out_serial = serial_to_use;
975 g_dbus_message_set_serial (message, serial_to_use);
977 _g_dbus_worker_send_message (connection->priv->worker,
981 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
992 * g_dbus_connection_send_message:
993 * @connection: A #GDBusConnection.
994 * @message: A #GDBusMessage
995 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
996 * @error: Return location for error or %NULL.
998 * Asynchronously sends @message to the peer represented by @connection.
1000 * If @out_serial is not %NULL, then the serial number assigned to
1001 * @message by @connection will be written to this location prior to
1002 * submitting the message to the underlying transport.
1004 * If @connection is closed then the operation will fail with
1005 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1006 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1007 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1009 * See <xref linkend="gdbus-server"/> and <xref
1010 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1011 * low-level API to send and receive UNIX file descriptors.
1013 * Returns: %TRUE if the message was well-formed and queued for
1014 * transmission, %FALSE if @error is set.
1019 g_dbus_connection_send_message (GDBusConnection *connection,
1020 GDBusMessage *message,
1021 volatile guint32 *out_serial,
1026 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1027 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1028 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1030 CONNECTION_LOCK (connection);
1031 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1032 CONNECTION_UNLOCK (connection);
1036 /* ---------------------------------------------------------------------------------------------------- */
1040 volatile gint ref_count;
1041 GDBusConnection *connection;
1043 GSimpleAsyncResult *simple;
1045 GMainContext *main_context;
1047 GCancellable *cancellable;
1049 gulong cancellable_handler_id;
1051 GSource *timeout_source;
1056 static SendMessageData *
1057 send_message_data_ref (SendMessageData *data)
1059 g_atomic_int_inc (&data->ref_count);
1064 send_message_data_unref (SendMessageData *data)
1066 if (g_atomic_int_dec_and_test (&data->ref_count))
1068 g_assert (data->timeout_source == NULL);
1069 g_assert (data->simple == NULL);
1070 g_assert (data->cancellable_handler_id == 0);
1071 g_object_unref (data->connection);
1072 if (data->cancellable != NULL)
1073 g_object_unref (data->cancellable);
1074 if (data->main_context != NULL)
1075 g_main_context_unref (data->main_context);
1080 /* ---------------------------------------------------------------------------------------------------- */
1082 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1084 send_message_with_reply_deliver (SendMessageData *data)
1086 CONNECTION_ENSURE_LOCK (data->connection);
1088 g_assert (!data->delivered);
1090 data->delivered = TRUE;
1092 g_simple_async_result_complete_in_idle (data->simple);
1093 g_object_unref (data->simple);
1094 data->simple = NULL;
1096 if (data->timeout_source != NULL)
1098 g_source_destroy (data->timeout_source);
1099 data->timeout_source = NULL;
1101 if (data->cancellable_handler_id > 0)
1103 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1104 data->cancellable_handler_id = 0;
1107 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1108 GUINT_TO_POINTER (data->serial)));
1110 send_message_data_unref (data);
1113 /* ---------------------------------------------------------------------------------------------------- */
1115 /* must hold lock */
1117 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1118 GDBusMessage *reply)
1120 if (data->delivered)
1123 g_simple_async_result_set_op_res_gpointer (data->simple,
1124 g_object_ref (reply),
1127 send_message_with_reply_deliver (data);
1133 /* ---------------------------------------------------------------------------------------------------- */
1136 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1138 SendMessageData *data = user_data;
1140 CONNECTION_LOCK (data->connection);
1141 if (data->delivered)
1144 g_simple_async_result_set_error (data->simple,
1146 G_IO_ERROR_CANCELLED,
1147 _("Operation was cancelled"));
1149 send_message_with_reply_deliver (data);
1152 CONNECTION_UNLOCK (data->connection);
1156 /* Can be called from any thread with or without lock held */
1158 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1161 SendMessageData *data = user_data;
1162 GSource *idle_source;
1164 /* postpone cancellation to idle handler since we may be called directly
1165 * via g_cancellable_connect() (e.g. holding lock)
1167 idle_source = g_idle_source_new ();
1168 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1169 g_source_set_callback (idle_source,
1170 send_message_with_reply_cancelled_idle_cb,
1171 send_message_data_ref (data),
1172 (GDestroyNotify) send_message_data_unref);
1173 g_source_attach (idle_source, data->main_context);
1174 g_source_unref (idle_source);
1177 /* ---------------------------------------------------------------------------------------------------- */
1180 send_message_with_reply_timeout_cb (gpointer user_data)
1182 SendMessageData *data = user_data;
1184 CONNECTION_LOCK (data->connection);
1185 if (data->delivered)
1188 g_simple_async_result_set_error (data->simple,
1190 G_IO_ERROR_TIMED_OUT,
1191 _("Timeout was reached"));
1193 send_message_with_reply_deliver (data);
1196 CONNECTION_UNLOCK (data->connection);
1201 /* ---------------------------------------------------------------------------------------------------- */
1204 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1205 GDBusMessage *message,
1207 volatile guint32 *out_serial,
1208 GCancellable *cancellable,
1209 GAsyncReadyCallback callback,
1212 GSimpleAsyncResult *simple;
1213 SendMessageData *data;
1215 volatile guint32 serial;
1219 if (out_serial == NULL)
1220 out_serial = &serial;
1222 if (timeout_msec == -1)
1223 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1225 simple = g_simple_async_result_new (G_OBJECT (connection),
1228 g_dbus_connection_send_message_with_reply);
1230 if (g_cancellable_is_cancelled (cancellable))
1232 g_simple_async_result_set_error (simple,
1234 G_IO_ERROR_CANCELLED,
1235 _("Operation was cancelled"));
1236 g_simple_async_result_complete_in_idle (simple);
1237 g_object_unref (simple);
1241 if (connection->priv->closed)
1243 g_simple_async_result_set_error (simple,
1246 _("The connection is closed"));
1247 g_simple_async_result_complete_in_idle (simple);
1248 g_object_unref (simple);
1253 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1255 g_simple_async_result_set_from_error (simple, error);
1256 g_simple_async_result_complete_in_idle (simple);
1257 g_object_unref (simple);
1261 data = g_new0 (SendMessageData, 1);
1262 data->ref_count = 1;
1263 data->connection = g_object_ref (connection);
1264 data->simple = simple;
1265 data->serial = *out_serial;
1266 data->main_context = g_main_context_get_thread_default ();
1267 if (data->main_context != NULL)
1268 g_main_context_ref (data->main_context);
1270 if (cancellable != NULL)
1272 data->cancellable = g_object_ref (cancellable);
1273 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1274 G_CALLBACK (send_message_with_reply_cancelled_cb),
1275 send_message_data_ref (data),
1276 (GDestroyNotify) send_message_data_unref);
1277 g_object_set_data_full (G_OBJECT (simple),
1279 g_object_ref (cancellable),
1280 (GDestroyNotify) g_object_unref);
1283 data->timeout_source = g_timeout_source_new (timeout_msec);
1284 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1285 g_source_set_callback (data->timeout_source,
1286 send_message_with_reply_timeout_cb,
1287 send_message_data_ref (data),
1288 (GDestroyNotify) send_message_data_unref);
1289 g_source_attach (data->timeout_source, data->main_context);
1290 g_source_unref (data->timeout_source);
1292 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1293 GUINT_TO_POINTER (*out_serial),
1301 * g_dbus_connection_send_message_with_reply:
1302 * @connection: A #GDBusConnection.
1303 * @message: A #GDBusMessage.
1304 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1305 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1306 * @cancellable: A #GCancellable or %NULL.
1307 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1308 * care about the result.
1309 * @user_data: The data to pass to @callback.
1311 * Asynchronously sends @message to the peer represented by @connection.
1313 * If @out_serial is not %NULL, then the serial number assigned to
1314 * @message by @connection will be written to this location prior to
1315 * submitting the message to the underlying transport.
1317 * If @connection is closed then the operation will fail with
1318 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1319 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1320 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1322 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1323 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1324 * of the thread you are calling this method from. You can then call
1325 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1326 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1328 * See <xref linkend="gdbus-server"/> and <xref
1329 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1330 * low-level API to send and receive UNIX file descriptors.
1335 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1336 GDBusMessage *message,
1338 volatile guint32 *out_serial,
1339 GCancellable *cancellable,
1340 GAsyncReadyCallback callback,
1343 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1344 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1345 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1347 CONNECTION_LOCK (connection);
1348 g_dbus_connection_send_message_with_reply_unlocked (connection,
1355 CONNECTION_UNLOCK (connection);
1359 * g_dbus_connection_send_message_with_reply_finish:
1360 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1361 * @error: Return location for error or %NULL.
1363 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1365 * Note that @error is only set if a local in-process error
1366 * occured. That is to say that the returned #GDBusMessage object may
1367 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1368 * g_dbus_message_to_gerror() to transcode this to a #GError.
1370 * See <xref linkend="gdbus-server"/> and <xref
1371 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1372 * low-level API to send and receive UNIX file descriptors.
1374 * Returns: A #GDBusMessage or %NULL if @error is set.
1379 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1383 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1384 GDBusMessage *reply;
1385 GCancellable *cancellable;
1387 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1388 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1392 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1394 if (g_simple_async_result_propagate_error (simple, error))
1397 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1398 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1399 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1401 g_object_unref (reply);
1403 g_set_error_literal (error,
1405 G_IO_ERROR_CANCELLED,
1406 _("Operation was cancelled"));
1412 /* ---------------------------------------------------------------------------------------------------- */
1417 GMainContext *context;
1419 } SendMessageSyncData;
1422 send_message_with_reply_sync_cb (GDBusConnection *connection,
1426 SendMessageSyncData *data = user_data;
1427 data->res = g_object_ref (res);
1428 g_main_loop_quit (data->loop);
1432 * g_dbus_connection_send_message_with_reply_sync:
1433 * @connection: A #GDBusConnection.
1434 * @message: A #GDBusMessage.
1435 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1436 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1437 * @cancellable: A #GCancellable or %NULL.
1438 * @error: Return location for error or %NULL.
1440 * Synchronously sends @message to the peer represented by @connection
1441 * and blocks the calling thread until a reply is received or the
1442 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1443 * for the asynchronous version of this method.
1445 * If @out_serial is not %NULL, then the serial number assigned to
1446 * @message by @connection will be written to this location prior to
1447 * submitting the message to the underlying transport.
1449 * If @connection is closed then the operation will fail with
1450 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1451 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1452 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1454 * Note that @error is only set if a local in-process error
1455 * occured. That is to say that the returned #GDBusMessage object may
1456 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1457 * g_dbus_message_to_gerror() to transcode this to a #GError.
1459 * See <xref linkend="gdbus-server"/> and <xref
1460 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1461 * low-level API to send and receive UNIX file descriptors.
1463 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1468 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1469 GDBusMessage *message,
1471 volatile guint32 *out_serial,
1472 GCancellable *cancellable,
1475 SendMessageSyncData *data;
1476 GDBusMessage *reply;
1478 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1479 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1480 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1481 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1483 data = g_new0 (SendMessageSyncData, 1);
1484 data->context = g_main_context_new ();
1485 data->loop = g_main_loop_new (data->context, FALSE);
1487 g_main_context_push_thread_default (data->context);
1489 g_dbus_connection_send_message_with_reply (connection,
1494 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1496 g_main_loop_run (data->loop);
1497 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1501 g_main_context_pop_thread_default (data->context);
1503 g_main_context_unref (data->context);
1504 g_main_loop_unref (data->loop);
1505 g_object_unref (data->res);
1511 /* ---------------------------------------------------------------------------------------------------- */
1515 GDBusMessageFilterFunction func;
1522 GDBusMessageFilterFunction filter_function;
1524 GDestroyNotify user_data_free_func;
1527 /* Called in worker's thread - we must not block */
1529 on_worker_message_received (GDBusWorker *worker,
1530 GDBusMessage *message,
1533 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1534 FilterCallback *filters;
1535 gboolean consumed_by_filter;
1539 //g_debug ("in on_worker_message_received");
1541 g_object_ref (connection);
1543 /* First collect the set of callback functions */
1544 CONNECTION_LOCK (connection);
1545 num_filters = connection->priv->filters->len;
1546 filters = g_new0 (FilterCallback, num_filters);
1547 for (n = 0; n < num_filters; n++)
1549 FilterData *data = connection->priv->filters->pdata[n];
1550 filters[n].func = data->filter_function;
1551 filters[n].user_data = data->user_data;
1553 CONNECTION_UNLOCK (connection);
1555 /* the call the filters in order (without holding the lock) */
1556 consumed_by_filter = FALSE;
1557 for (n = 0; n < num_filters; n++)
1559 consumed_by_filter = filters[n].func (connection,
1561 filters[n].user_data);
1562 if (consumed_by_filter)
1566 /* Standard dispatch unless the filter ate the message */
1567 if (!consumed_by_filter)
1569 GDBusMessageType message_type;
1571 message_type = g_dbus_message_get_type (message);
1572 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1574 guint32 reply_serial;
1575 SendMessageData *send_message_data;
1577 reply_serial = g_dbus_message_get_reply_serial (message);
1578 CONNECTION_LOCK (connection);
1579 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1580 GUINT_TO_POINTER (reply_serial));
1581 if (send_message_data != NULL)
1583 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1584 send_message_data_deliver_reply_unlocked (send_message_data, message);
1588 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1590 CONNECTION_UNLOCK (connection);
1592 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1594 CONNECTION_LOCK (connection);
1595 distribute_signals (connection, message);
1596 CONNECTION_UNLOCK (connection);
1598 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1600 CONNECTION_LOCK (connection);
1601 distribute_method_call (connection, message);
1602 CONNECTION_UNLOCK (connection);
1606 g_object_unref (connection);
1610 /* Called in worker's thread - we must not block */
1612 on_worker_closed (GDBusWorker *worker,
1613 gboolean remote_peer_vanished,
1617 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1619 //g_debug ("in on_worker_closed: %s", error->message);
1621 CONNECTION_LOCK (connection);
1622 if (!connection->priv->closed)
1623 set_closed_unlocked (connection, remote_peer_vanished, error);
1624 CONNECTION_UNLOCK (connection);
1627 /* ---------------------------------------------------------------------------------------------------- */
1629 /* Determines the biggest set of capabilities we can support on this connection */
1630 static GDBusCapabilityFlags
1631 get_offered_capabilities_max (GDBusConnection *connection)
1633 GDBusCapabilityFlags ret;
1634 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1636 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1638 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1646 initable_init (GInitable *initable,
1647 GCancellable *cancellable,
1650 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1653 /* This method needs to be idempotent to work with the singleton
1654 * pattern. See the docs for g_initable_init(). We implement this by
1657 * Unfortunately we can't use the main lock since the on_worker_*()
1658 * callbacks above needs the lock during initialization (for message
1659 * bus connections we do a synchronous Hello() call on the bus).
1661 g_mutex_lock (connection->priv->init_lock);
1665 if (connection->priv->is_initialized)
1667 if (connection->priv->stream != NULL)
1670 g_assert (connection->priv->initialization_error != NULL);
1673 g_assert (connection->priv->initialization_error == NULL);
1675 /* The user can pass multiple (but mutally exclusive) construct
1678 * - stream (of type GIOStream)
1679 * - address (of type gchar*)
1681 * At the end of the day we end up with a non-NULL GIOStream
1682 * object in connection->priv->stream.
1684 if (connection->priv->address != NULL)
1686 g_assert (connection->priv->stream == NULL);
1688 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1689 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1691 g_set_error_literal (error,
1693 G_IO_ERROR_INVALID_ARGUMENT,
1694 _("Unsupported flags encountered when constructing a client-side connection"));
1698 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1699 NULL, /* TODO: out_guid */
1701 &connection->priv->initialization_error);
1702 if (connection->priv->stream == NULL)
1705 else if (connection->priv->stream != NULL)
1711 g_assert_not_reached ();
1714 /* Authenticate the connection */
1715 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1717 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1718 g_assert (connection->priv->guid != NULL);
1719 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1720 if (!_g_dbus_auth_run_server (connection->priv->auth,
1721 connection->priv->authentication_observer,
1722 connection->priv->guid,
1723 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1724 get_offered_capabilities_max (connection),
1725 &connection->priv->capabilities,
1726 &connection->priv->crendentials,
1728 &connection->priv->initialization_error))
1731 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1733 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1734 g_assert (connection->priv->guid == NULL);
1735 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1736 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1737 get_offered_capabilities_max (connection),
1738 &connection->priv->capabilities,
1740 &connection->priv->initialization_error);
1741 if (connection->priv->guid == NULL)
1745 if (connection->priv->authentication_observer != NULL)
1747 g_object_unref (connection->priv->authentication_observer);
1748 connection->priv->authentication_observer = NULL;
1751 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1753 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1757 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1761 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1763 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1766 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1767 connection->priv->capabilities,
1768 on_worker_message_received,
1772 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1773 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1775 GVariant *hello_result;
1778 hello_result = g_dbus_connection_invoke_method_sync (connection,
1779 "org.freedesktop.DBus", /* name */
1780 "/org/freedesktop/DBus", /* path */
1781 "org.freedesktop.DBus", /* interface */
1783 NULL, /* parameters */
1784 G_DBUS_INVOKE_METHOD_FLAGS_NONE,
1786 NULL, /* TODO: cancellable */
1787 &connection->priv->initialization_error);
1788 if (hello_result == NULL)
1791 g_variant_get (hello_result, "(s)", &s);
1792 connection->priv->bus_unique_name = g_strdup (s);
1793 g_variant_unref (hello_result);
1794 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1797 connection->priv->is_initialized = TRUE;
1803 g_assert (connection->priv->initialization_error != NULL);
1804 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1807 g_mutex_unlock (connection->priv->init_lock);
1813 initable_iface_init (GInitableIface *initable_iface)
1815 initable_iface->init = initable_init;
1818 /* ---------------------------------------------------------------------------------------------------- */
1821 async_init_thread (GSimpleAsyncResult *res,
1823 GCancellable *cancellable)
1825 GError *error = NULL;
1827 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1829 g_simple_async_result_set_from_error (res, error);
1830 g_error_free (error);
1835 async_initable_init_async (GAsyncInitable *initable,
1837 GCancellable *cancellable,
1838 GAsyncReadyCallback callback,
1841 GSimpleAsyncResult *res;
1843 g_return_if_fail (G_IS_INITABLE (initable));
1845 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1846 async_initable_init_async);
1847 g_simple_async_result_run_in_thread (res, async_init_thread,
1848 io_priority, cancellable);
1849 g_object_unref (res);
1853 async_initable_init_finish (GAsyncInitable *initable,
1857 return TRUE; /* Errors handled by base impl */
1861 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1863 /* We basically just want to use GIO's default implementation - though that one is
1864 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1866 async_initable_iface->init_async = async_initable_init_async;
1867 async_initable_iface->init_finish = async_initable_init_finish;
1870 /* ---------------------------------------------------------------------------------------------------- */
1873 * g_dbus_connection_new:
1874 * @stream: A #GIOStream.
1875 * @guid: The GUID to use if a authenticating as a server or %NULL.
1876 * @flags: Flags describing how to make the connection.
1877 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1878 * @cancellable: A #GCancellable or %NULL.
1879 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1880 * @user_data: The data to pass to @callback.
1882 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1883 * with the end represented by @stream.
1885 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1886 * @auth_observer (if not %NULL) is used to assist in the client
1887 * authentication process.
1889 * When the operation is finished, @callback will be invoked. You can
1890 * then call g_dbus_connection_new_finish() to get the result of the
1893 * This is a asynchronous failable constructor. See
1894 * g_dbus_connection_new_sync() for the synchronous
1900 g_dbus_connection_new (GIOStream *stream,
1902 GDBusConnectionFlags flags,
1903 GDBusAuthObserver *authentication_observer,
1904 GCancellable *cancellable,
1905 GAsyncReadyCallback callback,
1908 g_return_if_fail (G_IS_IO_STREAM (stream));
1909 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1917 "authentication-observer", authentication_observer,
1922 * g_dbus_connection_new_finish:
1923 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1924 * @error: Return location for error or %NULL.
1926 * Finishes an operation started with g_dbus_connection_new().
1928 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1933 g_dbus_connection_new_finish (GAsyncResult *res,
1937 GObject *source_object;
1939 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1940 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1942 source_object = g_async_result_get_source_object (res);
1943 g_assert (source_object != NULL);
1944 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1947 g_object_unref (source_object);
1949 return G_DBUS_CONNECTION (object);
1955 * g_dbus_connection_new_sync:
1956 * @stream: A #GIOStream.
1957 * @guid: The GUID to use if a authenticating as a server or %NULL.
1958 * @flags: Flags describing how to make the connection.
1959 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1960 * @cancellable: A #GCancellable or %NULL.
1961 * @error: Return location for error or %NULL.
1963 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1964 * with the end represented by @stream.
1966 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1967 * @auth_observer (if not %NULL) is used to assist in the client
1968 * authentication process.
1970 * This is a synchronous failable constructor. See
1971 * g_dbus_connection_new() for the asynchronous version.
1973 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1978 g_dbus_connection_new_sync (GIOStream *stream,
1980 GDBusConnectionFlags flags,
1981 GDBusAuthObserver *authentication_observer,
1982 GCancellable *cancellable,
1985 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1986 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1987 return g_initable_new (G_TYPE_DBUS_CONNECTION,
1993 "authentication-observer", authentication_observer,
1997 /* ---------------------------------------------------------------------------------------------------- */
2000 * g_dbus_connection_new_for_address:
2001 * @address: A D-Bus address.
2002 * @flags: Flags describing how to make the connection.
2003 * @cancellable: A #GCancellable or %NULL.
2004 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2005 * @user_data: The data to pass to @callback.
2007 * Asynchronously connects and sets up a D-Bus client connection for
2008 * exchanging D-Bus messages with an endpoint specified by @address
2009 * which must be in the D-Bus address format.
2011 * This constructor can only be used to initiate client-side
2012 * connections - use g_dbus_connection_new() if you need to act as the
2013 * server. In particular, @flags cannot contain the
2014 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2015 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2017 * When the operation is finished, @callback will be invoked. You can
2018 * then call g_dbus_connection_new_finish() to get the result of the
2021 * This is a asynchronous failable constructor. See
2022 * g_dbus_connection_new_for_address_sync() for the synchronous
2028 g_dbus_connection_new_for_address (const gchar *address,
2029 GDBusConnectionFlags flags,
2030 GCancellable *cancellable,
2031 GAsyncReadyCallback callback,
2034 g_return_if_fail (address != NULL);
2035 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2046 * g_dbus_connection_new_for_address_finish:
2047 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2048 * @error: Return location for error or %NULL.
2050 * Finishes an operation started with g_dbus_connection_new_for_address().
2052 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2057 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2061 GObject *source_object;
2063 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2064 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2066 source_object = g_async_result_get_source_object (res);
2067 g_assert (source_object != NULL);
2068 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2071 g_object_unref (source_object);
2073 return G_DBUS_CONNECTION (object);
2079 * g_dbus_connection_new_for_address_sync:
2080 * @address: A D-Bus address.
2081 * @flags: Flags describing how to make the connection.
2082 * @cancellable: A #GCancellable or %NULL.
2083 * @error: Return location for error or %NULL.
2085 * Synchronously connects and sets up a D-Bus client connection for
2086 * exchanging D-Bus messages with an endpoint specified by @address
2087 * which must be in the D-Bus address format.
2089 * This constructor can only be used to initiate client-side
2090 * connections - use g_dbus_connection_new_sync() if you need to act
2091 * as the server. In particular, @flags cannot contain the
2092 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2093 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2095 * This is a synchronous failable constructor. See
2096 * g_dbus_connection_new_for_address() for the asynchronous version.
2098 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2103 g_dbus_connection_new_for_address_sync (const gchar *address,
2104 GDBusConnectionFlags flags,
2105 GCancellable *cancellable,
2108 g_return_val_if_fail (address != NULL, NULL);
2109 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2110 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2118 /* ---------------------------------------------------------------------------------------------------- */
2121 * g_dbus_connection_set_exit_on_close:
2122 * @connection: A #GDBusConnection.
2123 * @exit_on_close: Whether the process should be terminated
2124 * when @connection is closed by the remote peer.
2126 * Sets whether the process should be terminated when @connection is
2127 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2133 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2134 gboolean exit_on_close)
2136 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2137 connection->priv->exit_on_close = exit_on_close;
2141 * g_dbus_connection_get_exit_on_close:
2142 * @connection: A #GDBusConnection.
2144 * Gets whether the process is terminated when @connection is
2145 * closed by the remote peer. See
2146 * #GDBusConnection:exit-on-close for more details.
2148 * Returns: Whether the process is terminated when @connection is
2149 * closed by the remote peer.
2154 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2156 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2157 return connection->priv->exit_on_close;
2161 * g_dbus_connection_get_guid:
2162 * @connection: A #GDBusConnection.
2164 * The GUID of the peer performing the role of server when
2165 * authenticating. See #GDBusConnection:guid for more details.
2167 * Returns: The GUID. Do not free this string, it is owned by
2173 g_dbus_connection_get_guid (GDBusConnection *connection)
2175 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2176 return connection->priv->guid;
2180 * g_dbus_connection_get_unique_name:
2181 * @connection: A #GDBusConnection.
2183 * Gets the unique name of @connection as assigned by the message
2184 * bus. This can also be used to figure out if @connection is a
2185 * message bus connection.
2187 * Returns: The unique name or %NULL if @connection is not a message
2188 * bus connection. Do not free this string, it is owned by
2194 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2196 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2197 return connection->priv->bus_unique_name;
2201 * g_dbus_connection_get_peer_credentials:
2202 * @connection: A #GDBusConnection.
2204 * Gets the credentials of the authenticated peer. This will always
2205 * return %NULL unless @connection acted as a server
2206 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2207 * when set up and the client passed credentials as part of the
2208 * authentication process.
2210 * In a message bus setup, the message bus is always the server and
2211 * each application is a client. So this method will always return
2212 * %NULL for message bus clients.
2214 * Returns: A #GCredentials or %NULL if not available. Do not free
2215 * this object, it is owned by @connection.
2220 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2222 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2223 return connection->priv->crendentials;
2226 /* ---------------------------------------------------------------------------------------------------- */
2228 static guint _global_filter_id = 1;
2231 * g_dbus_connection_add_filter:
2232 * @connection: A #GDBusConnection.
2233 * @filter_function: A filter function.
2234 * @user_data: User data to pass to @filter_function.
2235 * @user_data_free_func: Function to free @user_data with when filter
2236 * is removed or %NULL.
2238 * Adds a message filter. Filters are handlers that are run on all
2239 * incoming messages, prior to standard dispatch. Filters are run in
2240 * the order that they were added. The same handler can be added as a
2241 * filter more than once, in which case it will be run more than once.
2242 * Filters added during a filter callback won't be run on the message
2245 * Note that filters are run in a dedicated message handling thread so
2246 * they can't block and, generally, can't do anything but signal a
2247 * worker thread. Also note that filters are rarely needed - use API
2248 * such as g_dbus_connection_send_message_with_reply(),
2249 * g_dbus_connection_signal_subscribe() or
2250 * g_dbus_connection_invoke_method() instead.
2252 * Returns: A filter identifier that can be used with
2253 * g_dbus_connection_remove_filter().
2258 g_dbus_connection_add_filter (GDBusConnection *connection,
2259 GDBusMessageFilterFunction filter_function,
2261 GDestroyNotify user_data_free_func)
2265 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2266 g_return_val_if_fail (filter_function != NULL, 0);
2268 CONNECTION_LOCK (connection);
2269 data = g_new0 (FilterData, 1);
2270 data->id = _global_filter_id++; /* TODO: overflow etc. */
2271 data->filter_function = filter_function;
2272 data->user_data = user_data;
2273 data->user_data_free_func = user_data_free_func;
2274 g_ptr_array_add (connection->priv->filters, data);
2275 CONNECTION_UNLOCK (connection);
2280 /* only called from finalize(), removes all filters */
2282 purge_all_filters (GDBusConnection *connection)
2285 for (n = 0; n < connection->priv->filters->len; n++)
2287 FilterData *data = connection->priv->filters->pdata[n];
2288 if (data->user_data_free_func != NULL)
2289 data->user_data_free_func (data->user_data);
2295 g_dbus_connection_remove_filter (GDBusConnection *connection,
2299 FilterData *to_destroy;
2301 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2303 CONNECTION_LOCK (connection);
2305 for (n = 0; n < connection->priv->filters->len; n++)
2307 FilterData *data = connection->priv->filters->pdata[n];
2308 if (data->id == filter_id)
2310 g_ptr_array_remove_index (connection->priv->filters, n);
2315 CONNECTION_UNLOCK (connection);
2317 /* do free without holding lock */
2318 if (to_destroy != NULL)
2320 if (to_destroy->user_data_free_func != NULL)
2321 to_destroy->user_data_free_func (to_destroy->user_data);
2322 g_free (to_destroy);
2326 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2330 /* ---------------------------------------------------------------------------------------------------- */
2336 gchar *interface_name;
2340 GArray *subscribers;
2345 GDBusSignalCallback callback;
2347 GDestroyNotify user_data_free_func;
2349 GMainContext *context;
2353 signal_data_free (SignalData *data)
2355 g_free (data->rule);
2356 g_free (data->sender);
2357 g_free (data->interface_name);
2358 g_free (data->member);
2359 g_free (data->object_path);
2360 g_free (data->arg0);
2361 g_array_free (data->subscribers, TRUE);
2366 args_to_rule (const gchar *sender,
2367 const gchar *interface_name,
2368 const gchar *member,
2369 const gchar *object_path,
2374 rule = g_string_new ("type='signal'");
2376 g_string_append_printf (rule, ",sender='%s'", sender);
2377 if (interface_name != NULL)
2378 g_string_append_printf (rule, ",interface='%s'", interface_name);
2380 g_string_append_printf (rule, ",member='%s'", member);
2381 if (object_path != NULL)
2382 g_string_append_printf (rule, ",path='%s'", object_path);
2384 g_string_append_printf (rule, ",arg0='%s'", arg0);
2386 return g_string_free (rule, FALSE);
2389 static guint _global_subscriber_id = 1;
2390 static guint _global_registration_id = 1;
2391 static guint _global_subtree_registration_id = 1;
2393 /* ---------------------------------------------------------------------------------------------------- */
2395 /* must hold lock when calling */
2397 add_match_rule (GDBusConnection *connection,
2398 const gchar *match_rule)
2401 GDBusMessage *message;
2403 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2404 "/org/freedesktop/DBus", /* path */
2405 "org.freedesktop.DBus", /* interface */
2407 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2410 if (!g_dbus_connection_send_message_unlocked (connection,
2415 g_critical ("Error while sending AddMatch() message: %s", error->message);
2416 g_error_free (error);
2418 g_object_unref (message);
2421 /* ---------------------------------------------------------------------------------------------------- */
2423 /* must hold lock when calling */
2425 remove_match_rule (GDBusConnection *connection,
2426 const gchar *match_rule)
2429 GDBusMessage *message;
2431 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2432 "/org/freedesktop/DBus", /* path */
2433 "org.freedesktop.DBus", /* interface */
2435 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2438 if (!g_dbus_connection_send_message_unlocked (connection,
2443 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2444 g_error_free (error);
2446 g_object_unref (message);
2449 /* ---------------------------------------------------------------------------------------------------- */
2452 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2454 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2455 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2456 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2457 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2458 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2461 /* ---------------------------------------------------------------------------------------------------- */
2464 * g_dbus_connection_signal_subscribe:
2465 * @connection: A #GDBusConnection.
2466 * @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.
2467 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2468 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2469 * @object_path: Object path to match on or %NULL to match on all object paths.
2470 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2471 * @callback: Callback to invoke when there is a signal matching the requested data.
2472 * @user_data: User data to pass to @callback.
2473 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2475 * Subscribes to signals on @connection and invokes @callback with a
2476 * whenever the signal is received. Note that @callback
2477 * will be invoked in the <link
2478 * linkend="g-main-context-push-thread-default">thread-default main
2479 * loop</link> of the thread you are calling this method from.
2481 * It is considered a programming error to use this function if @connection is closed.
2483 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2484 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2485 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2486 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2487 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2488 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2490 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2495 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2496 const gchar *sender,
2497 const gchar *interface_name,
2498 const gchar *member,
2499 const gchar *object_path,
2501 GDBusSignalCallback callback,
2503 GDestroyNotify user_data_free_func)
2506 SignalData *signal_data;
2507 SignalSubscriber subscriber;
2508 GPtrArray *signal_data_array;
2510 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2511 * an OOM condition. We might want to change that but that would involve making
2512 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2513 * handle that. And there's really no sensible way of handling this short of retrying
2514 * to add the match rule... and then there's the little thing that, hey, maybe there's
2515 * a reason the bus in an OOM condition.
2517 * Doable, but not really sure it's worth it...
2520 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2521 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2522 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2523 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2524 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2525 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2526 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2527 g_return_val_if_fail (callback != NULL, 0);
2529 CONNECTION_LOCK (connection);
2531 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2536 subscriber.callback = callback;
2537 subscriber.user_data = user_data;
2538 subscriber.user_data_free_func = user_data_free_func;
2539 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2540 subscriber.context = g_main_context_get_thread_default ();
2541 if (subscriber.context != NULL)
2542 g_main_context_ref (subscriber.context);
2544 /* see if we've already have this rule */
2545 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2546 if (signal_data != NULL)
2548 g_array_append_val (signal_data->subscribers, subscriber);
2553 signal_data = g_new0 (SignalData, 1);
2554 signal_data->rule = rule;
2555 signal_data->sender = g_strdup (sender);
2556 signal_data->interface_name = g_strdup (interface_name);
2557 signal_data->member = g_strdup (member);
2558 signal_data->object_path = g_strdup (object_path);
2559 signal_data->arg0 = g_strdup (arg0);
2560 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2561 g_array_append_val (signal_data->subscribers, subscriber);
2563 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2567 /* Add the match rule to the bus...
2569 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2570 * always send such messages to to us.
2572 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2574 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2576 add_match_rule (connection, signal_data->rule);
2581 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2582 GUINT_TO_POINTER (subscriber.id),
2585 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2586 signal_data->sender);
2587 if (signal_data_array == NULL)
2589 signal_data_array = g_ptr_array_new ();
2590 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2591 g_strdup (signal_data->sender),
2594 g_ptr_array_add (signal_data_array, signal_data);
2596 CONNECTION_UNLOCK (connection);
2598 return subscriber.id;
2601 /* ---------------------------------------------------------------------------------------------------- */
2603 /* must hold lock when calling this */
2605 unsubscribe_id_internal (GDBusConnection *connection,
2606 guint subscription_id,
2607 GArray *out_removed_subscribers)
2609 SignalData *signal_data;
2610 GPtrArray *signal_data_array;
2613 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2614 GUINT_TO_POINTER (subscription_id));
2615 if (signal_data == NULL)
2617 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2621 for (n = 0; n < signal_data->subscribers->len; n++)
2623 SignalSubscriber *subscriber;
2625 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2626 if (subscriber->id != subscription_id)
2629 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2630 GUINT_TO_POINTER (subscription_id)));
2631 g_array_append_val (out_removed_subscribers, *subscriber);
2632 g_array_remove_index (signal_data->subscribers, n);
2634 if (signal_data->subscribers->len == 0)
2635 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2637 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2638 signal_data->sender);
2639 g_warn_if_fail (signal_data_array != NULL);
2640 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2642 if (signal_data_array->len == 0)
2644 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2646 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2647 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2649 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2651 remove_match_rule (connection, signal_data->rule);
2655 signal_data_free (signal_data);
2661 g_assert_not_reached ();
2668 * g_dbus_connection_signal_unsubscribe:
2669 * @connection: A #GDBusConnection.
2670 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2672 * Unsubscribes from signals.
2677 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2678 guint subscription_id)
2680 GArray *subscribers;
2683 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2685 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2687 CONNECTION_LOCK (connection);
2688 unsubscribe_id_internal (connection,
2691 CONNECTION_UNLOCK (connection);
2694 g_assert (subscribers->len == 0 || subscribers->len == 1);
2696 /* call GDestroyNotify without lock held */
2697 for (n = 0; n < subscribers->len; n++)
2699 SignalSubscriber *subscriber;
2700 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2701 if (subscriber->user_data_free_func != NULL)
2702 subscriber->user_data_free_func (subscriber->user_data);
2703 if (subscriber->context != NULL)
2704 g_main_context_unref (subscriber->context);
2707 g_array_free (subscribers, TRUE);
2710 /* ---------------------------------------------------------------------------------------------------- */
2714 guint subscription_id;
2715 GDBusSignalCallback callback;
2717 GDBusMessage *message;
2718 GDBusConnection *connection;
2719 const gchar *sender;
2721 const gchar *interface;
2722 const gchar *member;
2725 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2729 emit_signal_instance_in_idle_cb (gpointer data)
2731 SignalInstance *signal_instance = data;
2732 GVariant *parameters;
2733 gboolean has_subscription;
2735 parameters = g_dbus_message_get_body (signal_instance->message);
2736 if (parameters == NULL)
2738 parameters = g_variant_new ("()");
2739 g_variant_ref_sink (parameters);
2743 g_variant_ref_sink (parameters);
2747 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2748 signal_instance->sender,
2749 signal_instance->path,
2750 signal_instance->interface,
2751 signal_instance->member,
2752 g_variant_print (parameters, TRUE));
2755 /* Careful here, don't do the callback if we no longer has the subscription */
2756 CONNECTION_LOCK (signal_instance->connection);
2757 has_subscription = FALSE;
2758 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2759 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2760 has_subscription = TRUE;
2761 CONNECTION_UNLOCK (signal_instance->connection);
2763 if (has_subscription)
2765 signal_instance->callback (signal_instance->connection,
2766 signal_instance->sender,
2767 signal_instance->path,
2768 signal_instance->interface,
2769 signal_instance->member,
2771 signal_instance->user_data);
2773 if (parameters != NULL)
2774 g_variant_unref (parameters);
2780 signal_instance_free (SignalInstance *signal_instance)
2782 g_object_unref (signal_instance->message);
2783 g_object_unref (signal_instance->connection);
2784 g_free (signal_instance);
2787 /* called in message handler thread WITH lock held */
2789 schedule_callbacks (GDBusConnection *connection,
2790 GPtrArray *signal_data_array,
2791 GDBusMessage *message,
2792 const gchar *sender)
2795 const gchar *interface;
2796 const gchar *member;
2805 interface = g_dbus_message_get_interface (message);
2806 member = g_dbus_message_get_member (message);
2807 path = g_dbus_message_get_path (message);
2808 arg0 = g_dbus_message_get_arg0 (message);
2811 g_debug ("sender = `%s'", sender);
2812 g_debug ("interface = `%s'", interface);
2813 g_debug ("member = `%s'", member);
2814 g_debug ("path = `%s'", path);
2815 g_debug ("arg0 = `%s'", arg0);
2818 /* TODO: if this is slow, then we can change signal_data_array into
2819 * map_object_path_to_signal_data_array or something.
2821 for (n = 0; n < signal_data_array->len; n++)
2823 SignalData *signal_data = signal_data_array->pdata[n];
2825 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2828 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2831 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2834 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2837 for (m = 0; m < signal_data->subscribers->len; m++)
2839 SignalSubscriber *subscriber;
2840 GSource *idle_source;
2841 SignalInstance *signal_instance;
2843 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2845 signal_instance = g_new0 (SignalInstance, 1);
2846 signal_instance->subscription_id = subscriber->id;
2847 signal_instance->callback = subscriber->callback;
2848 signal_instance->user_data = subscriber->user_data;
2849 signal_instance->message = g_object_ref (message);
2850 signal_instance->connection = g_object_ref (connection);
2851 signal_instance->sender = sender;
2852 signal_instance->path = path;
2853 signal_instance->interface = interface;
2854 signal_instance->member = member;
2856 idle_source = g_idle_source_new ();
2857 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2858 g_source_set_callback (idle_source,
2859 emit_signal_instance_in_idle_cb,
2861 (GDestroyNotify) signal_instance_free);
2862 g_source_attach (idle_source, subscriber->context);
2863 g_source_unref (idle_source);
2868 /* called in message handler thread with lock held */
2870 distribute_signals (GDBusConnection *connection,
2871 GDBusMessage *message)
2873 GPtrArray *signal_data_array;
2874 const gchar *sender;
2876 sender = g_dbus_message_get_sender (message);
2878 /* collect subcsribers that match on sender */
2881 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2882 if (signal_data_array != NULL) {
2883 schedule_callbacks (connection, signal_data_array, message, sender);
2887 /* collect subcsribers not matching on sender */
2888 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2889 if (signal_data_array != NULL)
2891 schedule_callbacks (connection, signal_data_array, message, sender);
2895 /* ---------------------------------------------------------------------------------------------------- */
2897 /* only called from finalize(), removes all subscriptions */
2899 purge_all_signal_subscriptions (GDBusConnection *connection)
2901 GHashTableIter iter;
2904 GArray *subscribers;
2907 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2908 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2909 while (g_hash_table_iter_next (&iter, &key, NULL))
2911 guint subscription_id = GPOINTER_TO_UINT (key);
2912 g_array_append_val (ids, subscription_id);
2915 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2916 for (n = 0; n < ids->len; n++)
2918 guint subscription_id = g_array_index (ids, guint, n);
2919 unsubscribe_id_internal (connection,
2923 g_array_free (ids, TRUE);
2925 /* call GDestroyNotify without lock held */
2926 for (n = 0; n < subscribers->len; n++)
2928 SignalSubscriber *subscriber;
2929 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2930 if (subscriber->user_data_free_func != NULL)
2931 subscriber->user_data_free_func (subscriber->user_data);
2932 if (subscriber->context != NULL)
2933 g_main_context_unref (subscriber->context);
2936 g_array_free (subscribers, TRUE);
2939 /* ---------------------------------------------------------------------------------------------------- */
2941 struct ExportedObject
2944 GDBusConnection *connection;
2946 /* maps gchar* -> ExportedInterface* */
2947 GHashTable *map_if_name_to_ei;
2950 /* only called with lock held */
2952 exported_object_free (ExportedObject *eo)
2954 g_free (eo->object_path);
2955 g_hash_table_unref (eo->map_if_name_to_ei);
2964 gchar *interface_name;
2965 const GDBusInterfaceVTable *vtable;
2966 const GDBusInterfaceInfo *introspection_data;
2968 GMainContext *context;
2970 GDestroyNotify user_data_free_func;
2971 } ExportedInterface;
2973 /* called with lock held */
2975 exported_interface_free (ExportedInterface *ei)
2977 if (ei->user_data_free_func != NULL)
2979 /* TODO: push to thread-default mainloop */
2980 ei->user_data_free_func (ei->user_data);
2982 if (ei->context != NULL)
2984 g_main_context_unref (ei->context);
2986 g_free (ei->interface_name);
2990 /* ---------------------------------------------------------------------------------------------------- */
2994 GDBusConnection *connection;
2995 GDBusMessage *message;
2997 const char *property_name;
2998 const GDBusInterfaceVTable *vtable;
2999 const GDBusInterfaceInfo *interface_info;
3000 const GDBusPropertyInfo *property_info;
3004 property_data_free (PropertyData *data)
3006 g_object_unref (data->connection);
3007 g_object_unref (data->message);
3011 /* called in thread where object was registered - no locks held */
3013 invoke_get_property_in_idle_cb (gpointer _data)
3015 PropertyData *data = _data;
3018 GDBusMessage *reply;
3021 value = data->vtable->get_property (data->connection,
3022 g_dbus_message_get_sender (data->message),
3023 g_dbus_message_get_path (data->message),
3024 data->interface_info->name,
3025 data->property_name,
3032 g_assert_no_error (error);
3034 g_variant_ref_sink (value);
3035 reply = g_dbus_message_new_method_reply (data->message);
3036 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3037 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3038 g_variant_unref (value);
3039 g_object_unref (reply);
3043 gchar *dbus_error_name;
3045 g_assert (error != NULL);
3047 dbus_error_name = g_dbus_error_encode_gerror (error);
3048 reply = g_dbus_message_new_method_error_literal (data->message,
3051 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3052 g_free (dbus_error_name);
3053 g_error_free (error);
3054 g_object_unref (reply);
3060 /* called in thread where object was registered - no locks held */
3062 invoke_set_property_in_idle_cb (gpointer _data)
3064 PropertyData *data = _data;
3066 GDBusMessage *reply;
3072 g_variant_get (g_dbus_message_get_body (data->message),
3078 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3079 * of the given value is wrong
3081 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3083 reply = g_dbus_message_new_method_error (data->message,
3084 "org.freedesktop.DBus.Error.InvalidArgs",
3085 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3086 data->property_info->name,
3087 data->property_info->signature,
3088 g_variant_get_type_string (value));
3092 if (!data->vtable->set_property (data->connection,
3093 g_dbus_message_get_sender (data->message),
3094 g_dbus_message_get_path (data->message),
3095 data->interface_info->name,
3096 data->property_name,
3101 gchar *dbus_error_name;
3102 g_assert (error != NULL);
3103 dbus_error_name = g_dbus_error_encode_gerror (error);
3104 reply = g_dbus_message_new_method_error_literal (data->message,
3107 g_free (dbus_error_name);
3108 g_error_free (error);
3112 reply = g_dbus_message_new_method_reply (data->message);
3116 g_assert (reply != NULL);
3117 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3118 g_object_unref (reply);
3123 /* called with lock held */
3125 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3126 GDBusMessage *message,
3128 const GDBusInterfaceInfo *introspection_data,
3129 const GDBusInterfaceVTable *vtable,
3130 GMainContext *main_context,
3134 const char *interface_name;
3135 const char *property_name;
3136 const GDBusPropertyInfo *property_info;
3137 GSource *idle_source;
3138 PropertyData *property_data;
3139 GDBusMessage *reply;
3144 g_variant_get (g_dbus_message_get_body (message),
3149 g_variant_get (g_dbus_message_get_body (message),
3158 if (vtable == NULL || vtable->get_property == NULL)
3163 if (vtable == NULL || vtable->set_property == NULL)
3167 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3169 property_info = NULL;
3171 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3172 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3173 if (property_info == NULL)
3175 reply = g_dbus_message_new_method_error (message,
3176 "org.freedesktop.DBus.Error.InvalidArgs",
3177 _("No such property `%s'"),
3179 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3180 g_object_unref (reply);
3185 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3187 reply = g_dbus_message_new_method_error (message,
3188 "org.freedesktop.DBus.Error.InvalidArgs",
3189 _("Property `%s' is not readable"),
3191 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3192 g_object_unref (reply);
3196 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3198 reply = g_dbus_message_new_method_error (message,
3199 "org.freedesktop.DBus.Error.InvalidArgs",
3200 _("Property `%s' is not writable"),
3202 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3203 g_object_unref (reply);
3208 /* ok, got the property info - call user code in an idle handler */
3209 property_data = g_new0 (PropertyData, 1);
3210 property_data->connection = g_object_ref (connection);
3211 property_data->message = g_object_ref (message);
3212 property_data->user_data = user_data;
3213 property_data->property_name = property_name;
3214 property_data->vtable = vtable;
3215 property_data->interface_info = introspection_data;
3216 property_data->property_info = property_info;
3218 idle_source = g_idle_source_new ();
3219 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3220 g_source_set_callback (idle_source,
3221 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3223 (GDestroyNotify) property_data_free);
3224 g_source_attach (idle_source, main_context);
3225 g_source_unref (idle_source);
3233 /* called with lock held */
3235 handle_getset_property (GDBusConnection *connection,
3237 GDBusMessage *message,
3240 ExportedInterface *ei;
3242 const char *interface_name;
3243 const char *property_name;
3248 g_variant_get (g_dbus_message_get_body (message),
3253 g_variant_get (g_dbus_message_get_body (message),
3259 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3260 * no such interface registered
3262 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3265 GDBusMessage *reply;
3266 reply = g_dbus_message_new_method_error (message,
3267 "org.freedesktop.DBus.Error.InvalidArgs",
3268 _("No such interface `%s'"),
3270 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3271 g_object_unref (reply);
3276 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3279 ei->introspection_data,
3287 /* ---------------------------------------------------------------------------------------------------- */
3291 GDBusConnection *connection;
3292 GDBusMessage *message;
3294 const GDBusInterfaceVTable *vtable;
3295 const GDBusInterfaceInfo *interface_info;
3296 } PropertyGetAllData;
3299 property_get_all_data_free (PropertyData *data)
3301 g_object_unref (data->connection);
3302 g_object_unref (data->message);
3306 /* called in thread where object was registered - no locks held */
3308 invoke_get_all_properties_in_idle_cb (gpointer _data)
3310 PropertyGetAllData *data = _data;
3311 GVariantBuilder *builder;
3315 GDBusMessage *reply;
3320 /* TODO: Right now we never fail this call - we just omit values if
3321 * a get_property() call is failing.
3323 * We could fail the whole call if just a single get_property() call
3324 * returns an error. We need clarification in the D-Bus spec about this.
3326 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3327 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3329 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3332 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3335 value = data->vtable->get_property (data->connection,
3336 g_dbus_message_get_sender (data->message),
3337 g_dbus_message_get_path (data->message),
3338 data->interface_info->name,
3339 property_info->name,
3346 g_variant_ref_sink (value);
3347 g_variant_builder_add (builder,
3349 property_info->name,
3351 g_variant_unref (value);
3353 result = g_variant_builder_end (builder);
3355 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3356 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3357 packed = g_variant_builder_end (builder);
3359 reply = g_dbus_message_new_method_reply (data->message);
3360 g_dbus_message_set_body (reply, packed);
3361 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3362 g_object_unref (reply);
3367 /* called with lock held */
3369 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3370 GDBusMessage *message,
3371 const GDBusInterfaceInfo *introspection_data,
3372 const GDBusInterfaceVTable *vtable,
3373 GMainContext *main_context,
3377 const char *interface_name;
3378 GSource *idle_source;
3379 PropertyGetAllData *property_get_all_data;
3383 g_variant_get (g_dbus_message_get_body (message),
3387 if (vtable == NULL || vtable->get_property == NULL)
3390 /* ok, got the property info - call user in an idle handler */
3391 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3392 property_get_all_data->connection = g_object_ref (connection);
3393 property_get_all_data->message = g_object_ref (message);
3394 property_get_all_data->user_data = user_data;
3395 property_get_all_data->vtable = vtable;
3396 property_get_all_data->interface_info = introspection_data;
3398 idle_source = g_idle_source_new ();
3399 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3400 g_source_set_callback (idle_source,
3401 invoke_get_all_properties_in_idle_cb,
3402 property_get_all_data,
3403 (GDestroyNotify) property_get_all_data_free);
3404 g_source_attach (idle_source, main_context);
3405 g_source_unref (idle_source);
3413 /* called with lock held */
3415 handle_get_all_properties (GDBusConnection *connection,
3417 GDBusMessage *message)
3419 ExportedInterface *ei;
3421 const char *interface_name;
3425 g_variant_get (g_dbus_message_get_body (message),
3429 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3430 * no such interface registered
3432 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3435 GDBusMessage *reply;
3436 reply = g_dbus_message_new_method_error (message,
3437 "org.freedesktop.DBus.Error.InvalidArgs",
3438 _("No such interface"),
3440 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3441 g_object_unref (reply);
3446 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3448 ei->introspection_data,
3456 /* ---------------------------------------------------------------------------------------------------- */
3459 introspect_append_header (GString *s)
3462 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3463 "<!-- GDBus 0.1 -->\n"
3468 introspect_append_standard_interfaces (GString *s)
3471 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3472 " <method name=\"Get\">\n"
3473 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3474 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3475 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3477 " <method name=\"GetAll\">\n"
3478 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3479 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3481 " <method name=\"Set\">\n"
3482 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3483 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3484 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3486 " <signal name=\"PropertiesChanged\">\n"
3487 " <arg type=\"s\" name=\"interface_name\"/>\n"
3488 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3491 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3492 " <method name=\"Introspect\">\n"
3493 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3496 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3497 " <method name=\"Ping\"/>\n"
3498 " <method name=\"GetMachineId\">\n"
3499 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3505 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3507 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3513 begin = object_path + path_len;
3514 end = strchr (begin, '/');
3518 s = g_strndup (begin, end - begin);
3522 s = g_strdup (begin);
3525 if (g_hash_table_lookup (set, s) == NULL)
3527 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3536 /* TODO: we want a nicer public interface for this */
3538 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3543 GHashTableIter hash_iter;
3544 const gchar *object_path;
3550 CONNECTION_ENSURE_LOCK (connection);
3552 path_len = strlen (path);
3556 set = g_hash_table_new (g_str_hash, g_str_equal);
3558 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3559 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3560 maybe_add_path (path, path_len, object_path, set);
3562 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3563 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3564 maybe_add_path (path, path_len, object_path, set);
3566 p = g_ptr_array_new ();
3567 keys = g_hash_table_get_keys (set);
3568 for (l = keys; l != NULL; l = l->next)
3570 g_ptr_array_add (p, l->data);
3572 g_hash_table_unref (set);
3575 g_ptr_array_add (p, NULL);
3576 ret = (gchar **) g_ptr_array_free (p, FALSE);
3581 g_dbus_connection_list_registered (GDBusConnection *connection,
3585 CONNECTION_LOCK (connection);
3586 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3587 CONNECTION_UNLOCK (connection);
3591 /* called in message handler thread with lock held */
3593 handle_introspect (GDBusConnection *connection,
3595 GDBusMessage *message)
3599 GDBusMessage *reply;
3600 GHashTableIter hash_iter;
3601 ExportedInterface *ei;
3604 /* first the header with the standard interfaces */
3605 s = g_string_new (NULL);
3606 introspect_append_header (s);
3607 introspect_append_standard_interfaces (s);
3609 /* then include the registered interfaces */
3610 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3611 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3613 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3616 /* finally include nodes registered below us */
3617 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3618 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3620 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3622 g_strfreev (registered);
3623 g_string_append (s, "</node>\n");
3625 reply = g_dbus_message_new_method_reply (message);
3626 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3627 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3628 g_object_unref (reply);
3629 g_string_free (s, TRUE);
3634 /* called in thread where object was registered - no locks held */
3636 invoke_method_in_idle_cb (gpointer user_data)
3638 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3639 GDBusInterfaceVTable *vtable;
3641 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3642 g_assert (vtable != NULL && vtable->method_call != NULL);
3644 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3645 g_dbus_method_invocation_get_sender (invocation),
3646 g_dbus_method_invocation_get_object_path (invocation),
3647 g_dbus_method_invocation_get_interface_name (invocation),
3648 g_dbus_method_invocation_get_method_name (invocation),
3649 g_dbus_method_invocation_get_parameters (invocation),
3650 g_object_ref (invocation),
3651 g_dbus_method_invocation_get_user_data (invocation));
3656 /* called in message handler thread with lock held */
3658 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3659 GDBusMessage *message,
3660 const GDBusInterfaceInfo *introspection_data,
3661 const GDBusInterfaceVTable *vtable,
3662 GMainContext *main_context,
3665 GDBusMethodInvocation *invocation;
3666 const GDBusMethodInfo *method_info;
3667 GDBusMessage *reply;
3668 GVariant *parameters;
3669 GSource *idle_source;
3671 gchar *in_signature;
3675 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3676 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3678 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3679 * error to the caller
3681 if (method_info == NULL)
3683 reply = g_dbus_message_new_method_error (message,
3684 "org.freedesktop.DBus.Error.UnknownMethod",
3685 _("No such method `%s'"),
3686 g_dbus_message_get_member (message));
3687 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3688 g_object_unref (reply);
3693 /* Check that the incoming args are of the right type - if they are not, return
3694 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3696 * TODO: might also be worth caching the combined signature.
3698 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3699 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3701 reply = g_dbus_message_new_method_error (message,
3702 "org.freedesktop.DBus.Error.InvalidArgs",
3703 _("Signature of message, `%s', does not match expected signature `%s'"),
3704 g_dbus_message_get_signature (message),
3706 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3707 g_object_unref (reply);
3708 g_free (in_signature);
3712 g_free (in_signature);
3714 parameters = g_dbus_message_get_body (message);
3715 if (parameters == NULL)
3717 parameters = g_variant_new ("()");
3718 g_variant_ref_sink (parameters);
3722 g_variant_ref (parameters);
3725 /* schedule the call in idle */
3726 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3727 g_dbus_message_get_path (message),
3728 g_dbus_message_get_interface (message),
3729 g_dbus_message_get_member (message),
3735 g_variant_unref (parameters);
3736 g_object_set_data (G_OBJECT (invocation),
3737 "g-dbus-interface-vtable",
3740 idle_source = g_idle_source_new ();
3741 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3742 g_source_set_callback (idle_source,
3743 invoke_method_in_idle_cb,
3746 g_source_attach (idle_source, main_context);
3747 g_source_unref (idle_source);
3756 /* ---------------------------------------------------------------------------------------------------- */
3758 /* called in message handler thread with lock held */
3760 obj_message_func (GDBusConnection *connection,
3762 GDBusMessage *message)
3764 const gchar *interface_name;
3765 const gchar *member;
3766 const gchar *signature;
3771 interface_name = g_dbus_message_get_interface (message);
3772 member = g_dbus_message_get_member (message);
3773 signature = g_dbus_message_get_signature (message);
3775 /* see if we have an interface for handling this call */
3776 if (interface_name != NULL)
3778 ExportedInterface *ei;
3779 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3782 /* we do - invoke the handler in idle in the right thread */
3784 /* handle no vtable or handler being present */
3785 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3788 handled = validate_and_maybe_schedule_method_call (connection,
3790 ei->introspection_data,
3798 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3799 g_strcmp0 (member, "Introspect") == 0 &&
3800 g_strcmp0 (signature, "") == 0)
3802 handled = handle_introspect (connection, eo, message);
3805 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3806 g_strcmp0 (member, "Get") == 0 &&
3807 g_strcmp0 (signature, "ss") == 0)
3809 handled = handle_getset_property (connection, eo, message, TRUE);
3812 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3813 g_strcmp0 (member, "Set") == 0 &&
3814 g_strcmp0 (signature, "ssv") == 0)
3816 handled = handle_getset_property (connection, eo, message, FALSE);
3819 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3820 g_strcmp0 (member, "GetAll") == 0 &&
3821 g_strcmp0 (signature, "s") == 0)
3823 handled = handle_get_all_properties (connection, eo, message);
3832 * g_dbus_connection_register_object:
3833 * @connection: A #GDBusConnection.
3834 * @object_path: The object path to register at.
3835 * @interface_name: The D-Bus interface to register.
3836 * @introspection_data: Introspection data for the interface.
3837 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3838 * @user_data: Data to pass to functions in @vtable.
3839 * @user_data_free_func: Function to call when the object path is unregistered.
3840 * @error: Return location for error or %NULL.
3842 * Registers callbacks for exported objects at @object_path with the
3843 * D-Bus interface @interface_name.
3845 * Calls to functions in @vtable (and @user_data_free_func) will
3846 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3847 * loop</link> of the thread you are calling this method from.
3849 * Note that all #GVariant values passed to functions in @vtable will match
3850 * the signature given in @introspection_data - if a remote caller passes
3851 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3852 * is returned to the remote caller.
3854 * Additionally, if the remote caller attempts to invoke methods or
3855 * access properties not mentioned in @introspection_data the
3856 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3857 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3858 * are returned to the caller.
3860 * It is considered a programming error if the
3861 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3862 * #GVariant of incorrect type.
3864 * If an existing callback is already registered at @object_path and
3865 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3867 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3869 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3870 * that can be used with g_dbus_connection_unregister_object() .
3875 g_dbus_connection_register_object (GDBusConnection *connection,
3876 const gchar *object_path,
3877 const gchar *interface_name,
3878 const GDBusInterfaceInfo *introspection_data,
3879 const GDBusInterfaceVTable *vtable,
3881 GDestroyNotify user_data_free_func,
3885 ExportedInterface *ei;
3888 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3889 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3890 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3891 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3892 g_return_val_if_fail (introspection_data != NULL, 0);
3893 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3897 CONNECTION_LOCK (connection);
3899 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3902 eo = g_new0 (ExportedObject, 1);
3903 eo->object_path = g_strdup (object_path);
3904 eo->connection = connection;
3905 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3908 (GDestroyNotify) exported_interface_free);
3909 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3912 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3918 _("An object is already exported for the interface %s at %s"),
3924 ei = g_new0 (ExportedInterface, 1);
3925 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3927 ei->user_data = user_data;
3928 ei->user_data_free_func = user_data_free_func;
3929 ei->vtable = vtable;
3930 ei->introspection_data = introspection_data;
3931 ei->interface_name = g_strdup (interface_name);
3932 ei->context = g_main_context_get_thread_default ();
3933 if (ei->context != NULL)
3934 g_main_context_ref (ei->context);
3936 g_hash_table_insert (eo->map_if_name_to_ei,
3937 (gpointer) ei->interface_name,
3939 g_hash_table_insert (connection->priv->map_id_to_ei,
3940 GUINT_TO_POINTER (ei->id),
3946 CONNECTION_UNLOCK (connection);
3952 * g_dbus_connection_unregister_object:
3953 * @connection: A #GDBusConnection.
3954 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3956 * Unregisters an object.
3958 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3963 g_dbus_connection_unregister_object (GDBusConnection *connection,
3964 guint registration_id)
3966 ExportedInterface *ei;
3970 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3974 CONNECTION_LOCK (connection);
3976 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
3977 GUINT_TO_POINTER (registration_id));
3985 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
3986 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
3987 /* unregister object path if we have no more exported interfaces */
3988 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
3990 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
3997 CONNECTION_UNLOCK (connection);
4002 /* ---------------------------------------------------------------------------------------------------- */
4005 * g_dbus_connection_emit_signal:
4006 * @connection: A #GDBusConnection.
4007 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4008 * @object_path: Path of remote object.
4009 * @interface_name: D-Bus interface to emit a signal on.
4010 * @signal_name: The name of the signal to emit.
4011 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4012 * @error: Return location for error or %NULL.
4016 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4018 * Returns: %TRUE unless @error is set.
4023 g_dbus_connection_emit_signal (GDBusConnection *connection,
4024 const gchar *destination_bus_name,
4025 const gchar *object_path,
4026 const gchar *interface_name,
4027 const gchar *signal_name,
4028 GVariant *parameters,
4031 GDBusMessage *message;
4037 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4038 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4039 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4040 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4041 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4042 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4044 message = g_dbus_message_new_signal (object_path,
4048 if (destination_bus_name != NULL)
4050 g_dbus_message_set_header (message,
4051 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4052 g_variant_new_string (destination_bus_name));
4055 if (parameters != NULL)
4056 g_dbus_message_set_body (message, parameters);
4058 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4059 g_object_unref (message);
4065 add_invoke_method_flags (GDBusMessage *message,
4066 GDBusInvokeMethodFlags flags)
4068 if (flags & G_DBUS_INVOKE_METHOD_FLAGS_NO_AUTO_START)
4069 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4073 * g_dbus_connection_invoke_method:
4074 * @connection: A #GDBusConnection.
4075 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4076 * @object_path: Path of remote object.
4077 * @interface_name: D-Bus interface to invoke method on.
4078 * @method_name: The name of the method to invoke.
4079 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4080 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4081 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4082 * @cancellable: A #GCancellable or %NULL.
4083 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4084 * care about the result of the method invocation.
4085 * @user_data: The data to pass to @callback.
4087 * Asynchronously invokes the @method_name method on the
4088 * @interface_name D-Bus interface on the remote object at
4089 * @object_path owned by @bus_name.
4091 * If @connection is closed then the operation will fail with
4092 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4093 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4094 * not compatible with the D-Bus protocol, the operation fails with
4095 * %G_IO_ERROR_INVALID_ARGUMENT.
4097 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4098 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4099 * of the thread you are calling this method from. You can then call
4100 * g_dbus_connection_invoke_method_finish() to get the result of the operation.
4101 * See g_dbus_connection_invoke_method_sync() for the synchronous version of this
4107 g_dbus_connection_invoke_method (GDBusConnection *connection,
4108 const gchar *bus_name,
4109 const gchar *object_path,
4110 const gchar *interface_name,
4111 const gchar *method_name,
4112 GVariant *parameters,
4113 GDBusInvokeMethodFlags flags,
4115 GCancellable *cancellable,
4116 GAsyncReadyCallback callback,
4119 GDBusMessage *message;
4121 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4122 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4123 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4124 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4125 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4126 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4127 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4129 message = g_dbus_message_new_method_call (bus_name,
4133 add_invoke_method_flags (message, flags);
4134 if (parameters != NULL)
4135 g_dbus_message_set_body (message, parameters);
4137 g_dbus_connection_send_message_with_reply (connection,
4140 NULL, /* volatile guint32 *out_serial */
4145 if (message != NULL)
4146 g_object_unref (message);
4150 decode_method_reply (GDBusMessage *reply, GError **error)
4155 switch (g_dbus_message_get_type (reply))
4157 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4158 result = g_dbus_message_get_body (reply);
4161 result = g_variant_new ("()");
4162 g_variant_ref_sink (result);
4166 g_variant_ref (result);
4169 case G_DBUS_MESSAGE_TYPE_ERROR:
4170 g_dbus_message_to_gerror (reply, error);
4174 g_assert_not_reached ();
4182 * g_dbus_connection_invoke_method_finish:
4183 * @connection: A #GDBusConnection.
4184 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_invoke_method().
4185 * @error: Return location for error or %NULL.
4187 * Finishes an operation started with g_dbus_connection_invoke_method().
4189 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4190 * return values. Free with g_variant_unref().
4195 g_dbus_connection_invoke_method_finish (GDBusConnection *connection,
4199 GDBusMessage *reply;
4202 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4203 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4204 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4208 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4212 result = decode_method_reply (reply, error);
4214 g_object_unref (reply);
4220 /* ---------------------------------------------------------------------------------------------------- */
4223 * g_dbus_connection_invoke_method_sync:
4224 * @connection: A #GDBusConnection.
4225 * @bus_name: A unique or well-known bus name.
4226 * @object_path: Path of remote object.
4227 * @interface_name: D-Bus interface to invoke method on.
4228 * @method_name: The name of the method to invoke.
4229 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4230 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4231 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4232 * @cancellable: A #GCancellable or %NULL.
4233 * @error: Return location for error or %NULL.
4235 * Synchronously invokes the @method_name method on the
4236 * @interface_name D-Bus interface on the remote object at
4237 * @object_path owned by @bus_name.
4239 * If @connection is closed then the operation will fail with
4240 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4241 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4242 * contains a value not compatible with the D-Bus protocol, the operation
4243 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4245 * The calling thread is blocked until a reply is received. See
4246 * g_dbus_connection_invoke_method() for the asynchronous version of
4249 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4250 * return values. Free with g_variant_unref().
4255 g_dbus_connection_invoke_method_sync (GDBusConnection *connection,
4256 const gchar *bus_name,
4257 const gchar *object_path,
4258 const gchar *interface_name,
4259 const gchar *method_name,
4260 GVariant *parameters,
4261 GDBusInvokeMethodFlags flags,
4263 GCancellable *cancellable,
4266 GDBusMessage *message;
4267 GDBusMessage *reply;
4274 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4275 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4276 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4277 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4278 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4279 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4280 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4282 message = g_dbus_message_new_method_call (bus_name,
4286 add_invoke_method_flags (message, flags);
4287 if (parameters != NULL)
4288 g_dbus_message_set_body (message, parameters);
4290 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4293 NULL, /* volatile guint32 *out_serial */
4300 result = decode_method_reply (reply, error);
4303 if (message != NULL)
4304 g_object_unref (message);
4306 g_object_unref (reply);
4311 /* ---------------------------------------------------------------------------------------------------- */
4313 struct ExportedSubtree
4317 GDBusConnection *connection;
4318 const GDBusSubtreeVTable *vtable;
4319 GDBusSubtreeFlags flags;
4321 GMainContext *context;
4323 GDestroyNotify user_data_free_func;
4327 exported_subtree_free (ExportedSubtree *es)
4329 if (es->user_data_free_func != NULL)
4331 /* TODO: push to thread-default mainloop */
4332 es->user_data_free_func (es->user_data);
4334 if (es->context != NULL)
4336 g_main_context_unref (es->context);
4338 g_free (es->object_path);
4342 /* called without lock held */
4344 handle_subtree_introspect (GDBusConnection *connection,
4345 ExportedSubtree *es,
4346 GDBusMessage *message)
4350 GDBusMessage *reply;
4353 const gchar *sender;
4354 const gchar *requested_object_path;
4355 const gchar *requested_node;
4356 GPtrArray *interfaces;
4358 gchar **subnode_paths;
4362 requested_object_path = g_dbus_message_get_path (message);
4363 sender = g_dbus_message_get_sender (message);
4364 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4366 s = g_string_new (NULL);
4367 introspect_append_header (s);
4369 /* Strictly we don't need the children in dynamic mode, but we avoid the
4370 * conditionals to preserve code clarity
4372 children = es->vtable->enumerate (es->connection,
4379 requested_node = strrchr (requested_object_path, '/') + 1;
4381 /* Assert existence of object if we are not dynamic */
4382 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4383 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4388 requested_node = "/";
4391 interfaces = es->vtable->introspect (es->connection,
4396 if (interfaces != NULL)
4398 if (interfaces->len > 0)
4400 /* we're in business */
4401 introspect_append_standard_interfaces (s);
4403 for (n = 0; n < interfaces->len; n++)
4405 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4406 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4409 g_ptr_array_unref (interfaces);
4412 /* then include <node> entries from the Subtree for the root */
4415 for (n = 0; children != NULL && children[n] != NULL; n++)
4417 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4421 /* finally include nodes registered below us */
4422 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4423 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4425 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4427 g_strfreev (subnode_paths);
4429 g_string_append (s, "</node>\n");
4431 reply = g_dbus_message_new_method_reply (message);
4432 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4433 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4434 g_object_unref (reply);
4439 g_string_free (s, TRUE);
4440 g_strfreev (children);
4444 /* called without lock held */
4446 handle_subtree_method_invocation (GDBusConnection *connection,
4447 ExportedSubtree *es,
4448 GDBusMessage *message)
4451 const gchar *sender;
4452 const gchar *interface_name;
4453 const gchar *member;
4454 const gchar *signature;
4455 const gchar *requested_object_path;
4456 const gchar *requested_node;
4459 const GDBusInterfaceInfo *introspection_data;
4460 const GDBusInterfaceVTable *interface_vtable;
4461 gpointer interface_user_data;
4463 GPtrArray *interfaces;
4464 gboolean is_property_get;
4465 gboolean is_property_set;
4466 gboolean is_property_get_all;
4471 requested_object_path = g_dbus_message_get_path (message);
4472 sender = g_dbus_message_get_sender (message);
4473 interface_name = g_dbus_message_get_interface (message);
4474 member = g_dbus_message_get_member (message);
4475 signature = g_dbus_message_get_signature (message);
4476 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4478 is_property_get = FALSE;
4479 is_property_set = FALSE;
4480 is_property_get_all = FALSE;
4481 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4483 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4485 is_property_get = TRUE;
4487 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4489 is_property_set = TRUE;
4491 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4493 is_property_get_all = TRUE;
4497 children = es->vtable->enumerate (es->connection,
4504 requested_node = strrchr (requested_object_path, '/') + 1;
4506 /* If not dynamic, skip if requested node is not part of children */
4507 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4508 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4513 requested_node = "/";
4516 /* get introspection data for the node */
4517 interfaces = es->vtable->introspect (es->connection,
4519 requested_object_path,
4522 g_assert (interfaces != NULL);
4523 introspection_data = NULL;
4524 for (n = 0; n < interfaces->len; n++)
4526 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4527 if (g_strcmp0 (id_n->name, interface_name) == 0)
4529 introspection_data = id_n;
4533 /* dispatch the call if the user wants to handle it */
4534 if (introspection_data != NULL)
4536 /* figure out where to dispatch the method call */
4537 interface_user_data = NULL;
4538 interface_vtable = es->vtable->dispatch (es->connection,
4543 &interface_user_data,
4545 if (interface_vtable == NULL)
4548 CONNECTION_LOCK (connection);
4549 handled = validate_and_maybe_schedule_method_call (es->connection,
4554 interface_user_data);
4555 CONNECTION_UNLOCK (connection);
4557 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4558 else if (is_property_get || is_property_set || is_property_get_all)
4560 if (is_property_get)
4561 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4562 else if (is_property_set)
4563 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4564 else if (is_property_get_all)
4565 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4567 g_assert_not_reached ();
4569 /* see if the object supports this interface at all */
4570 for (n = 0; n < interfaces->len; n++)
4572 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4573 if (g_strcmp0 (id_n->name, interface_name) == 0)
4575 introspection_data = id_n;
4579 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4580 * claims it won't support the interface
4582 if (introspection_data == NULL)
4584 GDBusMessage *reply;
4585 reply = g_dbus_message_new_method_error (message,
4586 "org.freedesktop.DBus.Error.InvalidArgs",
4587 _("No such interface `%s'"),
4589 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4590 g_object_unref (reply);
4595 /* figure out where to dispatch the property get/set/getall calls */
4596 interface_user_data = NULL;
4597 interface_vtable = es->vtable->dispatch (es->connection,
4602 &interface_user_data,
4604 if (interface_vtable == NULL)
4607 if (is_property_get || is_property_set)
4609 CONNECTION_LOCK (connection);
4610 handled = validate_and_maybe_schedule_property_getset (es->connection,
4616 interface_user_data);
4617 CONNECTION_UNLOCK (connection);
4619 else if (is_property_get_all)
4621 CONNECTION_LOCK (connection);
4622 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4627 interface_user_data);
4628 CONNECTION_UNLOCK (connection);
4633 if (interfaces != NULL)
4634 g_ptr_array_unref (interfaces);
4635 g_strfreev (children);
4641 GDBusMessage *message;
4642 ExportedSubtree *es;
4643 } SubtreeDeferredData;
4646 subtree_deferred_data_free (SubtreeDeferredData *data)
4648 g_object_unref (data->message);
4652 /* called without lock held in the thread where the caller registered the subtree */
4654 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4656 SubtreeDeferredData *data = _data;
4661 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4662 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4663 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4665 handled = handle_subtree_introspect (data->es->connection,
4671 handled = handle_subtree_method_invocation (data->es->connection,
4679 CONNECTION_LOCK (data->es->connection);
4680 handled = handle_generic_unlocked (data->es->connection, data->message);
4681 CONNECTION_UNLOCK (data->es->connection);
4684 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4687 GDBusMessage *reply;
4688 reply = g_dbus_message_new_method_error (data->message,
4689 "org.freedesktop.DBus.Error.UnknownMethod",
4690 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4691 g_dbus_message_get_member (data->message),
4692 g_dbus_message_get_interface (data->message),
4693 g_dbus_message_get_signature (data->message));
4694 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4695 g_object_unref (reply);
4701 /* called in message handler thread with lock held */
4703 subtree_message_func (GDBusConnection *connection,
4704 ExportedSubtree *es,
4705 GDBusMessage *message)
4707 GSource *idle_source;
4708 SubtreeDeferredData *data;
4710 data = g_new0 (SubtreeDeferredData, 1);
4711 data->message = g_object_ref (message);
4714 /* defer this call to an idle handler in the right thread */
4715 idle_source = g_idle_source_new ();
4716 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4717 g_source_set_callback (idle_source,
4718 process_subtree_vtable_message_in_idle_cb,
4720 (GDestroyNotify) subtree_deferred_data_free);
4721 g_source_attach (idle_source, es->context);
4722 g_source_unref (idle_source);
4724 /* since we own the entire subtree, handlers for objects not in the subtree have been
4725 * tried already by libdbus-1 - so we just need to ensure that we're always going
4726 * to reply to the message
4732 * g_dbus_connection_register_subtree:
4733 * @connection: A #GDBusConnection.
4734 * @object_path: The object path to register the subtree at.
4735 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4736 * @flags: Flags used to fine tune the behavior of the subtree.
4737 * @user_data: Data to pass to functions in @vtable.
4738 * @user_data_free_func: Function to call when the subtree is unregistered.
4739 * @error: Return location for error or %NULL.
4741 * Registers a whole subtree of <quote>dynamic</quote> objects.
4743 * The @enumerate and @introspection functions in @vtable are used to
4744 * convey, to remote callers, what nodes exist in the subtree rooted
4747 * When handling remote calls into any node in the subtree, first the
4748 * @enumerate function is used to check if the node exists. If the node exists
4749 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4750 * the @introspection function is used to check if the node supports the
4751 * requested method. If so, the @dispatch function is used to determine
4752 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4753 * #gpointer will be used to call into the interface vtable for processing
4756 * All calls into user-provided code will be invoked in the <link
4757 * linkend="g-main-context-push-thread-default">thread-default main
4758 * loop</link> of the thread you are calling this method from.
4760 * If an existing subtree is already registered at @object_path or
4761 * then @error is set to #G_IO_ERROR_EXISTS.
4763 * Note that it is valid to register regular objects (using
4764 * g_dbus_connection_register_object()) in a subtree registered with
4765 * g_dbus_connection_register_subtree() - if so, the subtree handler
4766 * is tried as the last resort. One way to think about a subtree
4767 * handler is to consider it a <quote>fallback handler</quote>
4768 * for object paths not registered via g_dbus_connection_register_object()
4769 * or other bindings.
4771 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4773 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4774 * that can be used with g_dbus_connection_unregister_subtree() .
4779 g_dbus_connection_register_subtree (GDBusConnection *connection,
4780 const gchar *object_path,
4781 const GDBusSubtreeVTable *vtable,
4782 GDBusSubtreeFlags flags,
4784 GDestroyNotify user_data_free_func,
4788 ExportedSubtree *es;
4790 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4791 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4792 g_return_val_if_fail (vtable != NULL, 0);
4793 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4797 CONNECTION_LOCK (connection);
4799 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4805 _("A subtree is already exported for %s"),
4810 es = g_new0 (ExportedSubtree, 1);
4811 es->object_path = g_strdup (object_path);
4812 es->connection = connection;
4814 es->vtable = vtable;
4816 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4817 es->user_data = user_data;
4818 es->user_data_free_func = user_data_free_func;
4819 es->context = g_main_context_get_thread_default ();
4820 if (es->context != NULL)
4821 g_main_context_ref (es->context);
4823 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4824 g_hash_table_insert (connection->priv->map_id_to_es,
4825 GUINT_TO_POINTER (es->id),
4831 CONNECTION_UNLOCK (connection);
4836 /* ---------------------------------------------------------------------------------------------------- */
4839 * g_dbus_connection_unregister_subtree:
4840 * @connection: A #GDBusConnection.
4841 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4843 * Unregisters a subtree.
4845 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4850 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4851 guint registration_id)
4853 ExportedSubtree *es;
4856 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4860 CONNECTION_LOCK (connection);
4862 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4863 GUINT_TO_POINTER (registration_id));
4869 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4870 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4875 CONNECTION_UNLOCK (connection);
4880 /* ---------------------------------------------------------------------------------------------------- */
4882 /* must be called with lock held */
4884 handle_generic_ping_unlocked (GDBusConnection *connection,
4885 const gchar *object_path,
4886 GDBusMessage *message)
4888 GDBusMessage *reply;
4889 reply = g_dbus_message_new_method_reply (message);
4890 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4891 g_object_unref (reply);
4894 /* must be called with lock held */
4896 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4897 const gchar *object_path,
4898 GDBusMessage *message)
4900 GDBusMessage *reply;
4903 if (connection->priv->machine_id == NULL)
4907 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4908 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4909 &connection->priv->machine_id,
4913 reply = g_dbus_message_new_method_error (message,
4914 "org.freedesktop.DBus.Error.Failed",
4915 _("Unable to load /var/lib/dbus/machine-id: %s"),
4917 g_error_free (error);
4921 g_strstrip (connection->priv->machine_id);
4922 /* TODO: validate value */
4928 reply = g_dbus_message_new_method_reply (message);
4929 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4931 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4932 g_object_unref (reply);
4935 /* must be called with lock held */
4937 handle_generic_introspect_unlocked (GDBusConnection *connection,
4938 const gchar *object_path,
4939 GDBusMessage *message)
4944 GDBusMessage *reply;
4946 /* first the header */
4947 s = g_string_new (NULL);
4948 introspect_append_header (s);
4950 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4951 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4953 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4955 g_strfreev (registered);
4956 g_string_append (s, "</node>\n");
4958 reply = g_dbus_message_new_method_reply (message);
4959 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4960 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4961 g_object_unref (reply);
4962 g_string_free (s, TRUE);
4965 /* must be called with lock held */
4967 handle_generic_unlocked (GDBusConnection *connection,
4968 GDBusMessage *message)
4971 const gchar *interface_name;
4972 const gchar *member;
4973 const gchar *signature;
4976 CONNECTION_ENSURE_LOCK (connection);
4980 interface_name = g_dbus_message_get_interface (message);
4981 member = g_dbus_message_get_member (message);
4982 signature = g_dbus_message_get_signature (message);
4983 path = g_dbus_message_get_path (message);
4985 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4986 g_strcmp0 (member, "Introspect") == 0 &&
4987 g_strcmp0 (signature, "") == 0)
4989 handle_generic_introspect_unlocked (connection, path, message);
4992 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4993 g_strcmp0 (member, "Ping") == 0 &&
4994 g_strcmp0 (signature, "") == 0)
4996 handle_generic_ping_unlocked (connection, path, message);
4999 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5000 g_strcmp0 (member, "GetMachineId") == 0 &&
5001 g_strcmp0 (signature, "") == 0)
5003 handle_generic_get_machine_id_unlocked (connection, path, message);
5010 /* ---------------------------------------------------------------------------------------------------- */
5012 /* called in message handler thread with lock held */
5014 distribute_method_call (GDBusConnection *connection,
5015 GDBusMessage *message)
5018 ExportedSubtree *es;
5019 const gchar *object_path;
5020 const gchar *interface_name;
5021 const gchar *member;
5022 const gchar *signature;
5024 gchar *subtree_path;
5027 g_assert (g_dbus_message_get_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5029 interface_name = g_dbus_message_get_interface (message);
5030 member = g_dbus_message_get_member (message);
5031 signature = g_dbus_message_get_signature (message);
5032 path = g_dbus_message_get_path (message);
5033 subtree_path = g_strdup (path);
5034 needle = strrchr (subtree_path, '/');
5035 if (needle != NULL && needle != subtree_path)
5041 g_free (subtree_path);
5042 subtree_path = NULL;
5046 g_debug ("interface = `%s'", interface_name);
5047 g_debug ("member = `%s'", member);
5048 g_debug ("signature = `%s'", signature);
5049 g_debug ("path = `%s'", path);
5050 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5053 object_path = g_dbus_message_get_path (message);
5054 g_assert (object_path != NULL);
5056 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5059 if (obj_message_func (connection, eo, message))
5063 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5066 if (subtree_message_func (connection, es, message))
5070 if (subtree_path != NULL)
5072 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5075 if (subtree_message_func (connection, es, message))
5080 if (handle_generic_unlocked (connection, message))
5083 /* if we end up here, the message has not been not handled */
5086 g_free (subtree_path);
5089 /* ---------------------------------------------------------------------------------------------------- */
5091 static GDBusConnection **
5092 message_bus_get_singleton (GBusType bus_type,
5095 GDBusConnection **ret;
5096 const gchar *starter_bus;
5103 g_assert_not_reached ();
5106 case G_BUS_TYPE_SESSION:
5107 ret = &the_session_bus;
5110 case G_BUS_TYPE_SYSTEM:
5111 ret = &the_system_bus;
5114 case G_BUS_TYPE_STARTER:
5115 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5116 if (g_strcmp0 (starter_bus, "session") == 0)
5118 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5121 else if (g_strcmp0 (starter_bus, "system") == 0)
5123 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5128 if (starter_bus != NULL)
5132 G_IO_ERROR_INVALID_ARGUMENT,
5133 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5134 " - unknown value `%s'"),
5139 g_set_error_literal (error,
5141 G_IO_ERROR_INVALID_ARGUMENT,
5142 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5143 "variable is not set"));
5152 static GDBusConnection *
5153 get_uninitialized_connection (GBusType bus_type,
5154 GCancellable *cancellable,
5157 GDBusConnection **singleton;
5158 GDBusConnection *ret;
5162 G_LOCK (message_bus_lock);
5163 singleton = message_bus_get_singleton (bus_type, error);
5164 if (singleton == NULL)
5167 if (*singleton == NULL)
5170 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5171 if (address == NULL)
5173 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5175 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5176 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5177 "exit-on-close", TRUE,
5182 ret = g_object_ref (*singleton);
5185 g_assert (ret != NULL);
5188 G_UNLOCK (message_bus_lock);
5194 * @bus_type: A #GBusType.
5195 * @cancellable: A #GCancellable or %NULL.
5196 * @error: Return location for error or %NULL.
5198 * Synchronously connects to the message bus specified by @bus_type.
5199 * Note that the returned object may shared with other callers,
5200 * e.g. if two separate parts of a process calls this function with
5201 * the same @bus_type, they will share the same object.
5203 * This is a synchronous failable function. See g_bus_get() and
5204 * g_bus_get_finish() for the asynchronous version.
5206 * The returned object is a singleton, that is, shared with other
5207 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5208 * event that you need a private message bus connection, use
5209 * g_dbus_address_get_for_bus() and
5210 * g_dbus_connection_new_for_address().
5212 * Note that the returned #GDBusConnection object will (usually) have
5213 * the #GDBusConnection:exit-on-close property set to %TRUE.
5215 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5220 g_bus_get_sync (GBusType bus_type,
5221 GCancellable *cancellable,
5224 GDBusConnection *connection;
5226 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5228 connection = get_uninitialized_connection (bus_type, cancellable, error);
5229 if (connection == NULL)
5232 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5234 g_object_unref (connection);
5243 bus_get_async_initable_cb (GObject *source_object,
5247 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5251 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5255 g_assert (error != NULL);
5256 g_simple_async_result_set_from_error (simple, error);
5257 g_error_free (error);
5258 g_object_unref (source_object);
5262 g_simple_async_result_set_op_res_gpointer (simple,
5266 g_simple_async_result_complete_in_idle (simple);
5267 g_object_unref (simple);
5272 * @bus_type: A #GBusType.
5273 * @cancellable: A #GCancellable or %NULL.
5274 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5275 * @user_data: The data to pass to @callback.
5277 * Asynchronously connects to the message bus specified by @bus_type.
5279 * When the operation is finished, @callback will be invoked. You can
5280 * then call g_bus_get_finish() to get the result of the operation.
5282 * This is a asynchronous failable function. See g_bus_get_sync() for
5283 * the synchronous version.
5288 g_bus_get (GBusType bus_type,
5289 GCancellable *cancellable,
5290 GAsyncReadyCallback callback,
5293 GDBusConnection *connection;
5294 GSimpleAsyncResult *simple;
5297 simple = g_simple_async_result_new (NULL,
5303 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5304 if (connection == NULL)
5306 g_assert (error != NULL);
5307 g_simple_async_result_set_from_error (simple, error);
5308 g_error_free (error);
5309 g_simple_async_result_complete_in_idle (simple);
5310 g_object_unref (simple);
5314 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5317 bus_get_async_initable_cb,
5324 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5325 * @error: Return location for error or %NULL.
5327 * Finishes an operation started with g_bus_get().
5329 * The returned object is a singleton, that is, shared with other
5330 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5331 * event that you need a private message bus connection, use
5332 * g_dbus_address_get_for_bus() and
5333 * g_dbus_connection_new_for_address().
5335 * Note that the returned #GDBusConnection object will (usually) have
5336 * the #GDBusConnection:exit-on-close property set to %TRUE.
5338 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5343 g_bus_get_finish (GAsyncResult *res,
5346 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5348 GDBusConnection *ret;
5350 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5352 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5356 if (g_simple_async_result_propagate_error (simple, error))
5359 object = g_simple_async_result_get_op_res_gpointer (simple);
5360 g_assert (object != NULL);
5361 ret = g_object_ref (G_DBUS_CONNECTION (object));
5367 /* ---------------------------------------------------------------------------------------------------- */