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>
83 * SECTION:gdbusconnection
84 * @short_description: D-Bus Connections
88 * This class is rarely used directly in D-Bus clients. If you are
89 * writing an D-Bus client, it is often easier to use the
90 * g_bus_own_name(), g_bus_watch_name() or g_bus_watch_proxy() APIs.
93 * The #GDBusConnection type is used for D-Bus connections to remote
94 * peers such as a message buses.
96 * <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>
98 * <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>
100 * <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>
103 /* ---------------------------------------------------------------------------------------------------- */
105 G_LOCK_DEFINE_STATIC (message_bus_lock);
107 static GDBusConnection *the_session_bus = NULL;
108 static GDBusConnection *the_system_bus = NULL;
110 /* ---------------------------------------------------------------------------------------------------- */
113 _g_strv_has_string (const gchar* const * haystack,
118 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
120 if (g_strcmp0 (haystack[n], needle) == 0)
126 /* ---------------------------------------------------------------------------------------------------- */
129 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
131 // TODO: for some reason this doesn't work on Windows
132 #define CONNECTION_ENSURE_LOCK(obj) do { \
133 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
135 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
136 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
141 #define CONNECTION_LOCK(obj) do { \
142 g_mutex_lock ((obj)->priv->lock); \
145 #define CONNECTION_UNLOCK(obj) do { \
146 g_mutex_unlock ((obj)->priv->lock); \
149 struct _GDBusConnectionPrivate
151 /* ------------------------------------------------------------------------ */
152 /* -- General object state ------------------------------------------------ */
153 /* ------------------------------------------------------------------------ */
155 /* object-wide lock */
158 /* A lock used in the init() method of the GInitable interface - see comments
159 * in initable_init() for why a separate lock is needed
163 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
164 * someone calls org.freedesktop.DBus.GetMachineId()
168 /* The underlying stream used for communication */
171 /* The object used for authentication (if any) */
174 /* Set to TRUE if the connection has been closed */
177 /* Last serial used */
180 /* The object used to send/receive message */
183 /* If connected to a message bus, this contains the unique name assigned to
184 * us by the bus (e.g. ":1.42")
186 gchar *bus_unique_name;
188 /* The GUID returned by the other side if we authenticed as a client or
189 * the GUID to use if authenticating as a server
193 /* set to TRUE exactly when initable_init() has finished running */
194 gboolean is_initialized;
196 /* If the connection could not be established during initable_init(), this GError will set */
197 GError *initialization_error;
199 /* The result of g_main_context_get_thread_default() when the object
200 * was created (the GObject _init() function) - this is used for delivery
201 * of the :closed GObject signal.
203 GMainContext *main_context_at_construction;
205 /* construct properties */
207 GDBusConnectionFlags flags;
209 /* Map used for managing method replies */
210 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
212 /* Maps used for managing signal subscription */
213 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
214 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
215 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
217 /* Maps used for managing exported objects and subtrees */
218 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
219 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
220 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
221 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
223 /* Structure used for message filters */
226 /* Whether to exit on close */
227 gboolean exit_on_close;
229 /* Capabilities negotiated during authentication */
230 GDBusCapabilityFlags capabilities;
232 GDBusAuthObserver *authentication_observer;
233 GCredentials *crendentials;
236 typedef struct ExportedObject ExportedObject;
237 static void exported_object_free (ExportedObject *eo);
239 typedef struct ExportedSubtree ExportedSubtree;
240 static void exported_subtree_free (ExportedSubtree *es);
258 PROP_CAPABILITY_FLAGS,
259 PROP_AUTHENTICATION_OBSERVER,
262 static void distribute_signals (GDBusConnection *connection,
263 GDBusMessage *message);
265 static void distribute_method_call (GDBusConnection *connection,
266 GDBusMessage *message);
268 static gboolean handle_generic_unlocked (GDBusConnection *connection,
269 GDBusMessage *message);
272 static void purge_all_signal_subscriptions (GDBusConnection *connection);
273 static void purge_all_filters (GDBusConnection *connection);
275 #define _G_ENSURE_LOCK(name) do { \
276 if (G_UNLIKELY (G_TRYLOCK(name))) \
278 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
279 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
283 static guint signals[LAST_SIGNAL] = { 0 };
285 static void initable_iface_init (GInitableIface *initable_iface);
286 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
288 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
289 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
290 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
294 g_dbus_connection_dispose (GObject *object)
296 GDBusConnection *connection = G_DBUS_CONNECTION (object);
298 G_LOCK (message_bus_lock);
299 //g_debug ("disposing %p", connection);
300 if (connection == the_session_bus)
302 the_session_bus = NULL;
304 else if (connection == the_system_bus)
306 the_system_bus = NULL;
308 if (connection->priv->worker != NULL)
310 _g_dbus_worker_stop (connection->priv->worker);
311 connection->priv->worker = NULL;
313 G_UNLOCK (message_bus_lock);
315 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
316 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
320 g_dbus_connection_finalize (GObject *object)
322 GDBusConnection *connection = G_DBUS_CONNECTION (object);
324 if (connection->priv->authentication_observer != NULL)
325 g_object_unref (connection->priv->authentication_observer);
327 if (connection->priv->auth != NULL)
328 g_object_unref (connection->priv->auth);
330 //g_debug ("finalizing %p", connection);
331 if (connection->priv->stream != NULL)
333 /* We don't really care if closing the stream succeeds or not */
334 g_io_stream_close_async (connection->priv->stream,
336 NULL, /* GCancellable */
337 NULL, /* GAsyncReadyCallback */
338 NULL); /* userdata */
339 g_object_unref (connection->priv->stream);
340 connection->priv->stream = NULL;
343 g_free (connection->priv->address);
345 g_free (connection->priv->guid);
346 g_free (connection->priv->bus_unique_name);
348 if (connection->priv->initialization_error != NULL)
349 g_error_free (connection->priv->initialization_error);
351 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
353 purge_all_signal_subscriptions (connection);
354 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
355 g_hash_table_unref (connection->priv->map_id_to_signal_data);
356 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
358 g_hash_table_unref (connection->priv->map_id_to_ei);
359 g_hash_table_unref (connection->priv->map_object_path_to_eo);
360 g_hash_table_unref (connection->priv->map_id_to_es);
361 g_hash_table_unref (connection->priv->map_object_path_to_es);
363 purge_all_filters (connection);
364 g_ptr_array_unref (connection->priv->filters);
366 if (connection->priv->main_context_at_construction != NULL)
367 g_main_context_unref (connection->priv->main_context_at_construction);
369 g_free (connection->priv->machine_id);
371 g_mutex_free (connection->priv->init_lock);
372 g_mutex_free (connection->priv->lock);
374 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize != NULL)
375 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
379 g_dbus_connection_get_property (GObject *object,
384 GDBusConnection *connection = G_DBUS_CONNECTION (object);
389 g_value_set_object (value, g_dbus_connection_get_stream (connection));
393 g_value_set_string (value, g_dbus_connection_get_guid (connection));
396 case PROP_UNIQUE_NAME:
397 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
401 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
404 case PROP_EXIT_ON_CLOSE:
405 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
408 case PROP_CAPABILITY_FLAGS:
409 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
413 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
419 g_dbus_connection_set_property (GObject *object,
424 GDBusConnection *connection = G_DBUS_CONNECTION (object);
429 connection->priv->stream = g_value_dup_object (value);
433 connection->priv->guid = g_value_dup_string (value);
437 connection->priv->address = g_value_dup_string (value);
441 connection->priv->flags = g_value_get_flags (value);
444 case PROP_EXIT_ON_CLOSE:
445 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
448 case PROP_AUTHENTICATION_OBSERVER:
449 connection->priv->authentication_observer = g_value_dup_object (value);
453 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
459 g_dbus_connection_real_closed (GDBusConnection *connection,
460 gboolean remote_peer_vanished,
463 if (remote_peer_vanished && connection->priv->exit_on_close)
465 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
471 g_dbus_connection_class_init (GDBusConnectionClass *klass)
473 GObjectClass *gobject_class;
475 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
477 gobject_class = G_OBJECT_CLASS (klass);
479 gobject_class->finalize = g_dbus_connection_finalize;
480 gobject_class->dispose = g_dbus_connection_dispose;
481 gobject_class->set_property = g_dbus_connection_set_property;
482 gobject_class->get_property = g_dbus_connection_get_property;
484 klass->closed = g_dbus_connection_real_closed;
487 * GDBusConnection:stream:
489 * The underlying #GIOStream used for I/O.
493 g_object_class_install_property (gobject_class,
495 g_param_spec_object ("stream",
497 _("The underlying streams used for I/O"),
501 G_PARAM_CONSTRUCT_ONLY |
502 G_PARAM_STATIC_NAME |
503 G_PARAM_STATIC_BLURB |
504 G_PARAM_STATIC_NICK));
507 * GDBusConnection:address:
509 * A D-Bus address specifying potential endpoints that can be used
510 * when establishing the connection.
514 g_object_class_install_property (gobject_class,
516 g_param_spec_string ("address",
518 _("D-Bus address specifying potential socket endpoints"),
521 G_PARAM_CONSTRUCT_ONLY |
522 G_PARAM_STATIC_NAME |
523 G_PARAM_STATIC_BLURB |
524 G_PARAM_STATIC_NICK));
527 * GDBusConnection:flags:
529 * Flags from the #GDBusConnectionFlags enumeration.
533 g_object_class_install_property (gobject_class,
535 g_param_spec_flags ("flags",
538 G_TYPE_DBUS_CONNECTION_FLAGS,
539 G_DBUS_CONNECTION_FLAGS_NONE,
541 G_PARAM_CONSTRUCT_ONLY |
542 G_PARAM_STATIC_NAME |
543 G_PARAM_STATIC_BLURB |
544 G_PARAM_STATIC_NICK));
547 * GDBusConnection:guid:
549 * The GUID of the peer performing the role of server when
552 * If you are constructing a #GDBusConnection and pass
553 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
554 * #GDBusConnection:flags property then you MUST also set this
555 * property to a valid guid.
557 * If you are constructing a #GDBusConnection and pass
558 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
559 * #GDBusConnection:flags property you will be able to read the GUID
560 * of the other peer here after the connection has been succesfully
565 g_object_class_install_property (gobject_class,
567 g_param_spec_string ("guid",
569 _("GUID of the server peer"),
573 G_PARAM_CONSTRUCT_ONLY |
574 G_PARAM_STATIC_NAME |
575 G_PARAM_STATIC_BLURB |
576 G_PARAM_STATIC_NICK));
579 * GDBusConnection:unique-name:
581 * The unique name as assigned by the message bus or %NULL if the
582 * connection is not open or not a message bus connection.
586 g_object_class_install_property (gobject_class,
588 g_param_spec_string ("unique-name",
590 _("Unique name of bus connection"),
593 G_PARAM_STATIC_NAME |
594 G_PARAM_STATIC_BLURB |
595 G_PARAM_STATIC_NICK));
598 * GDBusConnection:closed:
600 * A boolean specifying whether the connection has been closed.
604 g_object_class_install_property (gobject_class,
606 g_param_spec_boolean ("closed",
608 _("Whether the connection is closed"),
611 G_PARAM_STATIC_NAME |
612 G_PARAM_STATIC_BLURB |
613 G_PARAM_STATIC_NICK));
616 * GDBusConnection:exit-on-close:
618 * A boolean specifying whether the process will be terminated (by
619 * calling <literal>raise(SIGTERM)</literal>) if the connection
620 * is closed by the remote peer.
624 g_object_class_install_property (gobject_class,
626 g_param_spec_boolean ("exit-on-close",
628 _("Whether the process is terminated when the connection is closed"),
632 G_PARAM_STATIC_NAME |
633 G_PARAM_STATIC_BLURB |
634 G_PARAM_STATIC_NICK));
637 * GDBusConnection:capabilities:
639 * Flags from the #GDBusCapabilityFlags enumeration
640 * representing connection features negotiated with the other peer.
644 g_object_class_install_property (gobject_class,
645 PROP_CAPABILITY_FLAGS,
646 g_param_spec_flags ("capabilities",
649 G_TYPE_DBUS_CAPABILITY_FLAGS,
650 G_DBUS_CAPABILITY_FLAGS_NONE,
652 G_PARAM_STATIC_NAME |
653 G_PARAM_STATIC_BLURB |
654 G_PARAM_STATIC_NICK));
657 * GDBusConnection:authentication-observer:
659 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
663 g_object_class_install_property (gobject_class,
664 PROP_AUTHENTICATION_OBSERVER,
665 g_param_spec_object ("authentication-observer",
666 _("Authentication Observer"),
667 _("Object used to assist in the authentication process"),
668 G_TYPE_DBUS_AUTH_OBSERVER,
670 G_PARAM_CONSTRUCT_ONLY |
671 G_PARAM_STATIC_NAME |
672 G_PARAM_STATIC_BLURB |
673 G_PARAM_STATIC_NICK));
676 * GDBusConnection::closed:
677 * @connection: The #GDBusConnection emitting the signal.
678 * @remote_peer_vanished: %TRUE if @connection is closed because the
679 * remote peer closed its end of the connection.
680 * @error: A #GError with more details about the event or %NULL.
682 * Emitted when the connection is closed.
684 * The cause of this event can be
687 * If g_dbus_connection_close() is called. In this case
688 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
691 * If the remote peer closes the connection. In this case
692 * @remote_peer_vanished is set to %TRUE and @error is set.
695 * If the remote peer sends invalid or malformed data. In this
696 * case @remote_peer_vanished is set to %FALSE and @error
701 * Upon receiving this signal, you should give up your reference to
702 * @connection. You are guaranteed that this signal is emitted only
707 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
708 G_TYPE_DBUS_CONNECTION,
710 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
713 _gio_marshal_VOID__BOOLEAN_BOXED,
721 g_dbus_connection_init (GDBusConnection *connection)
723 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
725 connection->priv->lock = g_mutex_new ();
726 connection->priv->init_lock = g_mutex_new ();
728 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
730 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
732 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
734 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
739 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
742 (GDestroyNotify) exported_object_free);
744 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
747 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
750 (GDestroyNotify) exported_subtree_free);
752 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
755 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
756 if (connection->priv->main_context_at_construction != NULL)
757 g_main_context_ref (connection->priv->main_context_at_construction);
759 connection->priv->filters = g_ptr_array_new ();
763 g_dbus_connection_get_stream (GDBusConnection *connection)
765 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
766 return connection->priv->stream;
771 * g_dbus_connection_is_closed:
772 * @connection: A #GDBusConnection.
774 * Gets whether @connection is closed.
776 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
781 g_dbus_connection_is_closed (GDBusConnection *connection)
783 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
784 return connection->priv->closed;
788 * g_dbus_connection_get_capabilities:
789 * @connection: A #GDBusConnection.
791 * Gets the capabilities negotiated with the remote peer
793 * Returns: One or more flags from the #GDBusCapabilityFlags enumeration.
798 g_dbus_connection_get_capabilities (GDBusConnection *connection)
800 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
801 return connection->priv->capabilities;
805 /* ---------------------------------------------------------------------------------------------------- */
809 GDBusConnection *connection;
811 gboolean remote_peer_vanished;
815 emit_closed_data_free (EmitClosedData *data)
817 g_object_unref (data->connection);
818 if (data->error != NULL)
819 g_error_free (data->error);
824 emit_closed_in_idle (gpointer user_data)
826 EmitClosedData *data = user_data;
829 g_object_notify (G_OBJECT (data->connection), "closed");
830 g_signal_emit (data->connection,
831 signals[CLOSED_SIGNAL],
833 data->remote_peer_vanished,
839 /* Can be called from any thread, must hold lock */
841 set_closed_unlocked (GDBusConnection *connection,
842 gboolean remote_peer_vanished,
845 GSource *idle_source;
846 EmitClosedData *data;
848 CONNECTION_ENSURE_LOCK (connection);
850 g_assert (!connection->priv->closed);
852 connection->priv->closed = TRUE;
854 data = g_new0 (EmitClosedData, 1);
855 data->connection = g_object_ref (connection);
856 data->remote_peer_vanished = remote_peer_vanished;
857 data->error = error != NULL ? g_error_copy (error) : NULL;
859 idle_source = g_idle_source_new ();
860 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
861 g_source_set_callback (idle_source,
864 (GDestroyNotify) emit_closed_data_free);
865 g_source_attach (idle_source, connection->priv->main_context_at_construction);
866 g_source_unref (idle_source);
869 /* ---------------------------------------------------------------------------------------------------- */
872 * g_dbus_connection_close:
873 * @connection: A #GDBusConnection.
875 * Closes @connection. Note that this never causes the process to
876 * exit (this might only happen if the other end of a shared message
877 * bus connection disconnects).
879 * If @connection is already closed, this method does nothing.
884 g_dbus_connection_close (GDBusConnection *connection)
886 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
888 CONNECTION_LOCK (connection);
889 if (!connection->priv->closed)
891 GError *error = NULL;
893 /* TODO: do this async */
894 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
895 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
897 g_warning ("Error closing stream: %s", error->message);
898 g_error_free (error);
901 set_closed_unlocked (connection, FALSE, NULL);
903 CONNECTION_UNLOCK (connection);
906 /* ---------------------------------------------------------------------------------------------------- */
909 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
910 GDBusMessage *message,
911 volatile guint32 *out_serial,
916 guint32 serial_to_use;
919 CONNECTION_ENSURE_LOCK (connection);
921 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
922 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
924 /* TODO: check all necessary headers are present */
929 if (out_serial != NULL)
932 if (connection->priv->closed)
934 g_set_error_literal (error,
937 _("The connection is closed"));
941 blob = g_dbus_message_to_blob (message,
947 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
952 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
955 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
958 g_assert_not_reached ();
963 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
964 blob_size, serial_to_use, connection);
965 g_printerr ("----\n");
966 hexdump (blob, blob_size);
967 g_printerr ("----\n");
970 /* TODO: use connection->priv->auth to encode the blob */
972 if (out_serial != NULL)
974 *out_serial = serial_to_use;
976 g_dbus_message_set_serial (message, serial_to_use);
978 _g_dbus_worker_send_message (connection->priv->worker,
982 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
993 * g_dbus_connection_send_message:
994 * @connection: A #GDBusConnection.
995 * @message: A #GDBusMessage
996 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
997 * @error: Return location for error or %NULL.
999 * Asynchronously sends @message to the peer represented by @connection.
1001 * If @out_serial is not %NULL, then the serial number assigned to
1002 * @message by @connection will be written to this location prior to
1003 * submitting the message to the underlying transport.
1005 * If @connection is closed then the operation will fail with
1006 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1007 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1008 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1010 * See <xref linkend="gdbus-server"/> and <xref
1011 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1012 * low-level API to send and receive UNIX file descriptors.
1014 * Returns: %TRUE if the message was well-formed and queued for
1015 * transmission, %FALSE if @error is set.
1020 g_dbus_connection_send_message (GDBusConnection *connection,
1021 GDBusMessage *message,
1022 volatile guint32 *out_serial,
1027 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1028 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1029 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1031 CONNECTION_LOCK (connection);
1032 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1033 CONNECTION_UNLOCK (connection);
1037 /* ---------------------------------------------------------------------------------------------------- */
1041 volatile gint ref_count;
1042 GDBusConnection *connection;
1044 GSimpleAsyncResult *simple;
1046 GMainContext *main_context;
1048 GCancellable *cancellable;
1050 gulong cancellable_handler_id;
1052 GSource *timeout_source;
1057 static SendMessageData *
1058 send_message_data_ref (SendMessageData *data)
1060 g_atomic_int_inc (&data->ref_count);
1065 send_message_data_unref (SendMessageData *data)
1067 if (g_atomic_int_dec_and_test (&data->ref_count))
1069 g_assert (data->timeout_source == NULL);
1070 g_assert (data->simple == NULL);
1071 g_assert (data->cancellable_handler_id == 0);
1072 g_object_unref (data->connection);
1073 if (data->cancellable != NULL)
1074 g_object_unref (data->cancellable);
1075 if (data->main_context != NULL)
1076 g_main_context_unref (data->main_context);
1081 /* ---------------------------------------------------------------------------------------------------- */
1083 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1085 send_message_with_reply_deliver (SendMessageData *data)
1087 CONNECTION_ENSURE_LOCK (data->connection);
1089 g_assert (!data->delivered);
1091 data->delivered = TRUE;
1093 g_simple_async_result_complete_in_idle (data->simple);
1094 g_object_unref (data->simple);
1095 data->simple = NULL;
1097 if (data->timeout_source != NULL)
1099 g_source_destroy (data->timeout_source);
1100 data->timeout_source = NULL;
1102 if (data->cancellable_handler_id > 0)
1104 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1105 data->cancellable_handler_id = 0;
1108 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1109 GUINT_TO_POINTER (data->serial)));
1111 send_message_data_unref (data);
1114 /* ---------------------------------------------------------------------------------------------------- */
1116 /* must hold lock */
1118 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1119 GDBusMessage *reply)
1121 if (data->delivered)
1124 g_simple_async_result_set_op_res_gpointer (data->simple,
1125 g_object_ref (reply),
1128 send_message_with_reply_deliver (data);
1134 /* ---------------------------------------------------------------------------------------------------- */
1137 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1139 SendMessageData *data = user_data;
1141 CONNECTION_LOCK (data->connection);
1142 if (data->delivered)
1145 g_simple_async_result_set_error (data->simple,
1147 G_IO_ERROR_CANCELLED,
1148 _("Operation was cancelled"));
1150 send_message_with_reply_deliver (data);
1153 CONNECTION_UNLOCK (data->connection);
1157 /* Can be called from any thread with or without lock held */
1159 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1162 SendMessageData *data = user_data;
1163 GSource *idle_source;
1165 /* postpone cancellation to idle handler since we may be called directly
1166 * via g_cancellable_connect() (e.g. holding lock)
1168 idle_source = g_idle_source_new ();
1169 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1170 g_source_set_callback (idle_source,
1171 send_message_with_reply_cancelled_idle_cb,
1172 send_message_data_ref (data),
1173 (GDestroyNotify) send_message_data_unref);
1174 g_source_attach (idle_source, data->main_context);
1175 g_source_unref (idle_source);
1178 /* ---------------------------------------------------------------------------------------------------- */
1181 send_message_with_reply_timeout_cb (gpointer user_data)
1183 SendMessageData *data = user_data;
1185 CONNECTION_LOCK (data->connection);
1186 if (data->delivered)
1189 g_simple_async_result_set_error (data->simple,
1191 G_IO_ERROR_TIMED_OUT,
1192 _("Timeout was reached"));
1194 send_message_with_reply_deliver (data);
1197 CONNECTION_UNLOCK (data->connection);
1202 /* ---------------------------------------------------------------------------------------------------- */
1205 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1206 GDBusMessage *message,
1208 volatile guint32 *out_serial,
1209 GCancellable *cancellable,
1210 GAsyncReadyCallback callback,
1213 GSimpleAsyncResult *simple;
1214 SendMessageData *data;
1216 volatile guint32 serial;
1220 if (out_serial == NULL)
1221 out_serial = &serial;
1223 if (timeout_msec == -1)
1224 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1226 simple = g_simple_async_result_new (G_OBJECT (connection),
1229 g_dbus_connection_send_message_with_reply);
1231 if (g_cancellable_is_cancelled (cancellable))
1233 g_simple_async_result_set_error (simple,
1235 G_IO_ERROR_CANCELLED,
1236 _("Operation was cancelled"));
1237 g_simple_async_result_complete_in_idle (simple);
1238 g_object_unref (simple);
1242 if (connection->priv->closed)
1244 g_simple_async_result_set_error (simple,
1247 _("The connection is closed"));
1248 g_simple_async_result_complete_in_idle (simple);
1249 g_object_unref (simple);
1254 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1256 g_simple_async_result_set_from_error (simple, error);
1257 g_simple_async_result_complete_in_idle (simple);
1258 g_object_unref (simple);
1262 data = g_new0 (SendMessageData, 1);
1263 data->ref_count = 1;
1264 data->connection = g_object_ref (connection);
1265 data->simple = simple;
1266 data->serial = *out_serial;
1267 data->main_context = g_main_context_get_thread_default ();
1268 if (data->main_context != NULL)
1269 g_main_context_ref (data->main_context);
1271 if (cancellable != NULL)
1273 data->cancellable = g_object_ref (cancellable);
1274 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1275 G_CALLBACK (send_message_with_reply_cancelled_cb),
1276 send_message_data_ref (data),
1277 (GDestroyNotify) send_message_data_unref);
1278 g_object_set_data_full (G_OBJECT (simple),
1280 g_object_ref (cancellable),
1281 (GDestroyNotify) g_object_unref);
1284 data->timeout_source = g_timeout_source_new (timeout_msec);
1285 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1286 g_source_set_callback (data->timeout_source,
1287 send_message_with_reply_timeout_cb,
1288 send_message_data_ref (data),
1289 (GDestroyNotify) send_message_data_unref);
1290 g_source_attach (data->timeout_source, data->main_context);
1291 g_source_unref (data->timeout_source);
1293 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1294 GUINT_TO_POINTER (*out_serial),
1302 * g_dbus_connection_send_message_with_reply:
1303 * @connection: A #GDBusConnection.
1304 * @message: A #GDBusMessage.
1305 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1306 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1307 * @cancellable: A #GCancellable or %NULL.
1308 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1309 * care about the result.
1310 * @user_data: The data to pass to @callback.
1312 * Asynchronously sends @message to the peer represented by @connection.
1314 * If @out_serial is not %NULL, then the serial number assigned to
1315 * @message by @connection will be written to this location prior to
1316 * submitting the message to the underlying transport.
1318 * If @connection is closed then the operation will fail with
1319 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1320 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1321 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1323 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1324 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1325 * of the thread you are calling this method from. You can then call
1326 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1327 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1329 * See <xref linkend="gdbus-server"/> and <xref
1330 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1331 * low-level API to send and receive UNIX file descriptors.
1336 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1337 GDBusMessage *message,
1339 volatile guint32 *out_serial,
1340 GCancellable *cancellable,
1341 GAsyncReadyCallback callback,
1344 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1345 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1346 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1348 CONNECTION_LOCK (connection);
1349 g_dbus_connection_send_message_with_reply_unlocked (connection,
1356 CONNECTION_UNLOCK (connection);
1360 * g_dbus_connection_send_message_with_reply_finish:
1361 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1362 * @error: Return location for error or %NULL.
1364 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1366 * Note that @error is only set if a local in-process error
1367 * occured. That is to say that the returned #GDBusMessage object may
1368 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1369 * g_dbus_message_to_gerror() to transcode this to a #GError.
1371 * See <xref linkend="gdbus-server"/> and <xref
1372 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1373 * low-level API to send and receive UNIX file descriptors.
1375 * Returns: A #GDBusMessage or %NULL if @error is set.
1380 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1384 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1385 GDBusMessage *reply;
1386 GCancellable *cancellable;
1388 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1389 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1393 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1395 if (g_simple_async_result_propagate_error (simple, error))
1398 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1399 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1400 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1402 g_object_unref (reply);
1404 g_set_error_literal (error,
1406 G_IO_ERROR_CANCELLED,
1407 _("Operation was cancelled"));
1413 /* ---------------------------------------------------------------------------------------------------- */
1418 GMainContext *context;
1420 } SendMessageSyncData;
1423 send_message_with_reply_sync_cb (GDBusConnection *connection,
1427 SendMessageSyncData *data = user_data;
1428 data->res = g_object_ref (res);
1429 g_main_loop_quit (data->loop);
1433 * g_dbus_connection_send_message_with_reply_sync:
1434 * @connection: A #GDBusConnection.
1435 * @message: A #GDBusMessage.
1436 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1437 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1438 * @cancellable: A #GCancellable or %NULL.
1439 * @error: Return location for error or %NULL.
1441 * Synchronously sends @message to the peer represented by @connection
1442 * and blocks the calling thread until a reply is received or the
1443 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1444 * for the asynchronous version of this method.
1446 * If @out_serial is not %NULL, then the serial number assigned to
1447 * @message by @connection will be written to this location prior to
1448 * submitting the message to the underlying transport.
1450 * If @connection is closed then the operation will fail with
1451 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1452 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1453 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1455 * Note that @error is only set if a local in-process error
1456 * occured. That is to say that the returned #GDBusMessage object may
1457 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1458 * g_dbus_message_to_gerror() to transcode this to a #GError.
1460 * See <xref linkend="gdbus-server"/> and <xref
1461 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1462 * low-level API to send and receive UNIX file descriptors.
1464 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1469 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1470 GDBusMessage *message,
1472 volatile guint32 *out_serial,
1473 GCancellable *cancellable,
1476 SendMessageSyncData *data;
1477 GDBusMessage *reply;
1479 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1480 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1481 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1482 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1484 data = g_new0 (SendMessageSyncData, 1);
1485 data->context = g_main_context_new ();
1486 data->loop = g_main_loop_new (data->context, FALSE);
1488 g_main_context_push_thread_default (data->context);
1490 g_dbus_connection_send_message_with_reply (connection,
1495 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1497 g_main_loop_run (data->loop);
1498 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1502 g_main_context_pop_thread_default (data->context);
1504 g_main_context_unref (data->context);
1505 g_main_loop_unref (data->loop);
1506 g_object_unref (data->res);
1512 /* ---------------------------------------------------------------------------------------------------- */
1516 GDBusMessageFilterFunction func;
1523 GDBusMessageFilterFunction filter_function;
1525 GDestroyNotify user_data_free_func;
1528 /* Called in worker's thread - we must not block */
1530 on_worker_message_received (GDBusWorker *worker,
1531 GDBusMessage *message,
1534 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1535 FilterCallback *filters;
1536 gboolean consumed_by_filter;
1540 //g_debug ("in on_worker_message_received");
1542 g_object_ref (connection);
1544 /* First collect the set of callback functions */
1545 CONNECTION_LOCK (connection);
1546 num_filters = connection->priv->filters->len;
1547 filters = g_new0 (FilterCallback, num_filters);
1548 for (n = 0; n < num_filters; n++)
1550 FilterData *data = connection->priv->filters->pdata[n];
1551 filters[n].func = data->filter_function;
1552 filters[n].user_data = data->user_data;
1554 CONNECTION_UNLOCK (connection);
1556 /* the call the filters in order (without holding the lock) */
1557 consumed_by_filter = FALSE;
1558 for (n = 0; n < num_filters; n++)
1560 consumed_by_filter = filters[n].func (connection,
1562 filters[n].user_data);
1563 if (consumed_by_filter)
1567 /* Standard dispatch unless the filter ate the message */
1568 if (!consumed_by_filter)
1570 GDBusMessageType message_type;
1572 message_type = g_dbus_message_get_message_type (message);
1573 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1575 guint32 reply_serial;
1576 SendMessageData *send_message_data;
1578 reply_serial = g_dbus_message_get_reply_serial (message);
1579 CONNECTION_LOCK (connection);
1580 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1581 GUINT_TO_POINTER (reply_serial));
1582 if (send_message_data != NULL)
1584 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1585 send_message_data_deliver_reply_unlocked (send_message_data, message);
1589 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1591 CONNECTION_UNLOCK (connection);
1593 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1595 CONNECTION_LOCK (connection);
1596 distribute_signals (connection, message);
1597 CONNECTION_UNLOCK (connection);
1599 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1601 CONNECTION_LOCK (connection);
1602 distribute_method_call (connection, message);
1603 CONNECTION_UNLOCK (connection);
1607 g_object_unref (connection);
1611 /* Called in worker's thread - we must not block */
1613 on_worker_closed (GDBusWorker *worker,
1614 gboolean remote_peer_vanished,
1618 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1620 //g_debug ("in on_worker_closed: %s", error->message);
1622 CONNECTION_LOCK (connection);
1623 if (!connection->priv->closed)
1624 set_closed_unlocked (connection, remote_peer_vanished, error);
1625 CONNECTION_UNLOCK (connection);
1628 /* ---------------------------------------------------------------------------------------------------- */
1630 /* Determines the biggest set of capabilities we can support on this connection */
1631 static GDBusCapabilityFlags
1632 get_offered_capabilities_max (GDBusConnection *connection)
1634 GDBusCapabilityFlags ret;
1635 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1637 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1639 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1647 initable_init (GInitable *initable,
1648 GCancellable *cancellable,
1651 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1654 /* This method needs to be idempotent to work with the singleton
1655 * pattern. See the docs for g_initable_init(). We implement this by
1658 * Unfortunately we can't use the main lock since the on_worker_*()
1659 * callbacks above needs the lock during initialization (for message
1660 * bus connections we do a synchronous Hello() call on the bus).
1662 g_mutex_lock (connection->priv->init_lock);
1666 if (connection->priv->is_initialized)
1668 if (connection->priv->stream != NULL)
1671 g_assert (connection->priv->initialization_error != NULL);
1674 g_assert (connection->priv->initialization_error == NULL);
1676 /* The user can pass multiple (but mutally exclusive) construct
1679 * - stream (of type GIOStream)
1680 * - address (of type gchar*)
1682 * At the end of the day we end up with a non-NULL GIOStream
1683 * object in connection->priv->stream.
1685 if (connection->priv->address != NULL)
1687 g_assert (connection->priv->stream == NULL);
1689 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1690 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1692 g_set_error_literal (error,
1694 G_IO_ERROR_INVALID_ARGUMENT,
1695 _("Unsupported flags encountered when constructing a client-side connection"));
1699 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1700 NULL, /* TODO: out_guid */
1702 &connection->priv->initialization_error);
1703 if (connection->priv->stream == NULL)
1706 else if (connection->priv->stream != NULL)
1712 g_assert_not_reached ();
1715 /* Authenticate the connection */
1716 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1718 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1719 g_assert (connection->priv->guid != NULL);
1720 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1721 if (!_g_dbus_auth_run_server (connection->priv->auth,
1722 connection->priv->authentication_observer,
1723 connection->priv->guid,
1724 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1725 get_offered_capabilities_max (connection),
1726 &connection->priv->capabilities,
1727 &connection->priv->crendentials,
1729 &connection->priv->initialization_error))
1732 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1734 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1735 g_assert (connection->priv->guid == NULL);
1736 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1737 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1738 get_offered_capabilities_max (connection),
1739 &connection->priv->capabilities,
1741 &connection->priv->initialization_error);
1742 if (connection->priv->guid == NULL)
1746 if (connection->priv->authentication_observer != NULL)
1748 g_object_unref (connection->priv->authentication_observer);
1749 connection->priv->authentication_observer = NULL;
1752 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1754 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1758 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1762 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1764 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1767 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1768 connection->priv->capabilities,
1769 on_worker_message_received,
1773 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1774 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1776 GVariant *hello_result;
1779 hello_result = g_dbus_connection_invoke_method_sync (connection,
1780 "org.freedesktop.DBus", /* name */
1781 "/org/freedesktop/DBus", /* path */
1782 "org.freedesktop.DBus", /* interface */
1784 NULL, /* parameters */
1785 G_DBUS_INVOKE_METHOD_FLAGS_NONE,
1787 NULL, /* TODO: cancellable */
1788 &connection->priv->initialization_error);
1789 if (hello_result == NULL)
1792 g_variant_get (hello_result, "(s)", &s);
1793 connection->priv->bus_unique_name = g_strdup (s);
1794 g_variant_unref (hello_result);
1795 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1798 connection->priv->is_initialized = TRUE;
1804 g_assert (connection->priv->initialization_error != NULL);
1805 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1808 g_mutex_unlock (connection->priv->init_lock);
1814 initable_iface_init (GInitableIface *initable_iface)
1816 initable_iface->init = initable_init;
1819 /* ---------------------------------------------------------------------------------------------------- */
1822 async_init_thread (GSimpleAsyncResult *res,
1824 GCancellable *cancellable)
1826 GError *error = NULL;
1828 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1830 g_simple_async_result_set_from_error (res, error);
1831 g_error_free (error);
1836 async_initable_init_async (GAsyncInitable *initable,
1838 GCancellable *cancellable,
1839 GAsyncReadyCallback callback,
1842 GSimpleAsyncResult *res;
1844 g_return_if_fail (G_IS_INITABLE (initable));
1846 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1847 async_initable_init_async);
1848 g_simple_async_result_run_in_thread (res, async_init_thread,
1849 io_priority, cancellable);
1850 g_object_unref (res);
1854 async_initable_init_finish (GAsyncInitable *initable,
1858 return TRUE; /* Errors handled by base impl */
1862 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1864 /* We basically just want to use GIO's default implementation - though that one is
1865 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1867 async_initable_iface->init_async = async_initable_init_async;
1868 async_initable_iface->init_finish = async_initable_init_finish;
1871 /* ---------------------------------------------------------------------------------------------------- */
1874 * g_dbus_connection_new:
1875 * @stream: A #GIOStream.
1876 * @guid: The GUID to use if a authenticating as a server or %NULL.
1877 * @flags: Flags describing how to make the connection.
1878 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1879 * @cancellable: A #GCancellable or %NULL.
1880 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1881 * @user_data: The data to pass to @callback.
1883 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1884 * with the end represented by @stream.
1886 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1887 * @auth_observer (if not %NULL) is used to assist in the client
1888 * authentication process.
1890 * When the operation is finished, @callback will be invoked. You can
1891 * then call g_dbus_connection_new_finish() to get the result of the
1894 * This is a asynchronous failable constructor. See
1895 * g_dbus_connection_new_sync() for the synchronous
1901 g_dbus_connection_new (GIOStream *stream,
1903 GDBusConnectionFlags flags,
1904 GDBusAuthObserver *authentication_observer,
1905 GCancellable *cancellable,
1906 GAsyncReadyCallback callback,
1909 g_return_if_fail (G_IS_IO_STREAM (stream));
1910 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1918 "authentication-observer", authentication_observer,
1923 * g_dbus_connection_new_finish:
1924 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1925 * @error: Return location for error or %NULL.
1927 * Finishes an operation started with g_dbus_connection_new().
1929 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1934 g_dbus_connection_new_finish (GAsyncResult *res,
1938 GObject *source_object;
1940 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1941 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1943 source_object = g_async_result_get_source_object (res);
1944 g_assert (source_object != NULL);
1945 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1948 g_object_unref (source_object);
1950 return G_DBUS_CONNECTION (object);
1956 * g_dbus_connection_new_sync:
1957 * @stream: A #GIOStream.
1958 * @guid: The GUID to use if a authenticating as a server or %NULL.
1959 * @flags: Flags describing how to make the connection.
1960 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1961 * @cancellable: A #GCancellable or %NULL.
1962 * @error: Return location for error or %NULL.
1964 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1965 * with the end represented by @stream.
1967 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1968 * @auth_observer (if not %NULL) is used to assist in the client
1969 * authentication process.
1971 * This is a synchronous failable constructor. See
1972 * g_dbus_connection_new() for the asynchronous version.
1974 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1979 g_dbus_connection_new_sync (GIOStream *stream,
1981 GDBusConnectionFlags flags,
1982 GDBusAuthObserver *authentication_observer,
1983 GCancellable *cancellable,
1986 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1987 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1988 return g_initable_new (G_TYPE_DBUS_CONNECTION,
1994 "authentication-observer", authentication_observer,
1998 /* ---------------------------------------------------------------------------------------------------- */
2001 * g_dbus_connection_new_for_address:
2002 * @address: A D-Bus address.
2003 * @flags: Flags describing how to make the connection.
2004 * @cancellable: A #GCancellable or %NULL.
2005 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2006 * @user_data: The data to pass to @callback.
2008 * Asynchronously connects and sets up a D-Bus client connection for
2009 * exchanging D-Bus messages with an endpoint specified by @address
2010 * which must be in the D-Bus address format.
2012 * This constructor can only be used to initiate client-side
2013 * connections - use g_dbus_connection_new() if you need to act as the
2014 * server. In particular, @flags cannot contain the
2015 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2016 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2018 * When the operation is finished, @callback will be invoked. You can
2019 * then call g_dbus_connection_new_finish() to get the result of the
2022 * This is a asynchronous failable constructor. See
2023 * g_dbus_connection_new_for_address_sync() for the synchronous
2029 g_dbus_connection_new_for_address (const gchar *address,
2030 GDBusConnectionFlags flags,
2031 GCancellable *cancellable,
2032 GAsyncReadyCallback callback,
2035 g_return_if_fail (address != NULL);
2036 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2047 * g_dbus_connection_new_for_address_finish:
2048 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2049 * @error: Return location for error or %NULL.
2051 * Finishes an operation started with g_dbus_connection_new_for_address().
2053 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2058 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2062 GObject *source_object;
2064 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2065 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2067 source_object = g_async_result_get_source_object (res);
2068 g_assert (source_object != NULL);
2069 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2072 g_object_unref (source_object);
2074 return G_DBUS_CONNECTION (object);
2080 * g_dbus_connection_new_for_address_sync:
2081 * @address: A D-Bus address.
2082 * @flags: Flags describing how to make the connection.
2083 * @cancellable: A #GCancellable or %NULL.
2084 * @error: Return location for error or %NULL.
2086 * Synchronously connects and sets up a D-Bus client connection for
2087 * exchanging D-Bus messages with an endpoint specified by @address
2088 * which must be in the D-Bus address format.
2090 * This constructor can only be used to initiate client-side
2091 * connections - use g_dbus_connection_new_sync() if you need to act
2092 * as the server. In particular, @flags cannot contain the
2093 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2094 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2096 * This is a synchronous failable constructor. See
2097 * g_dbus_connection_new_for_address() for the asynchronous version.
2099 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2104 g_dbus_connection_new_for_address_sync (const gchar *address,
2105 GDBusConnectionFlags flags,
2106 GCancellable *cancellable,
2109 g_return_val_if_fail (address != NULL, NULL);
2110 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2111 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2119 /* ---------------------------------------------------------------------------------------------------- */
2122 * g_dbus_connection_set_exit_on_close:
2123 * @connection: A #GDBusConnection.
2124 * @exit_on_close: Whether the process should be terminated
2125 * when @connection is closed by the remote peer.
2127 * Sets whether the process should be terminated when @connection is
2128 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2134 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2135 gboolean exit_on_close)
2137 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2138 connection->priv->exit_on_close = exit_on_close;
2142 * g_dbus_connection_get_exit_on_close:
2143 * @connection: A #GDBusConnection.
2145 * Gets whether the process is terminated when @connection is
2146 * closed by the remote peer. See
2147 * #GDBusConnection:exit-on-close for more details.
2149 * Returns: Whether the process is terminated when @connection is
2150 * closed by the remote peer.
2155 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2157 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2158 return connection->priv->exit_on_close;
2162 * g_dbus_connection_get_guid:
2163 * @connection: A #GDBusConnection.
2165 * The GUID of the peer performing the role of server when
2166 * authenticating. See #GDBusConnection:guid for more details.
2168 * Returns: The GUID. Do not free this string, it is owned by
2174 g_dbus_connection_get_guid (GDBusConnection *connection)
2176 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2177 return connection->priv->guid;
2181 * g_dbus_connection_get_unique_name:
2182 * @connection: A #GDBusConnection.
2184 * Gets the unique name of @connection as assigned by the message
2185 * bus. This can also be used to figure out if @connection is a
2186 * message bus connection.
2188 * Returns: The unique name or %NULL if @connection is not a message
2189 * bus connection. Do not free this string, it is owned by
2195 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2197 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2198 return connection->priv->bus_unique_name;
2202 * g_dbus_connection_get_peer_credentials:
2203 * @connection: A #GDBusConnection.
2205 * Gets the credentials of the authenticated peer. This will always
2206 * return %NULL unless @connection acted as a server
2207 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2208 * when set up and the client passed credentials as part of the
2209 * authentication process.
2211 * In a message bus setup, the message bus is always the server and
2212 * each application is a client. So this method will always return
2213 * %NULL for message bus clients.
2215 * Returns: A #GCredentials or %NULL if not available. Do not free
2216 * this object, it is owned by @connection.
2221 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2223 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2224 return connection->priv->crendentials;
2227 /* ---------------------------------------------------------------------------------------------------- */
2229 static guint _global_filter_id = 1;
2232 * g_dbus_connection_add_filter:
2233 * @connection: A #GDBusConnection.
2234 * @filter_function: A filter function.
2235 * @user_data: User data to pass to @filter_function.
2236 * @user_data_free_func: Function to free @user_data with when filter
2237 * is removed or %NULL.
2239 * Adds a message filter. Filters are handlers that are run on all
2240 * incoming messages, prior to standard dispatch. Filters are run in
2241 * the order that they were added. The same handler can be added as a
2242 * filter more than once, in which case it will be run more than once.
2243 * Filters added during a filter callback won't be run on the message
2246 * Note that filters are run in a dedicated message handling thread so
2247 * they can't block and, generally, can't do anything but signal a
2248 * worker thread. Also note that filters are rarely needed - use API
2249 * such as g_dbus_connection_send_message_with_reply(),
2250 * g_dbus_connection_signal_subscribe() or
2251 * g_dbus_connection_invoke_method() instead.
2253 * Returns: A filter identifier that can be used with
2254 * g_dbus_connection_remove_filter().
2259 g_dbus_connection_add_filter (GDBusConnection *connection,
2260 GDBusMessageFilterFunction filter_function,
2262 GDestroyNotify user_data_free_func)
2266 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2267 g_return_val_if_fail (filter_function != NULL, 0);
2269 CONNECTION_LOCK (connection);
2270 data = g_new0 (FilterData, 1);
2271 data->id = _global_filter_id++; /* TODO: overflow etc. */
2272 data->filter_function = filter_function;
2273 data->user_data = user_data;
2274 data->user_data_free_func = user_data_free_func;
2275 g_ptr_array_add (connection->priv->filters, data);
2276 CONNECTION_UNLOCK (connection);
2281 /* only called from finalize(), removes all filters */
2283 purge_all_filters (GDBusConnection *connection)
2286 for (n = 0; n < connection->priv->filters->len; n++)
2288 FilterData *data = connection->priv->filters->pdata[n];
2289 if (data->user_data_free_func != NULL)
2290 data->user_data_free_func (data->user_data);
2296 g_dbus_connection_remove_filter (GDBusConnection *connection,
2300 FilterData *to_destroy;
2302 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2304 CONNECTION_LOCK (connection);
2306 for (n = 0; n < connection->priv->filters->len; n++)
2308 FilterData *data = connection->priv->filters->pdata[n];
2309 if (data->id == filter_id)
2311 g_ptr_array_remove_index (connection->priv->filters, n);
2316 CONNECTION_UNLOCK (connection);
2318 /* do free without holding lock */
2319 if (to_destroy != NULL)
2321 if (to_destroy->user_data_free_func != NULL)
2322 to_destroy->user_data_free_func (to_destroy->user_data);
2323 g_free (to_destroy);
2327 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2331 /* ---------------------------------------------------------------------------------------------------- */
2337 gchar *interface_name;
2341 GArray *subscribers;
2346 GDBusSignalCallback callback;
2348 GDestroyNotify user_data_free_func;
2350 GMainContext *context;
2354 signal_data_free (SignalData *data)
2356 g_free (data->rule);
2357 g_free (data->sender);
2358 g_free (data->interface_name);
2359 g_free (data->member);
2360 g_free (data->object_path);
2361 g_free (data->arg0);
2362 g_array_free (data->subscribers, TRUE);
2367 args_to_rule (const gchar *sender,
2368 const gchar *interface_name,
2369 const gchar *member,
2370 const gchar *object_path,
2375 rule = g_string_new ("type='signal'");
2377 g_string_append_printf (rule, ",sender='%s'", sender);
2378 if (interface_name != NULL)
2379 g_string_append_printf (rule, ",interface='%s'", interface_name);
2381 g_string_append_printf (rule, ",member='%s'", member);
2382 if (object_path != NULL)
2383 g_string_append_printf (rule, ",path='%s'", object_path);
2385 g_string_append_printf (rule, ",arg0='%s'", arg0);
2387 return g_string_free (rule, FALSE);
2390 static guint _global_subscriber_id = 1;
2391 static guint _global_registration_id = 1;
2392 static guint _global_subtree_registration_id = 1;
2394 /* ---------------------------------------------------------------------------------------------------- */
2396 /* must hold lock when calling */
2398 add_match_rule (GDBusConnection *connection,
2399 const gchar *match_rule)
2402 GDBusMessage *message;
2404 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2405 "/org/freedesktop/DBus", /* path */
2406 "org.freedesktop.DBus", /* interface */
2408 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2411 if (!g_dbus_connection_send_message_unlocked (connection,
2416 g_critical ("Error while sending AddMatch() message: %s", error->message);
2417 g_error_free (error);
2419 g_object_unref (message);
2422 /* ---------------------------------------------------------------------------------------------------- */
2424 /* must hold lock when calling */
2426 remove_match_rule (GDBusConnection *connection,
2427 const gchar *match_rule)
2430 GDBusMessage *message;
2432 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2433 "/org/freedesktop/DBus", /* path */
2434 "org.freedesktop.DBus", /* interface */
2436 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2439 if (!g_dbus_connection_send_message_unlocked (connection,
2444 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2445 g_error_free (error);
2447 g_object_unref (message);
2450 /* ---------------------------------------------------------------------------------------------------- */
2453 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2455 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2456 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2457 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2458 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2459 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2462 /* ---------------------------------------------------------------------------------------------------- */
2465 * g_dbus_connection_signal_subscribe:
2466 * @connection: A #GDBusConnection.
2467 * @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.
2468 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2469 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2470 * @object_path: Object path to match on or %NULL to match on all object paths.
2471 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2472 * @callback: Callback to invoke when there is a signal matching the requested data.
2473 * @user_data: User data to pass to @callback.
2474 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2476 * Subscribes to signals on @connection and invokes @callback with a
2477 * whenever the signal is received. Note that @callback
2478 * will be invoked in the <link
2479 * linkend="g-main-context-push-thread-default">thread-default main
2480 * loop</link> of the thread you are calling this method from.
2482 * It is considered a programming error to use this function if @connection is closed.
2484 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2485 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2486 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2487 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2488 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2489 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2491 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2496 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2497 const gchar *sender,
2498 const gchar *interface_name,
2499 const gchar *member,
2500 const gchar *object_path,
2502 GDBusSignalCallback callback,
2504 GDestroyNotify user_data_free_func)
2507 SignalData *signal_data;
2508 SignalSubscriber subscriber;
2509 GPtrArray *signal_data_array;
2511 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2512 * an OOM condition. We might want to change that but that would involve making
2513 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2514 * handle that. And there's really no sensible way of handling this short of retrying
2515 * to add the match rule... and then there's the little thing that, hey, maybe there's
2516 * a reason the bus in an OOM condition.
2518 * Doable, but not really sure it's worth it...
2521 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2522 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2523 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2524 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2525 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2526 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2527 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2528 g_return_val_if_fail (callback != NULL, 0);
2530 CONNECTION_LOCK (connection);
2532 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2537 subscriber.callback = callback;
2538 subscriber.user_data = user_data;
2539 subscriber.user_data_free_func = user_data_free_func;
2540 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2541 subscriber.context = g_main_context_get_thread_default ();
2542 if (subscriber.context != NULL)
2543 g_main_context_ref (subscriber.context);
2545 /* see if we've already have this rule */
2546 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2547 if (signal_data != NULL)
2549 g_array_append_val (signal_data->subscribers, subscriber);
2554 signal_data = g_new0 (SignalData, 1);
2555 signal_data->rule = rule;
2556 signal_data->sender = g_strdup (sender);
2557 signal_data->interface_name = g_strdup (interface_name);
2558 signal_data->member = g_strdup (member);
2559 signal_data->object_path = g_strdup (object_path);
2560 signal_data->arg0 = g_strdup (arg0);
2561 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2562 g_array_append_val (signal_data->subscribers, subscriber);
2564 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2568 /* Add the match rule to the bus...
2570 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2571 * always send such messages to to us.
2573 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2575 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2577 add_match_rule (connection, signal_data->rule);
2582 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2583 GUINT_TO_POINTER (subscriber.id),
2586 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2587 signal_data->sender);
2588 if (signal_data_array == NULL)
2590 signal_data_array = g_ptr_array_new ();
2591 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2592 g_strdup (signal_data->sender),
2595 g_ptr_array_add (signal_data_array, signal_data);
2597 CONNECTION_UNLOCK (connection);
2599 return subscriber.id;
2602 /* ---------------------------------------------------------------------------------------------------- */
2604 /* must hold lock when calling this */
2606 unsubscribe_id_internal (GDBusConnection *connection,
2607 guint subscription_id,
2608 GArray *out_removed_subscribers)
2610 SignalData *signal_data;
2611 GPtrArray *signal_data_array;
2614 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2615 GUINT_TO_POINTER (subscription_id));
2616 if (signal_data == NULL)
2618 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2622 for (n = 0; n < signal_data->subscribers->len; n++)
2624 SignalSubscriber *subscriber;
2626 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2627 if (subscriber->id != subscription_id)
2630 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2631 GUINT_TO_POINTER (subscription_id)));
2632 g_array_append_val (out_removed_subscribers, *subscriber);
2633 g_array_remove_index (signal_data->subscribers, n);
2635 if (signal_data->subscribers->len == 0)
2636 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2638 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2639 signal_data->sender);
2640 g_warn_if_fail (signal_data_array != NULL);
2641 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2643 if (signal_data_array->len == 0)
2645 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2647 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2648 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2650 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2652 remove_match_rule (connection, signal_data->rule);
2656 signal_data_free (signal_data);
2662 g_assert_not_reached ();
2669 * g_dbus_connection_signal_unsubscribe:
2670 * @connection: A #GDBusConnection.
2671 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2673 * Unsubscribes from signals.
2678 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2679 guint subscription_id)
2681 GArray *subscribers;
2684 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2686 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2688 CONNECTION_LOCK (connection);
2689 unsubscribe_id_internal (connection,
2692 CONNECTION_UNLOCK (connection);
2695 g_assert (subscribers->len == 0 || subscribers->len == 1);
2697 /* call GDestroyNotify without lock held */
2698 for (n = 0; n < subscribers->len; n++)
2700 SignalSubscriber *subscriber;
2701 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2702 if (subscriber->user_data_free_func != NULL)
2703 subscriber->user_data_free_func (subscriber->user_data);
2704 if (subscriber->context != NULL)
2705 g_main_context_unref (subscriber->context);
2708 g_array_free (subscribers, TRUE);
2711 /* ---------------------------------------------------------------------------------------------------- */
2715 guint subscription_id;
2716 GDBusSignalCallback callback;
2718 GDBusMessage *message;
2719 GDBusConnection *connection;
2720 const gchar *sender;
2722 const gchar *interface;
2723 const gchar *member;
2726 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2730 emit_signal_instance_in_idle_cb (gpointer data)
2732 SignalInstance *signal_instance = data;
2733 GVariant *parameters;
2734 gboolean has_subscription;
2736 parameters = g_dbus_message_get_body (signal_instance->message);
2737 if (parameters == NULL)
2739 parameters = g_variant_new ("()");
2740 g_variant_ref_sink (parameters);
2744 g_variant_ref_sink (parameters);
2748 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2749 signal_instance->sender,
2750 signal_instance->path,
2751 signal_instance->interface,
2752 signal_instance->member,
2753 g_variant_print (parameters, TRUE));
2756 /* Careful here, don't do the callback if we no longer has the subscription */
2757 CONNECTION_LOCK (signal_instance->connection);
2758 has_subscription = FALSE;
2759 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2760 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2761 has_subscription = TRUE;
2762 CONNECTION_UNLOCK (signal_instance->connection);
2764 if (has_subscription)
2766 signal_instance->callback (signal_instance->connection,
2767 signal_instance->sender,
2768 signal_instance->path,
2769 signal_instance->interface,
2770 signal_instance->member,
2772 signal_instance->user_data);
2774 if (parameters != NULL)
2775 g_variant_unref (parameters);
2781 signal_instance_free (SignalInstance *signal_instance)
2783 g_object_unref (signal_instance->message);
2784 g_object_unref (signal_instance->connection);
2785 g_free (signal_instance);
2788 /* called in message handler thread WITH lock held */
2790 schedule_callbacks (GDBusConnection *connection,
2791 GPtrArray *signal_data_array,
2792 GDBusMessage *message,
2793 const gchar *sender)
2796 const gchar *interface;
2797 const gchar *member;
2806 interface = g_dbus_message_get_interface (message);
2807 member = g_dbus_message_get_member (message);
2808 path = g_dbus_message_get_path (message);
2809 arg0 = g_dbus_message_get_arg0 (message);
2812 g_debug ("sender = `%s'", sender);
2813 g_debug ("interface = `%s'", interface);
2814 g_debug ("member = `%s'", member);
2815 g_debug ("path = `%s'", path);
2816 g_debug ("arg0 = `%s'", arg0);
2819 /* TODO: if this is slow, then we can change signal_data_array into
2820 * map_object_path_to_signal_data_array or something.
2822 for (n = 0; n < signal_data_array->len; n++)
2824 SignalData *signal_data = signal_data_array->pdata[n];
2826 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2829 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2832 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2835 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2838 for (m = 0; m < signal_data->subscribers->len; m++)
2840 SignalSubscriber *subscriber;
2841 GSource *idle_source;
2842 SignalInstance *signal_instance;
2844 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2846 signal_instance = g_new0 (SignalInstance, 1);
2847 signal_instance->subscription_id = subscriber->id;
2848 signal_instance->callback = subscriber->callback;
2849 signal_instance->user_data = subscriber->user_data;
2850 signal_instance->message = g_object_ref (message);
2851 signal_instance->connection = g_object_ref (connection);
2852 signal_instance->sender = sender;
2853 signal_instance->path = path;
2854 signal_instance->interface = interface;
2855 signal_instance->member = member;
2857 idle_source = g_idle_source_new ();
2858 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2859 g_source_set_callback (idle_source,
2860 emit_signal_instance_in_idle_cb,
2862 (GDestroyNotify) signal_instance_free);
2863 g_source_attach (idle_source, subscriber->context);
2864 g_source_unref (idle_source);
2869 /* called in message handler thread with lock held */
2871 distribute_signals (GDBusConnection *connection,
2872 GDBusMessage *message)
2874 GPtrArray *signal_data_array;
2875 const gchar *sender;
2877 sender = g_dbus_message_get_sender (message);
2879 /* collect subcsribers that match on sender */
2882 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2883 if (signal_data_array != NULL) {
2884 schedule_callbacks (connection, signal_data_array, message, sender);
2888 /* collect subcsribers not matching on sender */
2889 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2890 if (signal_data_array != NULL)
2892 schedule_callbacks (connection, signal_data_array, message, sender);
2896 /* ---------------------------------------------------------------------------------------------------- */
2898 /* only called from finalize(), removes all subscriptions */
2900 purge_all_signal_subscriptions (GDBusConnection *connection)
2902 GHashTableIter iter;
2905 GArray *subscribers;
2908 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2909 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2910 while (g_hash_table_iter_next (&iter, &key, NULL))
2912 guint subscription_id = GPOINTER_TO_UINT (key);
2913 g_array_append_val (ids, subscription_id);
2916 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2917 for (n = 0; n < ids->len; n++)
2919 guint subscription_id = g_array_index (ids, guint, n);
2920 unsubscribe_id_internal (connection,
2924 g_array_free (ids, TRUE);
2926 /* call GDestroyNotify without lock held */
2927 for (n = 0; n < subscribers->len; n++)
2929 SignalSubscriber *subscriber;
2930 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2931 if (subscriber->user_data_free_func != NULL)
2932 subscriber->user_data_free_func (subscriber->user_data);
2933 if (subscriber->context != NULL)
2934 g_main_context_unref (subscriber->context);
2937 g_array_free (subscribers, TRUE);
2940 /* ---------------------------------------------------------------------------------------------------- */
2942 struct ExportedObject
2945 GDBusConnection *connection;
2947 /* maps gchar* -> ExportedInterface* */
2948 GHashTable *map_if_name_to_ei;
2951 /* only called with lock held */
2953 exported_object_free (ExportedObject *eo)
2955 g_free (eo->object_path);
2956 g_hash_table_unref (eo->map_if_name_to_ei);
2965 gchar *interface_name;
2966 const GDBusInterfaceVTable *vtable;
2967 const GDBusInterfaceInfo *introspection_data;
2969 GMainContext *context;
2971 GDestroyNotify user_data_free_func;
2972 } ExportedInterface;
2974 /* called with lock held */
2976 exported_interface_free (ExportedInterface *ei)
2978 if (ei->user_data_free_func != NULL)
2980 /* TODO: push to thread-default mainloop */
2981 ei->user_data_free_func (ei->user_data);
2983 if (ei->context != NULL)
2985 g_main_context_unref (ei->context);
2987 g_free (ei->interface_name);
2991 /* ---------------------------------------------------------------------------------------------------- */
2995 GDBusConnection *connection;
2996 GDBusMessage *message;
2998 const char *property_name;
2999 const GDBusInterfaceVTable *vtable;
3000 const GDBusInterfaceInfo *interface_info;
3001 const GDBusPropertyInfo *property_info;
3005 property_data_free (PropertyData *data)
3007 g_object_unref (data->connection);
3008 g_object_unref (data->message);
3012 /* called in thread where object was registered - no locks held */
3014 invoke_get_property_in_idle_cb (gpointer _data)
3016 PropertyData *data = _data;
3019 GDBusMessage *reply;
3022 value = data->vtable->get_property (data->connection,
3023 g_dbus_message_get_sender (data->message),
3024 g_dbus_message_get_path (data->message),
3025 data->interface_info->name,
3026 data->property_name,
3033 g_assert_no_error (error);
3035 g_variant_ref_sink (value);
3036 reply = g_dbus_message_new_method_reply (data->message);
3037 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3038 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3039 g_variant_unref (value);
3040 g_object_unref (reply);
3044 gchar *dbus_error_name;
3046 g_assert (error != NULL);
3048 dbus_error_name = g_dbus_error_encode_gerror (error);
3049 reply = g_dbus_message_new_method_error_literal (data->message,
3052 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3053 g_free (dbus_error_name);
3054 g_error_free (error);
3055 g_object_unref (reply);
3061 /* called in thread where object was registered - no locks held */
3063 invoke_set_property_in_idle_cb (gpointer _data)
3065 PropertyData *data = _data;
3067 GDBusMessage *reply;
3073 g_variant_get (g_dbus_message_get_body (data->message),
3079 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3080 * of the given value is wrong
3082 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3084 reply = g_dbus_message_new_method_error (data->message,
3085 "org.freedesktop.DBus.Error.InvalidArgs",
3086 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3087 data->property_info->name,
3088 data->property_info->signature,
3089 g_variant_get_type_string (value));
3093 if (!data->vtable->set_property (data->connection,
3094 g_dbus_message_get_sender (data->message),
3095 g_dbus_message_get_path (data->message),
3096 data->interface_info->name,
3097 data->property_name,
3102 gchar *dbus_error_name;
3103 g_assert (error != NULL);
3104 dbus_error_name = g_dbus_error_encode_gerror (error);
3105 reply = g_dbus_message_new_method_error_literal (data->message,
3108 g_free (dbus_error_name);
3109 g_error_free (error);
3113 reply = g_dbus_message_new_method_reply (data->message);
3117 g_assert (reply != NULL);
3118 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3119 g_object_unref (reply);
3124 /* called with lock held */
3126 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3127 GDBusMessage *message,
3129 const GDBusInterfaceInfo *introspection_data,
3130 const GDBusInterfaceVTable *vtable,
3131 GMainContext *main_context,
3135 const char *interface_name;
3136 const char *property_name;
3137 const GDBusPropertyInfo *property_info;
3138 GSource *idle_source;
3139 PropertyData *property_data;
3140 GDBusMessage *reply;
3145 g_variant_get (g_dbus_message_get_body (message),
3150 g_variant_get (g_dbus_message_get_body (message),
3159 if (vtable == NULL || vtable->get_property == NULL)
3164 if (vtable == NULL || vtable->set_property == NULL)
3168 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3170 property_info = NULL;
3172 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3173 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3174 if (property_info == NULL)
3176 reply = g_dbus_message_new_method_error (message,
3177 "org.freedesktop.DBus.Error.InvalidArgs",
3178 _("No such property `%s'"),
3180 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3181 g_object_unref (reply);
3186 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3188 reply = g_dbus_message_new_method_error (message,
3189 "org.freedesktop.DBus.Error.InvalidArgs",
3190 _("Property `%s' is not readable"),
3192 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3193 g_object_unref (reply);
3197 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3199 reply = g_dbus_message_new_method_error (message,
3200 "org.freedesktop.DBus.Error.InvalidArgs",
3201 _("Property `%s' is not writable"),
3203 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3204 g_object_unref (reply);
3209 /* ok, got the property info - call user code in an idle handler */
3210 property_data = g_new0 (PropertyData, 1);
3211 property_data->connection = g_object_ref (connection);
3212 property_data->message = g_object_ref (message);
3213 property_data->user_data = user_data;
3214 property_data->property_name = property_name;
3215 property_data->vtable = vtable;
3216 property_data->interface_info = introspection_data;
3217 property_data->property_info = property_info;
3219 idle_source = g_idle_source_new ();
3220 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3221 g_source_set_callback (idle_source,
3222 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3224 (GDestroyNotify) property_data_free);
3225 g_source_attach (idle_source, main_context);
3226 g_source_unref (idle_source);
3234 /* called with lock held */
3236 handle_getset_property (GDBusConnection *connection,
3238 GDBusMessage *message,
3241 ExportedInterface *ei;
3243 const char *interface_name;
3244 const char *property_name;
3249 g_variant_get (g_dbus_message_get_body (message),
3254 g_variant_get (g_dbus_message_get_body (message),
3260 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3261 * no such interface registered
3263 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3266 GDBusMessage *reply;
3267 reply = g_dbus_message_new_method_error (message,
3268 "org.freedesktop.DBus.Error.InvalidArgs",
3269 _("No such interface `%s'"),
3271 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3272 g_object_unref (reply);
3277 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3280 ei->introspection_data,
3288 /* ---------------------------------------------------------------------------------------------------- */
3292 GDBusConnection *connection;
3293 GDBusMessage *message;
3295 const GDBusInterfaceVTable *vtable;
3296 const GDBusInterfaceInfo *interface_info;
3297 } PropertyGetAllData;
3300 property_get_all_data_free (PropertyData *data)
3302 g_object_unref (data->connection);
3303 g_object_unref (data->message);
3307 /* called in thread where object was registered - no locks held */
3309 invoke_get_all_properties_in_idle_cb (gpointer _data)
3311 PropertyGetAllData *data = _data;
3312 GVariantBuilder *builder;
3316 GDBusMessage *reply;
3321 /* TODO: Right now we never fail this call - we just omit values if
3322 * a get_property() call is failing.
3324 * We could fail the whole call if just a single get_property() call
3325 * returns an error. We need clarification in the D-Bus spec about this.
3327 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3328 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3330 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3333 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3336 value = data->vtable->get_property (data->connection,
3337 g_dbus_message_get_sender (data->message),
3338 g_dbus_message_get_path (data->message),
3339 data->interface_info->name,
3340 property_info->name,
3347 g_variant_ref_sink (value);
3348 g_variant_builder_add (builder,
3350 property_info->name,
3352 g_variant_unref (value);
3354 result = g_variant_builder_end (builder);
3356 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3357 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3358 packed = g_variant_builder_end (builder);
3360 reply = g_dbus_message_new_method_reply (data->message);
3361 g_dbus_message_set_body (reply, packed);
3362 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3363 g_object_unref (reply);
3368 /* called with lock held */
3370 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3371 GDBusMessage *message,
3372 const GDBusInterfaceInfo *introspection_data,
3373 const GDBusInterfaceVTable *vtable,
3374 GMainContext *main_context,
3378 const char *interface_name;
3379 GSource *idle_source;
3380 PropertyGetAllData *property_get_all_data;
3384 g_variant_get (g_dbus_message_get_body (message),
3388 if (vtable == NULL || vtable->get_property == NULL)
3391 /* ok, got the property info - call user in an idle handler */
3392 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3393 property_get_all_data->connection = g_object_ref (connection);
3394 property_get_all_data->message = g_object_ref (message);
3395 property_get_all_data->user_data = user_data;
3396 property_get_all_data->vtable = vtable;
3397 property_get_all_data->interface_info = introspection_data;
3399 idle_source = g_idle_source_new ();
3400 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3401 g_source_set_callback (idle_source,
3402 invoke_get_all_properties_in_idle_cb,
3403 property_get_all_data,
3404 (GDestroyNotify) property_get_all_data_free);
3405 g_source_attach (idle_source, main_context);
3406 g_source_unref (idle_source);
3414 /* called with lock held */
3416 handle_get_all_properties (GDBusConnection *connection,
3418 GDBusMessage *message)
3420 ExportedInterface *ei;
3422 const char *interface_name;
3426 g_variant_get (g_dbus_message_get_body (message),
3430 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3431 * no such interface registered
3433 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3436 GDBusMessage *reply;
3437 reply = g_dbus_message_new_method_error (message,
3438 "org.freedesktop.DBus.Error.InvalidArgs",
3439 _("No such interface"),
3441 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3442 g_object_unref (reply);
3447 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3449 ei->introspection_data,
3457 /* ---------------------------------------------------------------------------------------------------- */
3460 introspect_append_header (GString *s)
3463 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3464 "<!-- GDBus 0.1 -->\n"
3469 introspect_append_standard_interfaces (GString *s)
3472 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3473 " <method name=\"Get\">\n"
3474 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3475 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3476 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3478 " <method name=\"GetAll\">\n"
3479 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3480 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3482 " <method name=\"Set\">\n"
3483 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3484 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3485 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3487 " <signal name=\"PropertiesChanged\">\n"
3488 " <arg type=\"s\" name=\"interface_name\"/>\n"
3489 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3492 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3493 " <method name=\"Introspect\">\n"
3494 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3497 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3498 " <method name=\"Ping\"/>\n"
3499 " <method name=\"GetMachineId\">\n"
3500 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3506 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3508 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3514 begin = object_path + path_len;
3515 end = strchr (begin, '/');
3519 s = g_strndup (begin, end - begin);
3523 s = g_strdup (begin);
3526 if (g_hash_table_lookup (set, s) == NULL)
3528 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3537 /* TODO: we want a nicer public interface for this */
3539 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3544 GHashTableIter hash_iter;
3545 const gchar *object_path;
3551 CONNECTION_ENSURE_LOCK (connection);
3553 path_len = strlen (path);
3557 set = g_hash_table_new (g_str_hash, g_str_equal);
3559 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3560 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3561 maybe_add_path (path, path_len, object_path, set);
3563 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3564 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3565 maybe_add_path (path, path_len, object_path, set);
3567 p = g_ptr_array_new ();
3568 keys = g_hash_table_get_keys (set);
3569 for (l = keys; l != NULL; l = l->next)
3571 g_ptr_array_add (p, l->data);
3573 g_hash_table_unref (set);
3576 g_ptr_array_add (p, NULL);
3577 ret = (gchar **) g_ptr_array_free (p, FALSE);
3582 g_dbus_connection_list_registered (GDBusConnection *connection,
3586 CONNECTION_LOCK (connection);
3587 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3588 CONNECTION_UNLOCK (connection);
3592 /* called in message handler thread with lock held */
3594 handle_introspect (GDBusConnection *connection,
3596 GDBusMessage *message)
3600 GDBusMessage *reply;
3601 GHashTableIter hash_iter;
3602 ExportedInterface *ei;
3605 /* first the header with the standard interfaces */
3606 s = g_string_new (NULL);
3607 introspect_append_header (s);
3608 introspect_append_standard_interfaces (s);
3610 /* then include the registered interfaces */
3611 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3612 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3614 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3617 /* finally include nodes registered below us */
3618 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3619 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3621 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3623 g_strfreev (registered);
3624 g_string_append (s, "</node>\n");
3626 reply = g_dbus_message_new_method_reply (message);
3627 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3628 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3629 g_object_unref (reply);
3630 g_string_free (s, TRUE);
3635 /* called in thread where object was registered - no locks held */
3637 invoke_method_in_idle_cb (gpointer user_data)
3639 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3640 GDBusInterfaceVTable *vtable;
3642 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3643 g_assert (vtable != NULL && vtable->method_call != NULL);
3645 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3646 g_dbus_method_invocation_get_sender (invocation),
3647 g_dbus_method_invocation_get_object_path (invocation),
3648 g_dbus_method_invocation_get_interface_name (invocation),
3649 g_dbus_method_invocation_get_method_name (invocation),
3650 g_dbus_method_invocation_get_parameters (invocation),
3651 g_object_ref (invocation),
3652 g_dbus_method_invocation_get_user_data (invocation));
3657 /* called in message handler thread with lock held */
3659 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3660 GDBusMessage *message,
3661 const GDBusInterfaceInfo *introspection_data,
3662 const GDBusInterfaceVTable *vtable,
3663 GMainContext *main_context,
3666 GDBusMethodInvocation *invocation;
3667 const GDBusMethodInfo *method_info;
3668 GDBusMessage *reply;
3669 GVariant *parameters;
3670 GSource *idle_source;
3672 gchar *in_signature;
3676 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3677 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3679 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3680 * error to the caller
3682 if (method_info == NULL)
3684 reply = g_dbus_message_new_method_error (message,
3685 "org.freedesktop.DBus.Error.UnknownMethod",
3686 _("No such method `%s'"),
3687 g_dbus_message_get_member (message));
3688 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3689 g_object_unref (reply);
3694 /* Check that the incoming args are of the right type - if they are not, return
3695 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3697 * TODO: might also be worth caching the combined signature.
3699 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3700 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3702 reply = g_dbus_message_new_method_error (message,
3703 "org.freedesktop.DBus.Error.InvalidArgs",
3704 _("Signature of message, `%s', does not match expected signature `%s'"),
3705 g_dbus_message_get_signature (message),
3707 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3708 g_object_unref (reply);
3709 g_free (in_signature);
3713 g_free (in_signature);
3715 parameters = g_dbus_message_get_body (message);
3716 if (parameters == NULL)
3718 parameters = g_variant_new ("()");
3719 g_variant_ref_sink (parameters);
3723 g_variant_ref (parameters);
3726 /* schedule the call in idle */
3727 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3728 g_dbus_message_get_path (message),
3729 g_dbus_message_get_interface (message),
3730 g_dbus_message_get_member (message),
3736 g_variant_unref (parameters);
3737 g_object_set_data (G_OBJECT (invocation),
3738 "g-dbus-interface-vtable",
3741 idle_source = g_idle_source_new ();
3742 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3743 g_source_set_callback (idle_source,
3744 invoke_method_in_idle_cb,
3747 g_source_attach (idle_source, main_context);
3748 g_source_unref (idle_source);
3757 /* ---------------------------------------------------------------------------------------------------- */
3759 /* called in message handler thread with lock held */
3761 obj_message_func (GDBusConnection *connection,
3763 GDBusMessage *message)
3765 const gchar *interface_name;
3766 const gchar *member;
3767 const gchar *signature;
3772 interface_name = g_dbus_message_get_interface (message);
3773 member = g_dbus_message_get_member (message);
3774 signature = g_dbus_message_get_signature (message);
3776 /* see if we have an interface for handling this call */
3777 if (interface_name != NULL)
3779 ExportedInterface *ei;
3780 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3783 /* we do - invoke the handler in idle in the right thread */
3785 /* handle no vtable or handler being present */
3786 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3789 handled = validate_and_maybe_schedule_method_call (connection,
3791 ei->introspection_data,
3799 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3800 g_strcmp0 (member, "Introspect") == 0 &&
3801 g_strcmp0 (signature, "") == 0)
3803 handled = handle_introspect (connection, eo, message);
3806 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3807 g_strcmp0 (member, "Get") == 0 &&
3808 g_strcmp0 (signature, "ss") == 0)
3810 handled = handle_getset_property (connection, eo, message, TRUE);
3813 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3814 g_strcmp0 (member, "Set") == 0 &&
3815 g_strcmp0 (signature, "ssv") == 0)
3817 handled = handle_getset_property (connection, eo, message, FALSE);
3820 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3821 g_strcmp0 (member, "GetAll") == 0 &&
3822 g_strcmp0 (signature, "s") == 0)
3824 handled = handle_get_all_properties (connection, eo, message);
3833 * g_dbus_connection_register_object:
3834 * @connection: A #GDBusConnection.
3835 * @object_path: The object path to register at.
3836 * @interface_name: The D-Bus interface to register.
3837 * @introspection_data: Introspection data for the interface.
3838 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3839 * @user_data: Data to pass to functions in @vtable.
3840 * @user_data_free_func: Function to call when the object path is unregistered.
3841 * @error: Return location for error or %NULL.
3843 * Registers callbacks for exported objects at @object_path with the
3844 * D-Bus interface @interface_name.
3846 * Calls to functions in @vtable (and @user_data_free_func) will
3847 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3848 * loop</link> of the thread you are calling this method from.
3850 * Note that all #GVariant values passed to functions in @vtable will match
3851 * the signature given in @introspection_data - if a remote caller passes
3852 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3853 * is returned to the remote caller.
3855 * Additionally, if the remote caller attempts to invoke methods or
3856 * access properties not mentioned in @introspection_data the
3857 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3858 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3859 * are returned to the caller.
3861 * It is considered a programming error if the
3862 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3863 * #GVariant of incorrect type.
3865 * If an existing callback is already registered at @object_path and
3866 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3868 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3870 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3871 * that can be used with g_dbus_connection_unregister_object() .
3876 g_dbus_connection_register_object (GDBusConnection *connection,
3877 const gchar *object_path,
3878 const gchar *interface_name,
3879 const GDBusInterfaceInfo *introspection_data,
3880 const GDBusInterfaceVTable *vtable,
3882 GDestroyNotify user_data_free_func,
3886 ExportedInterface *ei;
3889 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3890 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3891 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3892 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3893 g_return_val_if_fail (introspection_data != NULL, 0);
3894 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3898 CONNECTION_LOCK (connection);
3900 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3903 eo = g_new0 (ExportedObject, 1);
3904 eo->object_path = g_strdup (object_path);
3905 eo->connection = connection;
3906 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3909 (GDestroyNotify) exported_interface_free);
3910 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3913 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3919 _("An object is already exported for the interface %s at %s"),
3925 ei = g_new0 (ExportedInterface, 1);
3926 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3928 ei->user_data = user_data;
3929 ei->user_data_free_func = user_data_free_func;
3930 ei->vtable = vtable;
3931 ei->introspection_data = introspection_data;
3932 ei->interface_name = g_strdup (interface_name);
3933 ei->context = g_main_context_get_thread_default ();
3934 if (ei->context != NULL)
3935 g_main_context_ref (ei->context);
3937 g_hash_table_insert (eo->map_if_name_to_ei,
3938 (gpointer) ei->interface_name,
3940 g_hash_table_insert (connection->priv->map_id_to_ei,
3941 GUINT_TO_POINTER (ei->id),
3947 CONNECTION_UNLOCK (connection);
3953 * g_dbus_connection_unregister_object:
3954 * @connection: A #GDBusConnection.
3955 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3957 * Unregisters an object.
3959 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3964 g_dbus_connection_unregister_object (GDBusConnection *connection,
3965 guint registration_id)
3967 ExportedInterface *ei;
3971 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3975 CONNECTION_LOCK (connection);
3977 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
3978 GUINT_TO_POINTER (registration_id));
3986 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
3987 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
3988 /* unregister object path if we have no more exported interfaces */
3989 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
3991 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
3998 CONNECTION_UNLOCK (connection);
4003 /* ---------------------------------------------------------------------------------------------------- */
4006 * g_dbus_connection_emit_signal:
4007 * @connection: A #GDBusConnection.
4008 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4009 * @object_path: Path of remote object.
4010 * @interface_name: D-Bus interface to emit a signal on.
4011 * @signal_name: The name of the signal to emit.
4012 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4013 * @error: Return location for error or %NULL.
4017 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4019 * Returns: %TRUE unless @error is set.
4024 g_dbus_connection_emit_signal (GDBusConnection *connection,
4025 const gchar *destination_bus_name,
4026 const gchar *object_path,
4027 const gchar *interface_name,
4028 const gchar *signal_name,
4029 GVariant *parameters,
4032 GDBusMessage *message;
4038 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4039 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4040 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4041 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4042 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4043 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4045 message = g_dbus_message_new_signal (object_path,
4049 if (destination_bus_name != NULL)
4051 g_dbus_message_set_header (message,
4052 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4053 g_variant_new_string (destination_bus_name));
4056 if (parameters != NULL)
4057 g_dbus_message_set_body (message, parameters);
4059 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4060 g_object_unref (message);
4066 add_invoke_method_flags (GDBusMessage *message,
4067 GDBusInvokeMethodFlags flags)
4069 if (flags & G_DBUS_INVOKE_METHOD_FLAGS_NO_AUTO_START)
4070 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4074 * g_dbus_connection_invoke_method:
4075 * @connection: A #GDBusConnection.
4076 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4077 * @object_path: Path of remote object.
4078 * @interface_name: D-Bus interface to invoke method on.
4079 * @method_name: The name of the method to invoke.
4080 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4081 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4082 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4083 * @cancellable: A #GCancellable or %NULL.
4084 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4085 * care about the result of the method invocation.
4086 * @user_data: The data to pass to @callback.
4088 * Asynchronously invokes the @method_name method on the
4089 * @interface_name D-Bus interface on the remote object at
4090 * @object_path owned by @bus_name.
4092 * If @connection is closed then the operation will fail with
4093 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4094 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4095 * not compatible with the D-Bus protocol, the operation fails with
4096 * %G_IO_ERROR_INVALID_ARGUMENT.
4098 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4099 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4100 * of the thread you are calling this method from. You can then call
4101 * g_dbus_connection_invoke_method_finish() to get the result of the operation.
4102 * See g_dbus_connection_invoke_method_sync() for the synchronous version of this
4108 g_dbus_connection_invoke_method (GDBusConnection *connection,
4109 const gchar *bus_name,
4110 const gchar *object_path,
4111 const gchar *interface_name,
4112 const gchar *method_name,
4113 GVariant *parameters,
4114 GDBusInvokeMethodFlags flags,
4116 GCancellable *cancellable,
4117 GAsyncReadyCallback callback,
4120 GDBusMessage *message;
4122 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4123 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4124 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4125 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4126 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4127 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4128 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4130 message = g_dbus_message_new_method_call (bus_name,
4134 add_invoke_method_flags (message, flags);
4135 if (parameters != NULL)
4136 g_dbus_message_set_body (message, parameters);
4138 g_dbus_connection_send_message_with_reply (connection,
4141 NULL, /* volatile guint32 *out_serial */
4146 if (message != NULL)
4147 g_object_unref (message);
4151 decode_method_reply (GDBusMessage *reply, GError **error)
4156 switch (g_dbus_message_get_message_type (reply))
4158 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4159 result = g_dbus_message_get_body (reply);
4162 result = g_variant_new ("()");
4163 g_variant_ref_sink (result);
4167 g_variant_ref (result);
4170 case G_DBUS_MESSAGE_TYPE_ERROR:
4171 g_dbus_message_to_gerror (reply, error);
4175 g_assert_not_reached ();
4183 * g_dbus_connection_invoke_method_finish:
4184 * @connection: A #GDBusConnection.
4185 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_invoke_method().
4186 * @error: Return location for error or %NULL.
4188 * Finishes an operation started with g_dbus_connection_invoke_method().
4190 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4191 * return values. Free with g_variant_unref().
4196 g_dbus_connection_invoke_method_finish (GDBusConnection *connection,
4200 GDBusMessage *reply;
4203 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4204 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4205 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4209 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4213 result = decode_method_reply (reply, error);
4215 g_object_unref (reply);
4221 /* ---------------------------------------------------------------------------------------------------- */
4224 * g_dbus_connection_invoke_method_sync:
4225 * @connection: A #GDBusConnection.
4226 * @bus_name: A unique or well-known bus name.
4227 * @object_path: Path of remote object.
4228 * @interface_name: D-Bus interface to invoke method on.
4229 * @method_name: The name of the method to invoke.
4230 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4231 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4232 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4233 * @cancellable: A #GCancellable or %NULL.
4234 * @error: Return location for error or %NULL.
4236 * Synchronously invokes the @method_name method on the
4237 * @interface_name D-Bus interface on the remote object at
4238 * @object_path owned by @bus_name.
4240 * If @connection is closed then the operation will fail with
4241 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4242 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4243 * contains a value not compatible with the D-Bus protocol, the operation
4244 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4246 * The calling thread is blocked until a reply is received. See
4247 * g_dbus_connection_invoke_method() for the asynchronous version of
4250 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4251 * return values. Free with g_variant_unref().
4256 g_dbus_connection_invoke_method_sync (GDBusConnection *connection,
4257 const gchar *bus_name,
4258 const gchar *object_path,
4259 const gchar *interface_name,
4260 const gchar *method_name,
4261 GVariant *parameters,
4262 GDBusInvokeMethodFlags flags,
4264 GCancellable *cancellable,
4267 GDBusMessage *message;
4268 GDBusMessage *reply;
4275 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4276 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4277 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4278 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4279 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4280 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4281 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4283 message = g_dbus_message_new_method_call (bus_name,
4287 add_invoke_method_flags (message, flags);
4288 if (parameters != NULL)
4289 g_dbus_message_set_body (message, parameters);
4291 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4294 NULL, /* volatile guint32 *out_serial */
4301 result = decode_method_reply (reply, error);
4304 if (message != NULL)
4305 g_object_unref (message);
4307 g_object_unref (reply);
4312 /* ---------------------------------------------------------------------------------------------------- */
4314 struct ExportedSubtree
4318 GDBusConnection *connection;
4319 const GDBusSubtreeVTable *vtable;
4320 GDBusSubtreeFlags flags;
4322 GMainContext *context;
4324 GDestroyNotify user_data_free_func;
4328 exported_subtree_free (ExportedSubtree *es)
4330 if (es->user_data_free_func != NULL)
4332 /* TODO: push to thread-default mainloop */
4333 es->user_data_free_func (es->user_data);
4335 if (es->context != NULL)
4337 g_main_context_unref (es->context);
4339 g_free (es->object_path);
4343 /* called without lock held */
4345 handle_subtree_introspect (GDBusConnection *connection,
4346 ExportedSubtree *es,
4347 GDBusMessage *message)
4351 GDBusMessage *reply;
4354 const gchar *sender;
4355 const gchar *requested_object_path;
4356 const gchar *requested_node;
4357 GPtrArray *interfaces;
4359 gchar **subnode_paths;
4363 requested_object_path = g_dbus_message_get_path (message);
4364 sender = g_dbus_message_get_sender (message);
4365 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4367 s = g_string_new (NULL);
4368 introspect_append_header (s);
4370 /* Strictly we don't need the children in dynamic mode, but we avoid the
4371 * conditionals to preserve code clarity
4373 children = es->vtable->enumerate (es->connection,
4380 requested_node = strrchr (requested_object_path, '/') + 1;
4382 /* Assert existence of object if we are not dynamic */
4383 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4384 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4389 requested_node = "/";
4392 interfaces = es->vtable->introspect (es->connection,
4397 if (interfaces != NULL)
4399 if (interfaces->len > 0)
4401 /* we're in business */
4402 introspect_append_standard_interfaces (s);
4404 for (n = 0; n < interfaces->len; n++)
4406 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4407 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4410 g_ptr_array_unref (interfaces);
4413 /* then include <node> entries from the Subtree for the root */
4416 for (n = 0; children != NULL && children[n] != NULL; n++)
4418 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4422 /* finally include nodes registered below us */
4423 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4424 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4426 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4428 g_strfreev (subnode_paths);
4430 g_string_append (s, "</node>\n");
4432 reply = g_dbus_message_new_method_reply (message);
4433 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4434 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4435 g_object_unref (reply);
4440 g_string_free (s, TRUE);
4441 g_strfreev (children);
4445 /* called without lock held */
4447 handle_subtree_method_invocation (GDBusConnection *connection,
4448 ExportedSubtree *es,
4449 GDBusMessage *message)
4452 const gchar *sender;
4453 const gchar *interface_name;
4454 const gchar *member;
4455 const gchar *signature;
4456 const gchar *requested_object_path;
4457 const gchar *requested_node;
4460 const GDBusInterfaceInfo *introspection_data;
4461 const GDBusInterfaceVTable *interface_vtable;
4462 gpointer interface_user_data;
4464 GPtrArray *interfaces;
4465 gboolean is_property_get;
4466 gboolean is_property_set;
4467 gboolean is_property_get_all;
4472 requested_object_path = g_dbus_message_get_path (message);
4473 sender = g_dbus_message_get_sender (message);
4474 interface_name = g_dbus_message_get_interface (message);
4475 member = g_dbus_message_get_member (message);
4476 signature = g_dbus_message_get_signature (message);
4477 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4479 is_property_get = FALSE;
4480 is_property_set = FALSE;
4481 is_property_get_all = FALSE;
4482 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4484 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4486 is_property_get = TRUE;
4488 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4490 is_property_set = TRUE;
4492 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4494 is_property_get_all = TRUE;
4498 children = es->vtable->enumerate (es->connection,
4505 requested_node = strrchr (requested_object_path, '/') + 1;
4507 /* If not dynamic, skip if requested node is not part of children */
4508 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4509 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4514 requested_node = "/";
4517 /* get introspection data for the node */
4518 interfaces = es->vtable->introspect (es->connection,
4520 requested_object_path,
4523 g_assert (interfaces != NULL);
4524 introspection_data = NULL;
4525 for (n = 0; n < interfaces->len; n++)
4527 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4528 if (g_strcmp0 (id_n->name, interface_name) == 0)
4530 introspection_data = id_n;
4534 /* dispatch the call if the user wants to handle it */
4535 if (introspection_data != NULL)
4537 /* figure out where to dispatch the method call */
4538 interface_user_data = NULL;
4539 interface_vtable = es->vtable->dispatch (es->connection,
4544 &interface_user_data,
4546 if (interface_vtable == NULL)
4549 CONNECTION_LOCK (connection);
4550 handled = validate_and_maybe_schedule_method_call (es->connection,
4555 interface_user_data);
4556 CONNECTION_UNLOCK (connection);
4558 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4559 else if (is_property_get || is_property_set || is_property_get_all)
4561 if (is_property_get)
4562 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4563 else if (is_property_set)
4564 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4565 else if (is_property_get_all)
4566 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4568 g_assert_not_reached ();
4570 /* see if the object supports this interface at all */
4571 for (n = 0; n < interfaces->len; n++)
4573 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4574 if (g_strcmp0 (id_n->name, interface_name) == 0)
4576 introspection_data = id_n;
4580 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4581 * claims it won't support the interface
4583 if (introspection_data == NULL)
4585 GDBusMessage *reply;
4586 reply = g_dbus_message_new_method_error (message,
4587 "org.freedesktop.DBus.Error.InvalidArgs",
4588 _("No such interface `%s'"),
4590 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4591 g_object_unref (reply);
4596 /* figure out where to dispatch the property get/set/getall calls */
4597 interface_user_data = NULL;
4598 interface_vtable = es->vtable->dispatch (es->connection,
4603 &interface_user_data,
4605 if (interface_vtable == NULL)
4608 if (is_property_get || is_property_set)
4610 CONNECTION_LOCK (connection);
4611 handled = validate_and_maybe_schedule_property_getset (es->connection,
4617 interface_user_data);
4618 CONNECTION_UNLOCK (connection);
4620 else if (is_property_get_all)
4622 CONNECTION_LOCK (connection);
4623 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4628 interface_user_data);
4629 CONNECTION_UNLOCK (connection);
4634 if (interfaces != NULL)
4635 g_ptr_array_unref (interfaces);
4636 g_strfreev (children);
4642 GDBusMessage *message;
4643 ExportedSubtree *es;
4644 } SubtreeDeferredData;
4647 subtree_deferred_data_free (SubtreeDeferredData *data)
4649 g_object_unref (data->message);
4653 /* called without lock held in the thread where the caller registered the subtree */
4655 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4657 SubtreeDeferredData *data = _data;
4662 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4663 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4664 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4666 handled = handle_subtree_introspect (data->es->connection,
4672 handled = handle_subtree_method_invocation (data->es->connection,
4680 CONNECTION_LOCK (data->es->connection);
4681 handled = handle_generic_unlocked (data->es->connection, data->message);
4682 CONNECTION_UNLOCK (data->es->connection);
4685 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4688 GDBusMessage *reply;
4689 reply = g_dbus_message_new_method_error (data->message,
4690 "org.freedesktop.DBus.Error.UnknownMethod",
4691 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4692 g_dbus_message_get_member (data->message),
4693 g_dbus_message_get_interface (data->message),
4694 g_dbus_message_get_signature (data->message));
4695 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4696 g_object_unref (reply);
4702 /* called in message handler thread with lock held */
4704 subtree_message_func (GDBusConnection *connection,
4705 ExportedSubtree *es,
4706 GDBusMessage *message)
4708 GSource *idle_source;
4709 SubtreeDeferredData *data;
4711 data = g_new0 (SubtreeDeferredData, 1);
4712 data->message = g_object_ref (message);
4715 /* defer this call to an idle handler in the right thread */
4716 idle_source = g_idle_source_new ();
4717 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4718 g_source_set_callback (idle_source,
4719 process_subtree_vtable_message_in_idle_cb,
4721 (GDestroyNotify) subtree_deferred_data_free);
4722 g_source_attach (idle_source, es->context);
4723 g_source_unref (idle_source);
4725 /* since we own the entire subtree, handlers for objects not in the subtree have been
4726 * tried already by libdbus-1 - so we just need to ensure that we're always going
4727 * to reply to the message
4733 * g_dbus_connection_register_subtree:
4734 * @connection: A #GDBusConnection.
4735 * @object_path: The object path to register the subtree at.
4736 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4737 * @flags: Flags used to fine tune the behavior of the subtree.
4738 * @user_data: Data to pass to functions in @vtable.
4739 * @user_data_free_func: Function to call when the subtree is unregistered.
4740 * @error: Return location for error or %NULL.
4742 * Registers a whole subtree of <quote>dynamic</quote> objects.
4744 * The @enumerate and @introspection functions in @vtable are used to
4745 * convey, to remote callers, what nodes exist in the subtree rooted
4748 * When handling remote calls into any node in the subtree, first the
4749 * @enumerate function is used to check if the node exists. If the node exists
4750 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4751 * the @introspection function is used to check if the node supports the
4752 * requested method. If so, the @dispatch function is used to determine
4753 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4754 * #gpointer will be used to call into the interface vtable for processing
4757 * All calls into user-provided code will be invoked in the <link
4758 * linkend="g-main-context-push-thread-default">thread-default main
4759 * loop</link> of the thread you are calling this method from.
4761 * If an existing subtree is already registered at @object_path or
4762 * then @error is set to #G_IO_ERROR_EXISTS.
4764 * Note that it is valid to register regular objects (using
4765 * g_dbus_connection_register_object()) in a subtree registered with
4766 * g_dbus_connection_register_subtree() - if so, the subtree handler
4767 * is tried as the last resort. One way to think about a subtree
4768 * handler is to consider it a <quote>fallback handler</quote>
4769 * for object paths not registered via g_dbus_connection_register_object()
4770 * or other bindings.
4772 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4774 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4775 * that can be used with g_dbus_connection_unregister_subtree() .
4780 g_dbus_connection_register_subtree (GDBusConnection *connection,
4781 const gchar *object_path,
4782 const GDBusSubtreeVTable *vtable,
4783 GDBusSubtreeFlags flags,
4785 GDestroyNotify user_data_free_func,
4789 ExportedSubtree *es;
4791 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4792 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4793 g_return_val_if_fail (vtable != NULL, 0);
4794 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4798 CONNECTION_LOCK (connection);
4800 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4806 _("A subtree is already exported for %s"),
4811 es = g_new0 (ExportedSubtree, 1);
4812 es->object_path = g_strdup (object_path);
4813 es->connection = connection;
4815 es->vtable = vtable;
4817 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4818 es->user_data = user_data;
4819 es->user_data_free_func = user_data_free_func;
4820 es->context = g_main_context_get_thread_default ();
4821 if (es->context != NULL)
4822 g_main_context_ref (es->context);
4824 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4825 g_hash_table_insert (connection->priv->map_id_to_es,
4826 GUINT_TO_POINTER (es->id),
4832 CONNECTION_UNLOCK (connection);
4837 /* ---------------------------------------------------------------------------------------------------- */
4840 * g_dbus_connection_unregister_subtree:
4841 * @connection: A #GDBusConnection.
4842 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4844 * Unregisters a subtree.
4846 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4851 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4852 guint registration_id)
4854 ExportedSubtree *es;
4857 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4861 CONNECTION_LOCK (connection);
4863 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4864 GUINT_TO_POINTER (registration_id));
4870 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4871 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4876 CONNECTION_UNLOCK (connection);
4881 /* ---------------------------------------------------------------------------------------------------- */
4883 /* must be called with lock held */
4885 handle_generic_ping_unlocked (GDBusConnection *connection,
4886 const gchar *object_path,
4887 GDBusMessage *message)
4889 GDBusMessage *reply;
4890 reply = g_dbus_message_new_method_reply (message);
4891 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4892 g_object_unref (reply);
4895 /* must be called with lock held */
4897 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4898 const gchar *object_path,
4899 GDBusMessage *message)
4901 GDBusMessage *reply;
4904 if (connection->priv->machine_id == NULL)
4908 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4909 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4910 &connection->priv->machine_id,
4914 reply = g_dbus_message_new_method_error (message,
4915 "org.freedesktop.DBus.Error.Failed",
4916 _("Unable to load /var/lib/dbus/machine-id: %s"),
4918 g_error_free (error);
4922 g_strstrip (connection->priv->machine_id);
4923 /* TODO: validate value */
4929 reply = g_dbus_message_new_method_reply (message);
4930 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4932 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4933 g_object_unref (reply);
4936 /* must be called with lock held */
4938 handle_generic_introspect_unlocked (GDBusConnection *connection,
4939 const gchar *object_path,
4940 GDBusMessage *message)
4945 GDBusMessage *reply;
4947 /* first the header */
4948 s = g_string_new (NULL);
4949 introspect_append_header (s);
4951 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4952 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4954 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4956 g_strfreev (registered);
4957 g_string_append (s, "</node>\n");
4959 reply = g_dbus_message_new_method_reply (message);
4960 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4961 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4962 g_object_unref (reply);
4963 g_string_free (s, TRUE);
4966 /* must be called with lock held */
4968 handle_generic_unlocked (GDBusConnection *connection,
4969 GDBusMessage *message)
4972 const gchar *interface_name;
4973 const gchar *member;
4974 const gchar *signature;
4977 CONNECTION_ENSURE_LOCK (connection);
4981 interface_name = g_dbus_message_get_interface (message);
4982 member = g_dbus_message_get_member (message);
4983 signature = g_dbus_message_get_signature (message);
4984 path = g_dbus_message_get_path (message);
4986 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4987 g_strcmp0 (member, "Introspect") == 0 &&
4988 g_strcmp0 (signature, "") == 0)
4990 handle_generic_introspect_unlocked (connection, path, message);
4993 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4994 g_strcmp0 (member, "Ping") == 0 &&
4995 g_strcmp0 (signature, "") == 0)
4997 handle_generic_ping_unlocked (connection, path, message);
5000 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5001 g_strcmp0 (member, "GetMachineId") == 0 &&
5002 g_strcmp0 (signature, "") == 0)
5004 handle_generic_get_machine_id_unlocked (connection, path, message);
5011 /* ---------------------------------------------------------------------------------------------------- */
5013 /* called in message handler thread with lock held */
5015 distribute_method_call (GDBusConnection *connection,
5016 GDBusMessage *message)
5019 ExportedSubtree *es;
5020 const gchar *object_path;
5021 const gchar *interface_name;
5022 const gchar *member;
5023 const gchar *signature;
5025 gchar *subtree_path;
5028 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5030 interface_name = g_dbus_message_get_interface (message);
5031 member = g_dbus_message_get_member (message);
5032 signature = g_dbus_message_get_signature (message);
5033 path = g_dbus_message_get_path (message);
5034 subtree_path = g_strdup (path);
5035 needle = strrchr (subtree_path, '/');
5036 if (needle != NULL && needle != subtree_path)
5042 g_free (subtree_path);
5043 subtree_path = NULL;
5047 g_debug ("interface = `%s'", interface_name);
5048 g_debug ("member = `%s'", member);
5049 g_debug ("signature = `%s'", signature);
5050 g_debug ("path = `%s'", path);
5051 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5054 object_path = g_dbus_message_get_path (message);
5055 g_assert (object_path != NULL);
5057 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5060 if (obj_message_func (connection, eo, message))
5064 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5067 if (subtree_message_func (connection, es, message))
5071 if (subtree_path != NULL)
5073 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5076 if (subtree_message_func (connection, es, message))
5081 if (handle_generic_unlocked (connection, message))
5084 /* if we end up here, the message has not been not handled */
5087 g_free (subtree_path);
5090 /* ---------------------------------------------------------------------------------------------------- */
5092 static GDBusConnection **
5093 message_bus_get_singleton (GBusType bus_type,
5096 GDBusConnection **ret;
5097 const gchar *starter_bus;
5104 g_assert_not_reached ();
5107 case G_BUS_TYPE_SESSION:
5108 ret = &the_session_bus;
5111 case G_BUS_TYPE_SYSTEM:
5112 ret = &the_system_bus;
5115 case G_BUS_TYPE_STARTER:
5116 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5117 if (g_strcmp0 (starter_bus, "session") == 0)
5119 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5122 else if (g_strcmp0 (starter_bus, "system") == 0)
5124 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5129 if (starter_bus != NULL)
5133 G_IO_ERROR_INVALID_ARGUMENT,
5134 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5135 " - unknown value `%s'"),
5140 g_set_error_literal (error,
5142 G_IO_ERROR_INVALID_ARGUMENT,
5143 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5144 "variable is not set"));
5153 static GDBusConnection *
5154 get_uninitialized_connection (GBusType bus_type,
5155 GCancellable *cancellable,
5158 GDBusConnection **singleton;
5159 GDBusConnection *ret;
5163 G_LOCK (message_bus_lock);
5164 singleton = message_bus_get_singleton (bus_type, error);
5165 if (singleton == NULL)
5168 if (*singleton == NULL)
5171 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5172 if (address == NULL)
5174 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5176 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5177 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5178 "exit-on-close", TRUE,
5183 ret = g_object_ref (*singleton);
5186 g_assert (ret != NULL);
5189 G_UNLOCK (message_bus_lock);
5195 * @bus_type: A #GBusType.
5196 * @cancellable: A #GCancellable or %NULL.
5197 * @error: Return location for error or %NULL.
5199 * Synchronously connects to the message bus specified by @bus_type.
5200 * Note that the returned object may shared with other callers,
5201 * e.g. if two separate parts of a process calls this function with
5202 * the same @bus_type, they will share the same object.
5204 * This is a synchronous failable function. See g_bus_get() and
5205 * g_bus_get_finish() for the asynchronous version.
5207 * The returned object is a singleton, that is, shared with other
5208 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5209 * event that you need a private message bus connection, use
5210 * g_dbus_address_get_for_bus() and
5211 * g_dbus_connection_new_for_address().
5213 * Note that the returned #GDBusConnection object will (usually) have
5214 * the #GDBusConnection:exit-on-close property set to %TRUE.
5216 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5221 g_bus_get_sync (GBusType bus_type,
5222 GCancellable *cancellable,
5225 GDBusConnection *connection;
5227 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5229 connection = get_uninitialized_connection (bus_type, cancellable, error);
5230 if (connection == NULL)
5233 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5235 g_object_unref (connection);
5244 bus_get_async_initable_cb (GObject *source_object,
5248 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5252 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5256 g_assert (error != NULL);
5257 g_simple_async_result_set_from_error (simple, error);
5258 g_error_free (error);
5259 g_object_unref (source_object);
5263 g_simple_async_result_set_op_res_gpointer (simple,
5267 g_simple_async_result_complete_in_idle (simple);
5268 g_object_unref (simple);
5273 * @bus_type: A #GBusType.
5274 * @cancellable: A #GCancellable or %NULL.
5275 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5276 * @user_data: The data to pass to @callback.
5278 * Asynchronously connects to the message bus specified by @bus_type.
5280 * When the operation is finished, @callback will be invoked. You can
5281 * then call g_bus_get_finish() to get the result of the operation.
5283 * This is a asynchronous failable function. See g_bus_get_sync() for
5284 * the synchronous version.
5289 g_bus_get (GBusType bus_type,
5290 GCancellable *cancellable,
5291 GAsyncReadyCallback callback,
5294 GDBusConnection *connection;
5295 GSimpleAsyncResult *simple;
5298 simple = g_simple_async_result_new (NULL,
5304 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5305 if (connection == NULL)
5307 g_assert (error != NULL);
5308 g_simple_async_result_set_from_error (simple, error);
5309 g_error_free (error);
5310 g_simple_async_result_complete_in_idle (simple);
5311 g_object_unref (simple);
5315 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5318 bus_get_async_initable_cb,
5325 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5326 * @error: Return location for error or %NULL.
5328 * Finishes an operation started with g_bus_get().
5330 * The returned object is a singleton, that is, shared with other
5331 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5332 * event that you need a private message bus connection, use
5333 * g_dbus_address_get_for_bus() and
5334 * g_dbus_connection_new_for_address().
5336 * Note that the returned #GDBusConnection object will (usually) have
5337 * the #GDBusConnection:exit-on-close property set to %TRUE.
5339 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5344 g_bus_get_finish (GAsyncResult *res,
5347 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5349 GDBusConnection *ret;
5351 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5353 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5357 if (g_simple_async_result_propagate_error (simple, error))
5360 object = g_simple_async_result_get_op_res_gpointer (simple);
5361 g_assert (object != NULL);
5362 ret = g_object_ref (G_DBUS_CONNECTION (object));
5368 /* ---------------------------------------------------------------------------------------------------- */
5370 #define __G_DBUS_CONNECTION_C__
5371 #include "gioaliasdef.c"