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.
53 #include <glib/gi18n.h>
56 #include <gio/gunixconnection.h>
57 #include <gio/gunixfdmessage.h>
61 #include <sys/types.h>
64 #include "gdbusauth.h"
66 #include "gdbusutils.h"
67 #include "gdbusaddress.h"
68 #include "gdbusmessage.h"
69 #include "gdbusconnection.h"
70 #include "gdbuserror.h"
71 #include "gioenumtypes.h"
72 #include "gdbusintrospection.h"
73 #include "gdbusmethodinvocation.h"
74 #include "gdbusprivate.h"
75 #include "gdbusauthobserver.h"
76 #include "gio-marshal.h"
79 * SECTION:gdbusconnection
80 * @short_description: D-Bus Connections
84 * This class is rarely used directly in D-Bus clients. If you are
85 * writing an D-Bus client, it is often easier to use the
86 * g_bus_own_name(), g_bus_watch_name() or g_bus_watch_proxy() APIs.
89 * The #GDBusConnection type is used for D-Bus connections to remote
90 * peers such as a message buses.
92 * <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>
94 * <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>
96 * <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>
99 /* ---------------------------------------------------------------------------------------------------- */
101 G_LOCK_DEFINE_STATIC (message_bus_lock);
103 static GDBusConnection *the_session_bus = NULL;
104 static GDBusConnection *the_system_bus = NULL;
106 /* ---------------------------------------------------------------------------------------------------- */
109 _g_strv_has_string (const gchar* const * haystack,
114 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
116 if (g_strcmp0 (haystack[n], needle) == 0)
122 /* ---------------------------------------------------------------------------------------------------- */
125 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
127 // TODO: for some reason this doesn't work on Windows
128 #define CONNECTION_ENSURE_LOCK(obj) do { \
129 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
131 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
132 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
137 #define CONNECTION_LOCK(obj) do { \
138 g_mutex_lock ((obj)->priv->lock); \
141 #define CONNECTION_UNLOCK(obj) do { \
142 g_mutex_unlock ((obj)->priv->lock); \
145 struct _GDBusConnectionPrivate
147 /* ------------------------------------------------------------------------ */
148 /* -- General object state ------------------------------------------------ */
149 /* ------------------------------------------------------------------------ */
151 /* object-wide lock */
154 /* A lock used in the init() method of the GInitable interface - see comments
155 * in initable_init() for why a separate lock is needed
159 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
160 * someone calls org.freedesktop.DBus.GetMachineId()
164 /* The underlying stream used for communication */
167 /* The object used for authentication (if any) */
170 /* Set to TRUE if the connection has been closed */
173 /* Last serial used */
176 /* The object used to send/receive message */
179 /* If connected to a message bus, this contains the unique name assigned to
180 * us by the bus (e.g. ":1.42")
182 gchar *bus_unique_name;
184 /* The GUID returned by the other side if we authenticed as a client or
185 * the GUID to use if authenticating as a server
189 /* set to TRUE exactly when initable_init() has finished running */
190 gboolean is_initialized;
192 /* If the connection could not be established during initable_init(), this GError will set */
193 GError *initialization_error;
195 /* The result of g_main_context_get_thread_default() when the object
196 * was created (the GObject _init() function) - this is used for delivery
197 * of the :closed GObject signal.
199 GMainContext *main_context_at_construction;
201 /* construct properties */
203 GDBusConnectionFlags flags;
205 /* Map used for managing method replies */
206 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
208 /* Maps used for managing signal subscription */
209 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
210 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
211 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
213 /* Maps used for managing exported objects and subtrees */
214 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
215 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
216 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
217 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
219 /* Structure used for message filters */
222 /* Whether to exit on close */
223 gboolean exit_on_close;
225 /* Capabilities negotiated during authentication */
226 GDBusCapabilityFlags capabilities;
228 GDBusAuthObserver *authentication_observer;
229 GCredentials *crendentials;
232 typedef struct ExportedObject ExportedObject;
233 static void exported_object_free (ExportedObject *eo);
235 typedef struct ExportedSubtree ExportedSubtree;
236 static void exported_subtree_free (ExportedSubtree *es);
254 PROP_CAPABILITY_FLAGS,
255 PROP_AUTHENTICATION_OBSERVER,
258 static void distribute_signals (GDBusConnection *connection,
259 GDBusMessage *message);
261 static void distribute_method_call (GDBusConnection *connection,
262 GDBusMessage *message);
264 static gboolean handle_generic_unlocked (GDBusConnection *connection,
265 GDBusMessage *message);
268 static void purge_all_signal_subscriptions (GDBusConnection *connection);
269 static void purge_all_filters (GDBusConnection *connection);
271 #define _G_ENSURE_LOCK(name) do { \
272 if (G_UNLIKELY (G_TRYLOCK(name))) \
274 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
275 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
279 static guint signals[LAST_SIGNAL] = { 0 };
281 static void initable_iface_init (GInitableIface *initable_iface);
282 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
284 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
285 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
286 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
290 g_dbus_connection_dispose (GObject *object)
292 GDBusConnection *connection = G_DBUS_CONNECTION (object);
294 G_LOCK (message_bus_lock);
295 //g_debug ("disposing %p", connection);
296 if (connection == the_session_bus)
298 the_session_bus = NULL;
300 else if (connection == the_system_bus)
302 the_system_bus = NULL;
304 if (connection->priv->worker != NULL)
306 _g_dbus_worker_stop (connection->priv->worker);
307 connection->priv->worker = NULL;
309 G_UNLOCK (message_bus_lock);
311 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
312 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
316 g_dbus_connection_finalize (GObject *object)
318 GDBusConnection *connection = G_DBUS_CONNECTION (object);
320 if (connection->priv->authentication_observer != NULL)
321 g_object_unref (connection->priv->authentication_observer);
323 if (connection->priv->auth != NULL)
324 g_object_unref (connection->priv->auth);
326 //g_debug ("finalizing %p", connection);
327 if (connection->priv->stream != NULL)
329 /* We don't really care if closing the stream succeeds or not */
330 g_io_stream_close_async (connection->priv->stream,
332 NULL, /* GCancellable */
333 NULL, /* GAsyncReadyCallback */
334 NULL); /* userdata */
335 g_object_unref (connection->priv->stream);
336 connection->priv->stream = NULL;
339 g_free (connection->priv->address);
341 g_free (connection->priv->guid);
342 g_free (connection->priv->bus_unique_name);
344 if (connection->priv->initialization_error != NULL)
345 g_error_free (connection->priv->initialization_error);
347 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
349 purge_all_signal_subscriptions (connection);
350 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
351 g_hash_table_unref (connection->priv->map_id_to_signal_data);
352 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
354 g_hash_table_unref (connection->priv->map_id_to_ei);
355 g_hash_table_unref (connection->priv->map_object_path_to_eo);
356 g_hash_table_unref (connection->priv->map_id_to_es);
357 g_hash_table_unref (connection->priv->map_object_path_to_es);
359 purge_all_filters (connection);
360 g_ptr_array_unref (connection->priv->filters);
362 if (connection->priv->main_context_at_construction != NULL)
363 g_main_context_unref (connection->priv->main_context_at_construction);
365 g_free (connection->priv->machine_id);
367 g_mutex_free (connection->priv->init_lock);
368 g_mutex_free (connection->priv->lock);
370 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize != NULL)
371 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
375 g_dbus_connection_get_property (GObject *object,
380 GDBusConnection *connection = G_DBUS_CONNECTION (object);
385 g_value_set_object (value, g_dbus_connection_get_stream (connection));
389 g_value_set_string (value, g_dbus_connection_get_guid (connection));
392 case PROP_UNIQUE_NAME:
393 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
397 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
400 case PROP_EXIT_ON_CLOSE:
401 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
404 case PROP_CAPABILITY_FLAGS:
405 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
409 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
415 g_dbus_connection_set_property (GObject *object,
420 GDBusConnection *connection = G_DBUS_CONNECTION (object);
425 connection->priv->stream = g_value_dup_object (value);
429 connection->priv->guid = g_value_dup_string (value);
433 connection->priv->address = g_value_dup_string (value);
437 connection->priv->flags = g_value_get_flags (value);
440 case PROP_EXIT_ON_CLOSE:
441 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
444 case PROP_AUTHENTICATION_OBSERVER:
445 connection->priv->authentication_observer = g_value_dup_object (value);
449 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
455 g_dbus_connection_real_closed (GDBusConnection *connection,
456 gboolean remote_peer_vanished,
459 if (remote_peer_vanished && connection->priv->exit_on_close)
461 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
467 g_dbus_connection_class_init (GDBusConnectionClass *klass)
469 GObjectClass *gobject_class;
471 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
473 gobject_class = G_OBJECT_CLASS (klass);
475 gobject_class->finalize = g_dbus_connection_finalize;
476 gobject_class->dispose = g_dbus_connection_dispose;
477 gobject_class->set_property = g_dbus_connection_set_property;
478 gobject_class->get_property = g_dbus_connection_get_property;
480 klass->closed = g_dbus_connection_real_closed;
483 * GDBusConnection:stream:
485 * The underlying #GIOStream used for I/O.
489 g_object_class_install_property (gobject_class,
491 g_param_spec_object ("stream",
493 _("The underlying streams used for I/O"),
497 G_PARAM_CONSTRUCT_ONLY |
498 G_PARAM_STATIC_NAME |
499 G_PARAM_STATIC_BLURB |
500 G_PARAM_STATIC_NICK));
503 * GDBusConnection:address:
505 * A D-Bus address specifying potential endpoints that can be used
506 * when establishing the connection.
510 g_object_class_install_property (gobject_class,
512 g_param_spec_string ("address",
514 _("D-Bus address specifying potential socket endpoints"),
517 G_PARAM_CONSTRUCT_ONLY |
518 G_PARAM_STATIC_NAME |
519 G_PARAM_STATIC_BLURB |
520 G_PARAM_STATIC_NICK));
523 * GDBusConnection:flags:
525 * Flags from the #GDBusConnectionFlags enumeration.
529 g_object_class_install_property (gobject_class,
531 g_param_spec_flags ("flags",
534 G_TYPE_DBUS_CONNECTION_FLAGS,
535 G_DBUS_CONNECTION_FLAGS_NONE,
537 G_PARAM_CONSTRUCT_ONLY |
538 G_PARAM_STATIC_NAME |
539 G_PARAM_STATIC_BLURB |
540 G_PARAM_STATIC_NICK));
543 * GDBusConnection:guid:
545 * The GUID of the peer performing the role of server when
548 * If you are constructing a #GDBusConnection and pass
549 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
550 * #GDBusConnection:flags property then you MUST also set this
551 * property to a valid guid.
553 * If you are constructing a #GDBusConnection and pass
554 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
555 * #GDBusConnection:flags property you will be able to read the GUID
556 * of the other peer here after the connection has been succesfully
561 g_object_class_install_property (gobject_class,
563 g_param_spec_string ("guid",
565 _("GUID of the server peer"),
569 G_PARAM_CONSTRUCT_ONLY |
570 G_PARAM_STATIC_NAME |
571 G_PARAM_STATIC_BLURB |
572 G_PARAM_STATIC_NICK));
575 * GDBusConnection:unique-name:
577 * The unique name as assigned by the message bus or %NULL if the
578 * connection is not open or not a message bus connection.
582 g_object_class_install_property (gobject_class,
584 g_param_spec_string ("unique-name",
586 _("Unique name of bus connection"),
589 G_PARAM_STATIC_NAME |
590 G_PARAM_STATIC_BLURB |
591 G_PARAM_STATIC_NICK));
594 * GDBusConnection:closed:
596 * A boolean specifying whether the connection has been closed.
600 g_object_class_install_property (gobject_class,
602 g_param_spec_boolean ("closed",
604 _("Whether the connection is closed"),
607 G_PARAM_STATIC_NAME |
608 G_PARAM_STATIC_BLURB |
609 G_PARAM_STATIC_NICK));
612 * GDBusConnection:exit-on-close:
614 * A boolean specifying whether the process will be terminated (by
615 * calling <literal>raise(SIGTERM)</literal>) if the connection
616 * is closed by the remote peer.
620 g_object_class_install_property (gobject_class,
622 g_param_spec_boolean ("exit-on-close",
624 _("Whether the process is terminated when the connection is closed"),
628 G_PARAM_STATIC_NAME |
629 G_PARAM_STATIC_BLURB |
630 G_PARAM_STATIC_NICK));
633 * GDBusConnection:capabilities:
635 * Flags from the #GDBusCapabilityFlags enumeration
636 * representing connection features negotiated with the other peer.
640 g_object_class_install_property (gobject_class,
641 PROP_CAPABILITY_FLAGS,
642 g_param_spec_flags ("capabilities",
645 G_TYPE_DBUS_CAPABILITY_FLAGS,
646 G_DBUS_CAPABILITY_FLAGS_NONE,
648 G_PARAM_STATIC_NAME |
649 G_PARAM_STATIC_BLURB |
650 G_PARAM_STATIC_NICK));
653 * GDBusConnection:authentication-observer:
655 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
659 g_object_class_install_property (gobject_class,
660 PROP_AUTHENTICATION_OBSERVER,
661 g_param_spec_object ("authentication-observer",
662 _("Authentication Observer"),
663 _("Object used to assist in the authentication process"),
664 G_TYPE_DBUS_AUTH_OBSERVER,
666 G_PARAM_CONSTRUCT_ONLY |
667 G_PARAM_STATIC_NAME |
668 G_PARAM_STATIC_BLURB |
669 G_PARAM_STATIC_NICK));
672 * GDBusConnection::closed:
673 * @connection: The #GDBusConnection emitting the signal.
674 * @remote_peer_vanished: %TRUE if @connection is closed because the
675 * remote peer closed its end of the connection.
676 * @error: A #GError with more details about the event or %NULL.
678 * Emitted when the connection is closed.
680 * The cause of this event can be
683 * If g_dbus_connection_close() is called. In this case
684 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
687 * If the remote peer closes the connection. In this case
688 * @remote_peer_vanished is set to %TRUE and @error is set.
691 * If the remote peer sends invalid or malformed data. In this
692 * case @remote_peer_vanished is set to %FALSE and @error
697 * Upon receiving this signal, you should give up your reference to
698 * @connection. You are guaranteed that this signal is emitted only
703 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
704 G_TYPE_DBUS_CONNECTION,
706 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
709 _gio_marshal_VOID__BOOLEAN_BOXED,
717 g_dbus_connection_init (GDBusConnection *connection)
719 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
721 connection->priv->lock = g_mutex_new ();
722 connection->priv->init_lock = g_mutex_new ();
724 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
726 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
728 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
730 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
735 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
738 (GDestroyNotify) exported_object_free);
740 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
743 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
746 (GDestroyNotify) exported_subtree_free);
748 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
751 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
752 if (connection->priv->main_context_at_construction != NULL)
753 g_main_context_ref (connection->priv->main_context_at_construction);
755 connection->priv->filters = g_ptr_array_new ();
759 g_dbus_connection_get_stream (GDBusConnection *connection)
761 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
762 return connection->priv->stream;
767 * g_dbus_connection_is_closed:
768 * @connection: A #GDBusConnection.
770 * Gets whether @connection is closed.
772 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
777 g_dbus_connection_is_closed (GDBusConnection *connection)
779 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
780 return connection->priv->closed;
784 * g_dbus_connection_get_capabilities:
785 * @connection: A #GDBusConnection.
787 * Gets the capabilities negotiated with the remote peer
789 * Returns: One or more flags from the #GDBusCapabilityFlags enumeration.
794 g_dbus_connection_get_capabilities (GDBusConnection *connection)
796 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
797 return connection->priv->capabilities;
801 /* ---------------------------------------------------------------------------------------------------- */
805 GDBusConnection *connection;
807 gboolean remote_peer_vanished;
811 emit_closed_data_free (EmitClosedData *data)
813 g_object_unref (data->connection);
814 if (data->error != NULL)
815 g_error_free (data->error);
820 emit_closed_in_idle (gpointer user_data)
822 EmitClosedData *data = user_data;
825 g_object_notify (G_OBJECT (data->connection), "closed");
826 g_signal_emit (data->connection,
827 signals[CLOSED_SIGNAL],
829 data->remote_peer_vanished,
835 /* Can be called from any thread, must hold lock */
837 set_closed_unlocked (GDBusConnection *connection,
838 gboolean remote_peer_vanished,
841 GSource *idle_source;
842 EmitClosedData *data;
844 CONNECTION_ENSURE_LOCK (connection);
846 g_assert (!connection->priv->closed);
848 connection->priv->closed = TRUE;
850 data = g_new0 (EmitClosedData, 1);
851 data->connection = g_object_ref (connection);
852 data->remote_peer_vanished = remote_peer_vanished;
853 data->error = error != NULL ? g_error_copy (error) : NULL;
855 idle_source = g_idle_source_new ();
856 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
857 g_source_set_callback (idle_source,
860 (GDestroyNotify) emit_closed_data_free);
861 g_source_attach (idle_source, connection->priv->main_context_at_construction);
862 g_source_unref (idle_source);
865 /* ---------------------------------------------------------------------------------------------------- */
868 * g_dbus_connection_close:
869 * @connection: A #GDBusConnection.
871 * Closes @connection. Note that this never causes the process to
872 * exit (this might only happen if the other end of a shared message
873 * bus connection disconnects).
875 * If @connection is already closed, this method does nothing.
880 g_dbus_connection_close (GDBusConnection *connection)
882 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
884 CONNECTION_LOCK (connection);
885 if (!connection->priv->closed)
887 GError *error = NULL;
889 /* TODO: do this async */
890 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
891 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
893 g_warning ("Error closing stream: %s", error->message);
894 g_error_free (error);
897 set_closed_unlocked (connection, FALSE, NULL);
899 CONNECTION_UNLOCK (connection);
902 /* ---------------------------------------------------------------------------------------------------- */
905 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
906 GDBusMessage *message,
907 volatile guint32 *out_serial,
912 guint32 serial_to_use;
915 CONNECTION_ENSURE_LOCK (connection);
917 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
918 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
920 /* TODO: check all necessary headers are present */
925 if (out_serial != NULL)
928 if (connection->priv->closed)
930 g_set_error_literal (error,
933 _("The connection is closed"));
937 blob = g_dbus_message_to_blob (message,
943 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
948 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
951 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
954 g_assert_not_reached ();
959 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
960 blob_size, serial_to_use, connection);
961 g_printerr ("----\n");
962 hexdump (blob, blob_size);
963 g_printerr ("----\n");
966 /* TODO: use connection->priv->auth to encode the blob */
968 if (out_serial != NULL)
970 *out_serial = serial_to_use;
972 g_dbus_message_set_serial (message, serial_to_use);
974 _g_dbus_worker_send_message (connection->priv->worker,
978 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
989 * g_dbus_connection_send_message:
990 * @connection: A #GDBusConnection.
991 * @message: A #GDBusMessage
992 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
993 * @error: Return location for error or %NULL.
995 * Asynchronously sends @message to the peer represented by @connection.
997 * If @out_serial is not %NULL, then the serial number assigned to
998 * @message by @connection will be written to this location prior to
999 * submitting the message to the underlying transport.
1001 * If @connection is closed then the operation will fail with
1002 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1003 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1004 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1006 * See <xref linkend="gdbus-server"/> and <xref
1007 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1008 * low-level API to send and receive UNIX file descriptors.
1010 * Returns: %TRUE if the message was well-formed and queued for
1011 * transmission, %FALSE if @error is set.
1016 g_dbus_connection_send_message (GDBusConnection *connection,
1017 GDBusMessage *message,
1018 volatile guint32 *out_serial,
1023 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1024 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1025 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1027 CONNECTION_LOCK (connection);
1028 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1029 CONNECTION_UNLOCK (connection);
1033 /* ---------------------------------------------------------------------------------------------------- */
1037 volatile gint ref_count;
1038 GDBusConnection *connection;
1040 GSimpleAsyncResult *simple;
1042 GMainContext *main_context;
1044 GCancellable *cancellable;
1046 gulong cancellable_handler_id;
1048 GSource *timeout_source;
1053 static SendMessageData *
1054 send_message_data_ref (SendMessageData *data)
1056 g_atomic_int_inc (&data->ref_count);
1061 send_message_data_unref (SendMessageData *data)
1063 if (g_atomic_int_dec_and_test (&data->ref_count))
1065 g_assert (data->timeout_source == NULL);
1066 g_assert (data->simple == NULL);
1067 g_assert (data->cancellable_handler_id == 0);
1068 g_object_unref (data->connection);
1069 if (data->cancellable != NULL)
1070 g_object_unref (data->cancellable);
1071 if (data->main_context != NULL)
1072 g_main_context_unref (data->main_context);
1077 /* ---------------------------------------------------------------------------------------------------- */
1079 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1081 send_message_with_reply_deliver (SendMessageData *data)
1083 CONNECTION_ENSURE_LOCK (data->connection);
1085 g_assert (!data->delivered);
1087 data->delivered = TRUE;
1089 g_simple_async_result_complete_in_idle (data->simple);
1090 g_object_unref (data->simple);
1091 data->simple = NULL;
1093 if (data->timeout_source != NULL)
1095 g_source_destroy (data->timeout_source);
1096 data->timeout_source = NULL;
1098 if (data->cancellable_handler_id > 0)
1100 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1101 data->cancellable_handler_id = 0;
1104 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1105 GUINT_TO_POINTER (data->serial)));
1107 send_message_data_unref (data);
1110 /* ---------------------------------------------------------------------------------------------------- */
1112 /* must hold lock */
1114 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1115 GDBusMessage *reply)
1117 if (data->delivered)
1120 g_simple_async_result_set_op_res_gpointer (data->simple,
1121 g_object_ref (reply),
1124 send_message_with_reply_deliver (data);
1130 /* ---------------------------------------------------------------------------------------------------- */
1133 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1135 SendMessageData *data = user_data;
1137 CONNECTION_LOCK (data->connection);
1138 if (data->delivered)
1141 g_simple_async_result_set_error (data->simple,
1143 G_IO_ERROR_CANCELLED,
1144 _("Operation was cancelled"));
1146 send_message_with_reply_deliver (data);
1149 CONNECTION_UNLOCK (data->connection);
1153 /* Can be called from any thread with or without lock held */
1155 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1158 SendMessageData *data = user_data;
1159 GSource *idle_source;
1161 /* postpone cancellation to idle handler since we may be called directly
1162 * via g_cancellable_connect() (e.g. holding lock)
1164 idle_source = g_idle_source_new ();
1165 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1166 g_source_set_callback (idle_source,
1167 send_message_with_reply_cancelled_idle_cb,
1168 send_message_data_ref (data),
1169 (GDestroyNotify) send_message_data_unref);
1170 g_source_attach (idle_source, data->main_context);
1171 g_source_unref (idle_source);
1174 /* ---------------------------------------------------------------------------------------------------- */
1177 send_message_with_reply_timeout_cb (gpointer user_data)
1179 SendMessageData *data = user_data;
1181 CONNECTION_LOCK (data->connection);
1182 if (data->delivered)
1185 g_simple_async_result_set_error (data->simple,
1187 G_IO_ERROR_TIMED_OUT,
1188 _("Timeout was reached"));
1190 send_message_with_reply_deliver (data);
1193 CONNECTION_UNLOCK (data->connection);
1198 /* ---------------------------------------------------------------------------------------------------- */
1201 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1202 GDBusMessage *message,
1204 volatile guint32 *out_serial,
1205 GCancellable *cancellable,
1206 GAsyncReadyCallback callback,
1209 GSimpleAsyncResult *simple;
1210 SendMessageData *data;
1212 volatile guint32 serial;
1216 if (out_serial == NULL)
1217 out_serial = &serial;
1219 if (timeout_msec == -1)
1220 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1222 simple = g_simple_async_result_new (G_OBJECT (connection),
1225 g_dbus_connection_send_message_with_reply);
1227 if (g_cancellable_is_cancelled (cancellable))
1229 g_simple_async_result_set_error (simple,
1231 G_IO_ERROR_CANCELLED,
1232 _("Operation was cancelled"));
1233 g_simple_async_result_complete_in_idle (simple);
1234 g_object_unref (simple);
1238 if (connection->priv->closed)
1240 g_simple_async_result_set_error (simple,
1243 _("The connection is closed"));
1244 g_simple_async_result_complete_in_idle (simple);
1245 g_object_unref (simple);
1250 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1252 g_simple_async_result_set_from_error (simple, error);
1253 g_simple_async_result_complete_in_idle (simple);
1254 g_object_unref (simple);
1258 data = g_new0 (SendMessageData, 1);
1259 data->ref_count = 1;
1260 data->connection = g_object_ref (connection);
1261 data->simple = simple;
1262 data->serial = *out_serial;
1263 data->main_context = g_main_context_get_thread_default ();
1264 if (data->main_context != NULL)
1265 g_main_context_ref (data->main_context);
1267 if (cancellable != NULL)
1269 data->cancellable = g_object_ref (cancellable);
1270 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1271 G_CALLBACK (send_message_with_reply_cancelled_cb),
1272 send_message_data_ref (data),
1273 (GDestroyNotify) send_message_data_unref);
1274 g_object_set_data_full (G_OBJECT (simple),
1276 g_object_ref (cancellable),
1277 (GDestroyNotify) g_object_unref);
1280 data->timeout_source = g_timeout_source_new (timeout_msec);
1281 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1282 g_source_set_callback (data->timeout_source,
1283 send_message_with_reply_timeout_cb,
1284 send_message_data_ref (data),
1285 (GDestroyNotify) send_message_data_unref);
1286 g_source_attach (data->timeout_source, data->main_context);
1287 g_source_unref (data->timeout_source);
1289 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1290 GUINT_TO_POINTER (*out_serial),
1298 * g_dbus_connection_send_message_with_reply:
1299 * @connection: A #GDBusConnection.
1300 * @message: A #GDBusMessage.
1301 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1302 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1303 * @cancellable: A #GCancellable or %NULL.
1304 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1305 * care about the result.
1306 * @user_data: The data to pass to @callback.
1308 * Asynchronously sends @message to the peer represented by @connection.
1310 * If @out_serial is not %NULL, then the serial number assigned to
1311 * @message by @connection will be written to this location prior to
1312 * submitting the message to the underlying transport.
1314 * If @connection is closed then the operation will fail with
1315 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1316 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1317 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1319 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1320 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1321 * of the thread you are calling this method from. You can then call
1322 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1323 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1325 * See <xref linkend="gdbus-server"/> and <xref
1326 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1327 * low-level API to send and receive UNIX file descriptors.
1332 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1333 GDBusMessage *message,
1335 volatile guint32 *out_serial,
1336 GCancellable *cancellable,
1337 GAsyncReadyCallback callback,
1340 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1341 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1342 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1344 CONNECTION_LOCK (connection);
1345 g_dbus_connection_send_message_with_reply_unlocked (connection,
1352 CONNECTION_UNLOCK (connection);
1356 * g_dbus_connection_send_message_with_reply_finish:
1357 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1358 * @error: Return location for error or %NULL.
1360 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1362 * Note that @error is only set if a local in-process error
1363 * occured. That is to say that the returned #GDBusMessage object may
1364 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1365 * g_dbus_message_to_gerror() to transcode this to a #GError.
1367 * See <xref linkend="gdbus-server"/> and <xref
1368 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1369 * low-level API to send and receive UNIX file descriptors.
1371 * Returns: A #GDBusMessage or %NULL if @error is set.
1376 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1380 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1381 GDBusMessage *reply;
1382 GCancellable *cancellable;
1384 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1385 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1389 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1391 if (g_simple_async_result_propagate_error (simple, error))
1394 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1395 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1396 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1398 g_object_unref (reply);
1400 g_set_error_literal (error,
1402 G_IO_ERROR_CANCELLED,
1403 _("Operation was cancelled"));
1409 /* ---------------------------------------------------------------------------------------------------- */
1414 GMainContext *context;
1416 } SendMessageSyncData;
1419 send_message_with_reply_sync_cb (GDBusConnection *connection,
1423 SendMessageSyncData *data = user_data;
1424 data->res = g_object_ref (res);
1425 g_main_loop_quit (data->loop);
1429 * g_dbus_connection_send_message_with_reply_sync:
1430 * @connection: A #GDBusConnection.
1431 * @message: A #GDBusMessage.
1432 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1433 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1434 * @cancellable: A #GCancellable or %NULL.
1435 * @error: Return location for error or %NULL.
1437 * Synchronously sends @message to the peer represented by @connection
1438 * and blocks the calling thread until a reply is received or the
1439 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1440 * for the asynchronous version of this method.
1442 * If @out_serial is not %NULL, then the serial number assigned to
1443 * @message by @connection will be written to this location prior to
1444 * submitting the message to the underlying transport.
1446 * If @connection is closed then the operation will fail with
1447 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1448 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1449 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1451 * Note that @error is only set if a local in-process error
1452 * occured. That is to say that the returned #GDBusMessage object may
1453 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1454 * g_dbus_message_to_gerror() to transcode this to a #GError.
1456 * See <xref linkend="gdbus-server"/> and <xref
1457 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1458 * low-level API to send and receive UNIX file descriptors.
1460 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1465 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1466 GDBusMessage *message,
1468 volatile guint32 *out_serial,
1469 GCancellable *cancellable,
1472 SendMessageSyncData *data;
1473 GDBusMessage *reply;
1475 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1476 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1477 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1478 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1480 data = g_new0 (SendMessageSyncData, 1);
1481 data->context = g_main_context_new ();
1482 data->loop = g_main_loop_new (data->context, FALSE);
1484 g_main_context_push_thread_default (data->context);
1486 g_dbus_connection_send_message_with_reply (connection,
1491 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1493 g_main_loop_run (data->loop);
1494 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1498 g_main_context_pop_thread_default (data->context);
1500 g_main_context_unref (data->context);
1501 g_main_loop_unref (data->loop);
1502 g_object_unref (data->res);
1508 /* ---------------------------------------------------------------------------------------------------- */
1512 GDBusMessageFilterFunction func;
1519 GDBusMessageFilterFunction filter_function;
1521 GDestroyNotify user_data_free_func;
1524 /* Called in worker's thread - we must not block */
1526 on_worker_message_received (GDBusWorker *worker,
1527 GDBusMessage *message,
1530 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1531 FilterCallback *filters;
1532 gboolean consumed_by_filter;
1536 //g_debug ("in on_worker_message_received");
1538 g_object_ref (connection);
1540 /* First collect the set of callback functions */
1541 CONNECTION_LOCK (connection);
1542 num_filters = connection->priv->filters->len;
1543 filters = g_new0 (FilterCallback, num_filters);
1544 for (n = 0; n < num_filters; n++)
1546 FilterData *data = connection->priv->filters->pdata[n];
1547 filters[n].func = data->filter_function;
1548 filters[n].user_data = data->user_data;
1550 CONNECTION_UNLOCK (connection);
1552 /* the call the filters in order (without holding the lock) */
1553 consumed_by_filter = FALSE;
1554 for (n = 0; n < num_filters; n++)
1556 consumed_by_filter = filters[n].func (connection,
1558 filters[n].user_data);
1559 if (consumed_by_filter)
1563 /* Standard dispatch unless the filter ate the message */
1564 if (!consumed_by_filter)
1566 GDBusMessageType message_type;
1568 message_type = g_dbus_message_get_type (message);
1569 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1571 guint32 reply_serial;
1572 SendMessageData *send_message_data;
1574 reply_serial = g_dbus_message_get_reply_serial (message);
1575 CONNECTION_LOCK (connection);
1576 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1577 GUINT_TO_POINTER (reply_serial));
1578 if (send_message_data != NULL)
1580 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1581 send_message_data_deliver_reply_unlocked (send_message_data, message);
1585 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1587 CONNECTION_UNLOCK (connection);
1589 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1591 CONNECTION_LOCK (connection);
1592 distribute_signals (connection, message);
1593 CONNECTION_UNLOCK (connection);
1595 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1597 CONNECTION_LOCK (connection);
1598 distribute_method_call (connection, message);
1599 CONNECTION_UNLOCK (connection);
1603 g_object_unref (connection);
1607 /* Called in worker's thread - we must not block */
1609 on_worker_closed (GDBusWorker *worker,
1610 gboolean remote_peer_vanished,
1614 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1616 //g_debug ("in on_worker_closed: %s", error->message);
1618 CONNECTION_LOCK (connection);
1619 if (!connection->priv->closed)
1620 set_closed_unlocked (connection, remote_peer_vanished, error);
1621 CONNECTION_UNLOCK (connection);
1624 /* ---------------------------------------------------------------------------------------------------- */
1626 /* Determines the biggest set of capabilities we can support on this connection */
1627 static GDBusCapabilityFlags
1628 get_offered_capabilities_max (GDBusConnection *connection)
1630 GDBusCapabilityFlags ret;
1631 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1633 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1635 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1643 initable_init (GInitable *initable,
1644 GCancellable *cancellable,
1647 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1650 /* This method needs to be idempotent to work with the singleton
1651 * pattern. See the docs for g_initable_init(). We implement this by
1654 * Unfortunately we can't use the main lock since the on_worker_*()
1655 * callbacks above needs the lock during initialization (for message
1656 * bus connections we do a synchronous Hello() call on the bus).
1658 g_mutex_lock (connection->priv->init_lock);
1662 if (connection->priv->is_initialized)
1664 if (connection->priv->stream != NULL)
1667 g_assert (connection->priv->initialization_error != NULL);
1670 g_assert (connection->priv->initialization_error == NULL);
1672 /* The user can pass multiple (but mutally exclusive) construct
1675 * - stream (of type GIOStream)
1676 * - address (of type gchar*)
1678 * At the end of the day we end up with a non-NULL GIOStream
1679 * object in connection->priv->stream.
1681 if (connection->priv->address != NULL)
1683 g_assert (connection->priv->stream == NULL);
1685 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1686 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1688 g_set_error_literal (error,
1690 G_IO_ERROR_INVALID_ARGUMENT,
1691 _("Unsupported flags encountered when constructing a client-side connection"));
1695 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1696 NULL, /* TODO: out_guid */
1698 &connection->priv->initialization_error);
1699 if (connection->priv->stream == NULL)
1702 else if (connection->priv->stream != NULL)
1708 g_assert_not_reached ();
1711 /* Authenticate the connection */
1712 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1714 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1715 g_assert (connection->priv->guid != NULL);
1716 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1717 if (!_g_dbus_auth_run_server (connection->priv->auth,
1718 connection->priv->authentication_observer,
1719 connection->priv->guid,
1720 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1721 get_offered_capabilities_max (connection),
1722 &connection->priv->capabilities,
1723 &connection->priv->crendentials,
1725 &connection->priv->initialization_error))
1728 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1730 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1731 g_assert (connection->priv->guid == NULL);
1732 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1733 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1734 get_offered_capabilities_max (connection),
1735 &connection->priv->capabilities,
1737 &connection->priv->initialization_error);
1738 if (connection->priv->guid == NULL)
1742 if (connection->priv->authentication_observer != NULL)
1744 g_object_unref (connection->priv->authentication_observer);
1745 connection->priv->authentication_observer = NULL;
1748 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1750 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1754 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1758 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1760 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1763 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1764 connection->priv->capabilities,
1765 on_worker_message_received,
1769 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1770 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1772 GVariant *hello_result;
1775 hello_result = g_dbus_connection_invoke_method_sync (connection,
1776 "org.freedesktop.DBus", /* name */
1777 "/org/freedesktop/DBus", /* path */
1778 "org.freedesktop.DBus", /* interface */
1780 NULL, /* parameters */
1781 G_DBUS_INVOKE_METHOD_FLAGS_NONE,
1783 NULL, /* TODO: cancellable */
1784 &connection->priv->initialization_error);
1785 if (hello_result == NULL)
1788 g_variant_get (hello_result, "(s)", &s);
1789 connection->priv->bus_unique_name = g_strdup (s);
1790 g_variant_unref (hello_result);
1791 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1794 connection->priv->is_initialized = TRUE;
1800 g_assert (connection->priv->initialization_error != NULL);
1801 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1804 g_mutex_unlock (connection->priv->init_lock);
1810 initable_iface_init (GInitableIface *initable_iface)
1812 initable_iface->init = initable_init;
1815 /* ---------------------------------------------------------------------------------------------------- */
1818 async_init_thread (GSimpleAsyncResult *res,
1820 GCancellable *cancellable)
1822 GError *error = NULL;
1824 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1826 g_simple_async_result_set_from_error (res, error);
1827 g_error_free (error);
1832 async_initable_init_async (GAsyncInitable *initable,
1834 GCancellable *cancellable,
1835 GAsyncReadyCallback callback,
1838 GSimpleAsyncResult *res;
1840 g_return_if_fail (G_IS_INITABLE (initable));
1842 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1843 async_initable_init_async);
1844 g_simple_async_result_run_in_thread (res, async_init_thread,
1845 io_priority, cancellable);
1846 g_object_unref (res);
1850 async_initable_init_finish (GAsyncInitable *initable,
1854 return TRUE; /* Errors handled by base impl */
1858 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1860 /* We basically just want to use GIO's default implementation - though that one is
1861 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1863 async_initable_iface->init_async = async_initable_init_async;
1864 async_initable_iface->init_finish = async_initable_init_finish;
1867 /* ---------------------------------------------------------------------------------------------------- */
1870 * g_dbus_connection_new:
1871 * @stream: A #GIOStream.
1872 * @guid: The GUID to use if a authenticating as a server or %NULL.
1873 * @flags: Flags describing how to make the connection.
1874 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1875 * @cancellable: A #GCancellable or %NULL.
1876 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1877 * @user_data: The data to pass to @callback.
1879 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1880 * with the end represented by @stream.
1882 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1883 * @auth_observer (if not %NULL) is used to assist in the client
1884 * authentication process.
1886 * When the operation is finished, @callback will be invoked. You can
1887 * then call g_dbus_connection_new_finish() to get the result of the
1890 * This is a asynchronous failable constructor. See
1891 * g_dbus_connection_new_sync() for the synchronous
1897 g_dbus_connection_new (GIOStream *stream,
1899 GDBusConnectionFlags flags,
1900 GDBusAuthObserver *authentication_observer,
1901 GCancellable *cancellable,
1902 GAsyncReadyCallback callback,
1905 g_return_if_fail (G_IS_IO_STREAM (stream));
1906 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1914 "authentication-observer", authentication_observer,
1919 * g_dbus_connection_new_finish:
1920 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1921 * @error: Return location for error or %NULL.
1923 * Finishes an operation started with g_dbus_connection_new().
1925 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1930 g_dbus_connection_new_finish (GAsyncResult *res,
1934 GObject *source_object;
1936 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1937 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1939 source_object = g_async_result_get_source_object (res);
1940 g_assert (source_object != NULL);
1941 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1944 g_object_unref (source_object);
1946 return G_DBUS_CONNECTION (object);
1952 * g_dbus_connection_new_sync:
1953 * @stream: A #GIOStream.
1954 * @guid: The GUID to use if a authenticating as a server or %NULL.
1955 * @flags: Flags describing how to make the connection.
1956 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1957 * @cancellable: A #GCancellable or %NULL.
1958 * @error: Return location for error or %NULL.
1960 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1961 * with the end represented by @stream.
1963 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1964 * @auth_observer (if not %NULL) is used to assist in the client
1965 * authentication process.
1967 * This is a synchronous failable constructor. See
1968 * g_dbus_connection_new() for the asynchronous version.
1970 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1975 g_dbus_connection_new_sync (GIOStream *stream,
1977 GDBusConnectionFlags flags,
1978 GDBusAuthObserver *authentication_observer,
1979 GCancellable *cancellable,
1982 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
1983 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1984 return g_initable_new (G_TYPE_DBUS_CONNECTION,
1990 "authentication-observer", authentication_observer,
1994 /* ---------------------------------------------------------------------------------------------------- */
1997 * g_dbus_connection_new_for_address:
1998 * @address: A D-Bus address.
1999 * @flags: Flags describing how to make the connection.
2000 * @cancellable: A #GCancellable or %NULL.
2001 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2002 * @user_data: The data to pass to @callback.
2004 * Asynchronously connects and sets up a D-Bus client connection for
2005 * exchanging D-Bus messages with an endpoint specified by @address
2006 * which must be in the D-Bus address format.
2008 * This constructor can only be used to initiate client-side
2009 * connections - use g_dbus_connection_new() if you need to act as the
2010 * server. In particular, @flags cannot contain the
2011 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2012 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2014 * When the operation is finished, @callback will be invoked. You can
2015 * then call g_dbus_connection_new_finish() to get the result of the
2018 * This is a asynchronous failable constructor. See
2019 * g_dbus_connection_new_for_address_sync() for the synchronous
2025 g_dbus_connection_new_for_address (const gchar *address,
2026 GDBusConnectionFlags flags,
2027 GCancellable *cancellable,
2028 GAsyncReadyCallback callback,
2031 g_return_if_fail (address != NULL);
2032 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2043 * g_dbus_connection_new_for_address_finish:
2044 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2045 * @error: Return location for error or %NULL.
2047 * Finishes an operation started with g_dbus_connection_new_for_address().
2049 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2054 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2058 GObject *source_object;
2060 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2061 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2063 source_object = g_async_result_get_source_object (res);
2064 g_assert (source_object != NULL);
2065 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2068 g_object_unref (source_object);
2070 return G_DBUS_CONNECTION (object);
2076 * g_dbus_connection_new_for_address_sync:
2077 * @address: A D-Bus address.
2078 * @flags: Flags describing how to make the connection.
2079 * @cancellable: A #GCancellable or %NULL.
2080 * @error: Return location for error or %NULL.
2082 * Synchronously connects and sets up a D-Bus client connection for
2083 * exchanging D-Bus messages with an endpoint specified by @address
2084 * which must be in the D-Bus address format.
2086 * This constructor can only be used to initiate client-side
2087 * connections - use g_dbus_connection_new_sync() if you need to act
2088 * as the server. In particular, @flags cannot contain the
2089 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2090 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2092 * This is a synchronous failable constructor. See
2093 * g_dbus_connection_new_for_address() for the asynchronous version.
2095 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2100 g_dbus_connection_new_for_address_sync (const gchar *address,
2101 GDBusConnectionFlags flags,
2102 GCancellable *cancellable,
2105 g_return_val_if_fail (address != NULL, NULL);
2106 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2107 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2115 /* ---------------------------------------------------------------------------------------------------- */
2118 * g_dbus_connection_set_exit_on_close:
2119 * @connection: A #GDBusConnection.
2120 * @exit_on_close: Whether the process should be terminated
2121 * when @connection is closed by the remote peer.
2123 * Sets whether the process should be terminated when @connection is
2124 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2130 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2131 gboolean exit_on_close)
2133 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2134 connection->priv->exit_on_close = exit_on_close;
2138 * g_dbus_connection_get_exit_on_close:
2139 * @connection: A #GDBusConnection.
2141 * Gets whether the process is terminated when @connection is
2142 * closed by the remote peer. See
2143 * #GDBusConnection:exit-on-close for more details.
2145 * Returns: Whether the process is terminated when @connection is
2146 * closed by the remote peer.
2151 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2153 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2154 return connection->priv->exit_on_close;
2158 * g_dbus_connection_get_guid:
2159 * @connection: A #GDBusConnection.
2161 * The GUID of the peer performing the role of server when
2162 * authenticating. See #GDBusConnection:guid for more details.
2164 * Returns: The GUID. Do not free this string, it is owned by
2170 g_dbus_connection_get_guid (GDBusConnection *connection)
2172 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2173 return connection->priv->guid;
2177 * g_dbus_connection_get_unique_name:
2178 * @connection: A #GDBusConnection.
2180 * Gets the unique name of @connection as assigned by the message
2181 * bus. This can also be used to figure out if @connection is a
2182 * message bus connection.
2184 * Returns: The unique name or %NULL if @connection is not a message
2185 * bus connection. Do not free this string, it is owned by
2191 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2193 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2194 return connection->priv->bus_unique_name;
2198 * g_dbus_connection_get_peer_credentials:
2199 * @connection: A #GDBusConnection.
2201 * Gets the credentials of the authenticated peer. This will always
2202 * return %NULL unless @connection acted as a server
2203 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2204 * when set up and the client passed credentials as part of the
2205 * authentication process.
2207 * In a message bus setup, the message bus is always the server and
2208 * each application is a client. So this method will always return
2209 * %NULL for message bus clients.
2211 * Returns: A #GCredentials or %NULL if not available. Do not free
2212 * this object, it is owned by @connection.
2217 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2219 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2220 return connection->priv->crendentials;
2223 /* ---------------------------------------------------------------------------------------------------- */
2225 static guint _global_filter_id = 1;
2228 * g_dbus_connection_add_filter:
2229 * @connection: A #GDBusConnection.
2230 * @filter_function: A filter function.
2231 * @user_data: User data to pass to @filter_function.
2232 * @user_data_free_func: Function to free @user_data with when filter
2233 * is removed or %NULL.
2235 * Adds a message filter. Filters are handlers that are run on all
2236 * incoming messages, prior to standard dispatch. Filters are run in
2237 * the order that they were added. The same handler can be added as a
2238 * filter more than once, in which case it will be run more than once.
2239 * Filters added during a filter callback won't be run on the message
2242 * Note that filters are run in a dedicated message handling thread so
2243 * they can't block and, generally, can't do anything but signal a
2244 * worker thread. Also note that filters are rarely needed - use API
2245 * such as g_dbus_connection_send_message_with_reply(),
2246 * g_dbus_connection_signal_subscribe() or
2247 * g_dbus_connection_invoke_method() instead.
2249 * Returns: A filter identifier that can be used with
2250 * g_dbus_connection_remove_filter().
2255 g_dbus_connection_add_filter (GDBusConnection *connection,
2256 GDBusMessageFilterFunction filter_function,
2258 GDestroyNotify user_data_free_func)
2262 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2263 g_return_val_if_fail (filter_function != NULL, 0);
2265 CONNECTION_LOCK (connection);
2266 data = g_new0 (FilterData, 1);
2267 data->id = _global_filter_id++; /* TODO: overflow etc. */
2268 data->filter_function = filter_function;
2269 data->user_data = user_data;
2270 data->user_data_free_func = user_data_free_func;
2271 g_ptr_array_add (connection->priv->filters, data);
2272 CONNECTION_UNLOCK (connection);
2277 /* only called from finalize(), removes all filters */
2279 purge_all_filters (GDBusConnection *connection)
2282 for (n = 0; n < connection->priv->filters->len; n++)
2284 FilterData *data = connection->priv->filters->pdata[n];
2285 if (data->user_data_free_func != NULL)
2286 data->user_data_free_func (data->user_data);
2292 g_dbus_connection_remove_filter (GDBusConnection *connection,
2296 FilterData *to_destroy;
2298 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2300 CONNECTION_LOCK (connection);
2302 for (n = 0; n < connection->priv->filters->len; n++)
2304 FilterData *data = connection->priv->filters->pdata[n];
2305 if (data->id == filter_id)
2307 g_ptr_array_remove_index (connection->priv->filters, n);
2312 CONNECTION_UNLOCK (connection);
2314 /* do free without holding lock */
2315 if (to_destroy != NULL)
2317 if (to_destroy->user_data_free_func != NULL)
2318 to_destroy->user_data_free_func (to_destroy->user_data);
2319 g_free (to_destroy);
2323 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2327 /* ---------------------------------------------------------------------------------------------------- */
2333 gchar *interface_name;
2337 GArray *subscribers;
2342 GDBusSignalCallback callback;
2344 GDestroyNotify user_data_free_func;
2346 GMainContext *context;
2350 signal_data_free (SignalData *data)
2352 g_free (data->rule);
2353 g_free (data->sender);
2354 g_free (data->interface_name);
2355 g_free (data->member);
2356 g_free (data->object_path);
2357 g_free (data->arg0);
2358 g_array_free (data->subscribers, TRUE);
2363 args_to_rule (const gchar *sender,
2364 const gchar *interface_name,
2365 const gchar *member,
2366 const gchar *object_path,
2371 rule = g_string_new ("type='signal'");
2373 g_string_append_printf (rule, ",sender='%s'", sender);
2374 if (interface_name != NULL)
2375 g_string_append_printf (rule, ",interface='%s'", interface_name);
2377 g_string_append_printf (rule, ",member='%s'", member);
2378 if (object_path != NULL)
2379 g_string_append_printf (rule, ",path='%s'", object_path);
2381 g_string_append_printf (rule, ",arg0='%s'", arg0);
2383 return g_string_free (rule, FALSE);
2386 static guint _global_subscriber_id = 1;
2387 static guint _global_registration_id = 1;
2388 static guint _global_subtree_registration_id = 1;
2390 /* ---------------------------------------------------------------------------------------------------- */
2392 /* must hold lock when calling */
2394 add_match_rule (GDBusConnection *connection,
2395 const gchar *match_rule)
2398 GDBusMessage *message;
2400 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2401 "/org/freedesktop/DBus", /* path */
2402 "org.freedesktop.DBus", /* interface */
2404 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2407 if (!g_dbus_connection_send_message_unlocked (connection,
2412 g_critical ("Error while sending AddMatch() message: %s", error->message);
2413 g_error_free (error);
2415 g_object_unref (message);
2418 /* ---------------------------------------------------------------------------------------------------- */
2420 /* must hold lock when calling */
2422 remove_match_rule (GDBusConnection *connection,
2423 const gchar *match_rule)
2426 GDBusMessage *message;
2428 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2429 "/org/freedesktop/DBus", /* path */
2430 "org.freedesktop.DBus", /* interface */
2432 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2435 if (!g_dbus_connection_send_message_unlocked (connection,
2440 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2441 g_error_free (error);
2443 g_object_unref (message);
2446 /* ---------------------------------------------------------------------------------------------------- */
2449 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2451 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2452 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2453 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2454 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2455 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2458 /* ---------------------------------------------------------------------------------------------------- */
2461 * g_dbus_connection_signal_subscribe:
2462 * @connection: A #GDBusConnection.
2463 * @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.
2464 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2465 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2466 * @object_path: Object path to match on or %NULL to match on all object paths.
2467 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2468 * @callback: Callback to invoke when there is a signal matching the requested data.
2469 * @user_data: User data to pass to @callback.
2470 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2472 * Subscribes to signals on @connection and invokes @callback with a
2473 * whenever the signal is received. Note that @callback
2474 * will be invoked in the <link
2475 * linkend="g-main-context-push-thread-default">thread-default main
2476 * loop</link> of the thread you are calling this method from.
2478 * It is considered a programming error to use this function if @connection is closed.
2480 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2481 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2482 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2483 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2484 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2485 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2487 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2492 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2493 const gchar *sender,
2494 const gchar *interface_name,
2495 const gchar *member,
2496 const gchar *object_path,
2498 GDBusSignalCallback callback,
2500 GDestroyNotify user_data_free_func)
2503 SignalData *signal_data;
2504 SignalSubscriber subscriber;
2505 GPtrArray *signal_data_array;
2507 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2508 * an OOM condition. We might want to change that but that would involve making
2509 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2510 * handle that. And there's really no sensible way of handling this short of retrying
2511 * to add the match rule... and then there's the little thing that, hey, maybe there's
2512 * a reason the bus in an OOM condition.
2514 * Doable, but not really sure it's worth it...
2517 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2518 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2519 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2520 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2521 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2522 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2523 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2524 g_return_val_if_fail (callback != NULL, 0);
2526 CONNECTION_LOCK (connection);
2528 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2533 subscriber.callback = callback;
2534 subscriber.user_data = user_data;
2535 subscriber.user_data_free_func = user_data_free_func;
2536 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2537 subscriber.context = g_main_context_get_thread_default ();
2538 if (subscriber.context != NULL)
2539 g_main_context_ref (subscriber.context);
2541 /* see if we've already have this rule */
2542 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2543 if (signal_data != NULL)
2545 g_array_append_val (signal_data->subscribers, subscriber);
2550 signal_data = g_new0 (SignalData, 1);
2551 signal_data->rule = rule;
2552 signal_data->sender = g_strdup (sender);
2553 signal_data->interface_name = g_strdup (interface_name);
2554 signal_data->member = g_strdup (member);
2555 signal_data->object_path = g_strdup (object_path);
2556 signal_data->arg0 = g_strdup (arg0);
2557 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2558 g_array_append_val (signal_data->subscribers, subscriber);
2560 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2564 /* Add the match rule to the bus...
2566 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2567 * always send such messages to to us.
2569 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2571 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2573 add_match_rule (connection, signal_data->rule);
2578 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2579 GUINT_TO_POINTER (subscriber.id),
2582 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2583 signal_data->sender);
2584 if (signal_data_array == NULL)
2586 signal_data_array = g_ptr_array_new ();
2587 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2588 g_strdup (signal_data->sender),
2591 g_ptr_array_add (signal_data_array, signal_data);
2593 CONNECTION_UNLOCK (connection);
2595 return subscriber.id;
2598 /* ---------------------------------------------------------------------------------------------------- */
2600 /* must hold lock when calling this */
2602 unsubscribe_id_internal (GDBusConnection *connection,
2603 guint subscription_id,
2604 GArray *out_removed_subscribers)
2606 SignalData *signal_data;
2607 GPtrArray *signal_data_array;
2610 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2611 GUINT_TO_POINTER (subscription_id));
2612 if (signal_data == NULL)
2614 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2618 for (n = 0; n < signal_data->subscribers->len; n++)
2620 SignalSubscriber *subscriber;
2622 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2623 if (subscriber->id != subscription_id)
2626 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2627 GUINT_TO_POINTER (subscription_id)));
2628 g_array_append_val (out_removed_subscribers, *subscriber);
2629 g_array_remove_index (signal_data->subscribers, n);
2631 if (signal_data->subscribers->len == 0)
2632 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2634 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2635 signal_data->sender);
2636 g_warn_if_fail (signal_data_array != NULL);
2637 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2639 if (signal_data_array->len == 0)
2641 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2643 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2644 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2646 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2648 remove_match_rule (connection, signal_data->rule);
2652 signal_data_free (signal_data);
2658 g_assert_not_reached ();
2665 * g_dbus_connection_signal_unsubscribe:
2666 * @connection: A #GDBusConnection.
2667 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2669 * Unsubscribes from signals.
2674 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2675 guint subscription_id)
2677 GArray *subscribers;
2680 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2682 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2684 CONNECTION_LOCK (connection);
2685 unsubscribe_id_internal (connection,
2688 CONNECTION_UNLOCK (connection);
2691 g_assert (subscribers->len == 0 || subscribers->len == 1);
2693 /* call GDestroyNotify without lock held */
2694 for (n = 0; n < subscribers->len; n++)
2696 SignalSubscriber *subscriber;
2697 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2698 if (subscriber->user_data_free_func != NULL)
2699 subscriber->user_data_free_func (subscriber->user_data);
2700 if (subscriber->context != NULL)
2701 g_main_context_unref (subscriber->context);
2704 g_array_free (subscribers, TRUE);
2707 /* ---------------------------------------------------------------------------------------------------- */
2711 guint subscription_id;
2712 GDBusSignalCallback callback;
2714 GDBusMessage *message;
2715 GDBusConnection *connection;
2716 const gchar *sender;
2718 const gchar *interface;
2719 const gchar *member;
2722 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2726 emit_signal_instance_in_idle_cb (gpointer data)
2728 SignalInstance *signal_instance = data;
2729 GVariant *parameters;
2730 gboolean has_subscription;
2732 parameters = g_dbus_message_get_body (signal_instance->message);
2733 if (parameters == NULL)
2735 parameters = g_variant_new ("()");
2736 g_variant_ref_sink (parameters);
2740 g_variant_ref_sink (parameters);
2744 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2745 signal_instance->sender,
2746 signal_instance->path,
2747 signal_instance->interface,
2748 signal_instance->member,
2749 g_variant_print (parameters, TRUE));
2752 /* Careful here, don't do the callback if we no longer has the subscription */
2753 CONNECTION_LOCK (signal_instance->connection);
2754 has_subscription = FALSE;
2755 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2756 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2757 has_subscription = TRUE;
2758 CONNECTION_UNLOCK (signal_instance->connection);
2760 if (has_subscription)
2762 signal_instance->callback (signal_instance->connection,
2763 signal_instance->sender,
2764 signal_instance->path,
2765 signal_instance->interface,
2766 signal_instance->member,
2768 signal_instance->user_data);
2770 if (parameters != NULL)
2771 g_variant_unref (parameters);
2777 signal_instance_free (SignalInstance *signal_instance)
2779 g_object_unref (signal_instance->message);
2780 g_object_unref (signal_instance->connection);
2781 g_free (signal_instance);
2784 /* called in message handler thread WITH lock held */
2786 schedule_callbacks (GDBusConnection *connection,
2787 GPtrArray *signal_data_array,
2788 GDBusMessage *message,
2789 const gchar *sender)
2792 const gchar *interface;
2793 const gchar *member;
2802 interface = g_dbus_message_get_interface (message);
2803 member = g_dbus_message_get_member (message);
2804 path = g_dbus_message_get_path (message);
2805 arg0 = g_dbus_message_get_arg0 (message);
2808 g_debug ("sender = `%s'", sender);
2809 g_debug ("interface = `%s'", interface);
2810 g_debug ("member = `%s'", member);
2811 g_debug ("path = `%s'", path);
2812 g_debug ("arg0 = `%s'", arg0);
2815 /* TODO: if this is slow, then we can change signal_data_array into
2816 * map_object_path_to_signal_data_array or something.
2818 for (n = 0; n < signal_data_array->len; n++)
2820 SignalData *signal_data = signal_data_array->pdata[n];
2822 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2825 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2828 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2831 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2834 for (m = 0; m < signal_data->subscribers->len; m++)
2836 SignalSubscriber *subscriber;
2837 GSource *idle_source;
2838 SignalInstance *signal_instance;
2840 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2842 signal_instance = g_new0 (SignalInstance, 1);
2843 signal_instance->subscription_id = subscriber->id;
2844 signal_instance->callback = subscriber->callback;
2845 signal_instance->user_data = subscriber->user_data;
2846 signal_instance->message = g_object_ref (message);
2847 signal_instance->connection = g_object_ref (connection);
2848 signal_instance->sender = sender;
2849 signal_instance->path = path;
2850 signal_instance->interface = interface;
2851 signal_instance->member = member;
2853 idle_source = g_idle_source_new ();
2854 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2855 g_source_set_callback (idle_source,
2856 emit_signal_instance_in_idle_cb,
2858 (GDestroyNotify) signal_instance_free);
2859 g_source_attach (idle_source, subscriber->context);
2860 g_source_unref (idle_source);
2865 /* called in message handler thread with lock held */
2867 distribute_signals (GDBusConnection *connection,
2868 GDBusMessage *message)
2870 GPtrArray *signal_data_array;
2871 const gchar *sender;
2873 sender = g_dbus_message_get_sender (message);
2875 /* collect subcsribers that match on sender */
2878 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2879 if (signal_data_array != NULL) {
2880 schedule_callbacks (connection, signal_data_array, message, sender);
2884 /* collect subcsribers not matching on sender */
2885 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2886 if (signal_data_array != NULL)
2888 schedule_callbacks (connection, signal_data_array, message, sender);
2892 /* ---------------------------------------------------------------------------------------------------- */
2894 /* only called from finalize(), removes all subscriptions */
2896 purge_all_signal_subscriptions (GDBusConnection *connection)
2898 GHashTableIter iter;
2901 GArray *subscribers;
2904 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2905 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2906 while (g_hash_table_iter_next (&iter, &key, NULL))
2908 guint subscription_id = GPOINTER_TO_UINT (key);
2909 g_array_append_val (ids, subscription_id);
2912 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2913 for (n = 0; n < ids->len; n++)
2915 guint subscription_id = g_array_index (ids, guint, n);
2916 unsubscribe_id_internal (connection,
2920 g_array_free (ids, TRUE);
2922 /* call GDestroyNotify without lock held */
2923 for (n = 0; n < subscribers->len; n++)
2925 SignalSubscriber *subscriber;
2926 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2927 if (subscriber->user_data_free_func != NULL)
2928 subscriber->user_data_free_func (subscriber->user_data);
2929 if (subscriber->context != NULL)
2930 g_main_context_unref (subscriber->context);
2933 g_array_free (subscribers, TRUE);
2936 /* ---------------------------------------------------------------------------------------------------- */
2938 struct ExportedObject
2941 GDBusConnection *connection;
2943 /* maps gchar* -> ExportedInterface* */
2944 GHashTable *map_if_name_to_ei;
2947 /* only called with lock held */
2949 exported_object_free (ExportedObject *eo)
2951 g_free (eo->object_path);
2952 g_hash_table_unref (eo->map_if_name_to_ei);
2961 gchar *interface_name;
2962 const GDBusInterfaceVTable *vtable;
2963 const GDBusInterfaceInfo *introspection_data;
2965 GMainContext *context;
2967 GDestroyNotify user_data_free_func;
2968 } ExportedInterface;
2970 /* called with lock held */
2972 exported_interface_free (ExportedInterface *ei)
2974 if (ei->user_data_free_func != NULL)
2976 /* TODO: push to thread-default mainloop */
2977 ei->user_data_free_func (ei->user_data);
2979 if (ei->context != NULL)
2981 g_main_context_unref (ei->context);
2983 g_free (ei->interface_name);
2987 /* ---------------------------------------------------------------------------------------------------- */
2991 GDBusConnection *connection;
2992 GDBusMessage *message;
2994 const char *property_name;
2995 const GDBusInterfaceVTable *vtable;
2996 const GDBusInterfaceInfo *interface_info;
2997 const GDBusPropertyInfo *property_info;
3001 property_data_free (PropertyData *data)
3003 g_object_unref (data->connection);
3004 g_object_unref (data->message);
3008 /* called in thread where object was registered - no locks held */
3010 invoke_get_property_in_idle_cb (gpointer _data)
3012 PropertyData *data = _data;
3015 GDBusMessage *reply;
3018 value = data->vtable->get_property (data->connection,
3019 g_dbus_message_get_sender (data->message),
3020 g_dbus_message_get_path (data->message),
3021 data->interface_info->name,
3022 data->property_name,
3029 g_assert_no_error (error);
3031 g_variant_ref_sink (value);
3032 reply = g_dbus_message_new_method_reply (data->message);
3033 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3034 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3035 g_variant_unref (value);
3036 g_object_unref (reply);
3040 gchar *dbus_error_name;
3042 g_assert (error != NULL);
3044 dbus_error_name = g_dbus_error_encode_gerror (error);
3045 reply = g_dbus_message_new_method_error_literal (data->message,
3048 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3049 g_free (dbus_error_name);
3050 g_error_free (error);
3051 g_object_unref (reply);
3057 /* called in thread where object was registered - no locks held */
3059 invoke_set_property_in_idle_cb (gpointer _data)
3061 PropertyData *data = _data;
3063 GDBusMessage *reply;
3069 g_variant_get (g_dbus_message_get_body (data->message),
3075 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3076 * of the given value is wrong
3078 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3080 reply = g_dbus_message_new_method_error (data->message,
3081 "org.freedesktop.DBus.Error.InvalidArgs",
3082 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3083 data->property_info->name,
3084 data->property_info->signature,
3085 g_variant_get_type_string (value));
3089 if (!data->vtable->set_property (data->connection,
3090 g_dbus_message_get_sender (data->message),
3091 g_dbus_message_get_path (data->message),
3092 data->interface_info->name,
3093 data->property_name,
3098 gchar *dbus_error_name;
3099 g_assert (error != NULL);
3100 dbus_error_name = g_dbus_error_encode_gerror (error);
3101 reply = g_dbus_message_new_method_error_literal (data->message,
3104 g_free (dbus_error_name);
3105 g_error_free (error);
3109 reply = g_dbus_message_new_method_reply (data->message);
3113 g_assert (reply != NULL);
3114 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3115 g_object_unref (reply);
3120 /* called with lock held */
3122 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3123 GDBusMessage *message,
3125 const GDBusInterfaceInfo *introspection_data,
3126 const GDBusInterfaceVTable *vtable,
3127 GMainContext *main_context,
3131 const char *interface_name;
3132 const char *property_name;
3133 const GDBusPropertyInfo *property_info;
3134 GSource *idle_source;
3135 PropertyData *property_data;
3136 GDBusMessage *reply;
3141 g_variant_get (g_dbus_message_get_body (message),
3146 g_variant_get (g_dbus_message_get_body (message),
3155 if (vtable == NULL || vtable->get_property == NULL)
3160 if (vtable == NULL || vtable->set_property == NULL)
3164 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3166 property_info = NULL;
3168 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3169 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3170 if (property_info == NULL)
3172 reply = g_dbus_message_new_method_error (message,
3173 "org.freedesktop.DBus.Error.InvalidArgs",
3174 _("No such property `%s'"),
3176 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3177 g_object_unref (reply);
3182 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3184 reply = g_dbus_message_new_method_error (message,
3185 "org.freedesktop.DBus.Error.InvalidArgs",
3186 _("Property `%s' is not readable"),
3188 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3189 g_object_unref (reply);
3193 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3195 reply = g_dbus_message_new_method_error (message,
3196 "org.freedesktop.DBus.Error.InvalidArgs",
3197 _("Property `%s' is not writable"),
3199 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3200 g_object_unref (reply);
3205 /* ok, got the property info - call user code in an idle handler */
3206 property_data = g_new0 (PropertyData, 1);
3207 property_data->connection = g_object_ref (connection);
3208 property_data->message = g_object_ref (message);
3209 property_data->user_data = user_data;
3210 property_data->property_name = property_name;
3211 property_data->vtable = vtable;
3212 property_data->interface_info = introspection_data;
3213 property_data->property_info = property_info;
3215 idle_source = g_idle_source_new ();
3216 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3217 g_source_set_callback (idle_source,
3218 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3220 (GDestroyNotify) property_data_free);
3221 g_source_attach (idle_source, main_context);
3222 g_source_unref (idle_source);
3230 /* called with lock held */
3232 handle_getset_property (GDBusConnection *connection,
3234 GDBusMessage *message,
3237 ExportedInterface *ei;
3239 const char *interface_name;
3240 const char *property_name;
3245 g_variant_get (g_dbus_message_get_body (message),
3250 g_variant_get (g_dbus_message_get_body (message),
3256 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3257 * no such interface registered
3259 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3262 GDBusMessage *reply;
3263 reply = g_dbus_message_new_method_error (message,
3264 "org.freedesktop.DBus.Error.InvalidArgs",
3265 _("No such interface `%s'"),
3267 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3268 g_object_unref (reply);
3273 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3276 ei->introspection_data,
3284 /* ---------------------------------------------------------------------------------------------------- */
3288 GDBusConnection *connection;
3289 GDBusMessage *message;
3291 const GDBusInterfaceVTable *vtable;
3292 const GDBusInterfaceInfo *interface_info;
3293 } PropertyGetAllData;
3296 property_get_all_data_free (PropertyData *data)
3298 g_object_unref (data->connection);
3299 g_object_unref (data->message);
3303 /* called in thread where object was registered - no locks held */
3305 invoke_get_all_properties_in_idle_cb (gpointer _data)
3307 PropertyGetAllData *data = _data;
3308 GVariantBuilder *builder;
3312 GDBusMessage *reply;
3317 /* TODO: Right now we never fail this call - we just omit values if
3318 * a get_property() call is failing.
3320 * We could fail the whole call if just a single get_property() call
3321 * returns an error. We need clarification in the D-Bus spec about this.
3323 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3324 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3326 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3329 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3332 value = data->vtable->get_property (data->connection,
3333 g_dbus_message_get_sender (data->message),
3334 g_dbus_message_get_path (data->message),
3335 data->interface_info->name,
3336 property_info->name,
3343 g_variant_ref_sink (value);
3344 g_variant_builder_add (builder,
3346 property_info->name,
3348 g_variant_unref (value);
3350 result = g_variant_builder_end (builder);
3352 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3353 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3354 packed = g_variant_builder_end (builder);
3356 reply = g_dbus_message_new_method_reply (data->message);
3357 g_dbus_message_set_body (reply, packed);
3358 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3359 g_object_unref (reply);
3364 /* called with lock held */
3366 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3367 GDBusMessage *message,
3368 const GDBusInterfaceInfo *introspection_data,
3369 const GDBusInterfaceVTable *vtable,
3370 GMainContext *main_context,
3374 const char *interface_name;
3375 GSource *idle_source;
3376 PropertyGetAllData *property_get_all_data;
3380 g_variant_get (g_dbus_message_get_body (message),
3384 if (vtable == NULL || vtable->get_property == NULL)
3387 /* ok, got the property info - call user in an idle handler */
3388 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3389 property_get_all_data->connection = g_object_ref (connection);
3390 property_get_all_data->message = g_object_ref (message);
3391 property_get_all_data->user_data = user_data;
3392 property_get_all_data->vtable = vtable;
3393 property_get_all_data->interface_info = introspection_data;
3395 idle_source = g_idle_source_new ();
3396 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3397 g_source_set_callback (idle_source,
3398 invoke_get_all_properties_in_idle_cb,
3399 property_get_all_data,
3400 (GDestroyNotify) property_get_all_data_free);
3401 g_source_attach (idle_source, main_context);
3402 g_source_unref (idle_source);
3410 /* called with lock held */
3412 handle_get_all_properties (GDBusConnection *connection,
3414 GDBusMessage *message)
3416 ExportedInterface *ei;
3418 const char *interface_name;
3422 g_variant_get (g_dbus_message_get_body (message),
3426 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3427 * no such interface registered
3429 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3432 GDBusMessage *reply;
3433 reply = g_dbus_message_new_method_error (message,
3434 "org.freedesktop.DBus.Error.InvalidArgs",
3435 _("No such interface"),
3437 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3438 g_object_unref (reply);
3443 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3445 ei->introspection_data,
3453 /* ---------------------------------------------------------------------------------------------------- */
3456 introspect_append_header (GString *s)
3459 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n\"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3460 "<!-- GDBus 0.1 -->\n"
3465 introspect_append_standard_interfaces (GString *s)
3468 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3469 " <method name=\"Get\">\n"
3470 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3471 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3472 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3474 " <method name=\"GetAll\">\n"
3475 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3476 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3478 " <method name=\"Set\">\n"
3479 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3480 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3481 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3483 " <signal name=\"PropertiesChanged\">\n"
3484 " <arg type=\"s\" name=\"interface_name\"/>\n"
3485 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3488 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3489 " <method name=\"Introspect\">\n"
3490 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3493 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3494 " <method name=\"Ping\"/>\n"
3495 " <method name=\"GetMachineId\">\n"
3496 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3502 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3504 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3510 begin = object_path + path_len;
3511 end = strchr (begin, '/');
3515 s = g_strndup (begin, end - begin);
3519 s = g_strdup (begin);
3522 if (g_hash_table_lookup (set, s) == NULL)
3524 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3533 /* TODO: we want a nicer public interface for this */
3535 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3540 GHashTableIter hash_iter;
3541 const gchar *object_path;
3547 CONNECTION_ENSURE_LOCK (connection);
3549 path_len = strlen (path);
3553 set = g_hash_table_new (g_str_hash, g_str_equal);
3555 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3556 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3557 maybe_add_path (path, path_len, object_path, set);
3559 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3560 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3561 maybe_add_path (path, path_len, object_path, set);
3563 p = g_ptr_array_new ();
3564 keys = g_hash_table_get_keys (set);
3565 for (l = keys; l != NULL; l = l->next)
3567 g_ptr_array_add (p, l->data);
3569 g_hash_table_unref (set);
3572 g_ptr_array_add (p, NULL);
3573 ret = (gchar **) g_ptr_array_free (p, FALSE);
3578 g_dbus_connection_list_registered (GDBusConnection *connection,
3582 CONNECTION_LOCK (connection);
3583 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3584 CONNECTION_UNLOCK (connection);
3588 /* called in message handler thread with lock held */
3590 handle_introspect (GDBusConnection *connection,
3592 GDBusMessage *message)
3596 GDBusMessage *reply;
3597 GHashTableIter hash_iter;
3598 ExportedInterface *ei;
3601 /* first the header with the standard interfaces */
3602 s = g_string_new (NULL);
3603 introspect_append_header (s);
3604 introspect_append_standard_interfaces (s);
3606 /* then include the registered interfaces */
3607 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3608 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3610 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3613 /* finally include nodes registered below us */
3614 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3615 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3617 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3619 g_strfreev (registered);
3620 g_string_append (s, "</node>\n");
3622 reply = g_dbus_message_new_method_reply (message);
3623 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3624 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3625 g_object_unref (reply);
3626 g_string_free (s, TRUE);
3631 /* called in thread where object was registered - no locks held */
3633 invoke_method_in_idle_cb (gpointer user_data)
3635 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3636 GDBusInterfaceVTable *vtable;
3638 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3639 g_assert (vtable != NULL && vtable->method_call != NULL);
3641 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3642 g_dbus_method_invocation_get_sender (invocation),
3643 g_dbus_method_invocation_get_object_path (invocation),
3644 g_dbus_method_invocation_get_interface_name (invocation),
3645 g_dbus_method_invocation_get_method_name (invocation),
3646 g_dbus_method_invocation_get_parameters (invocation),
3647 g_object_ref (invocation),
3648 g_dbus_method_invocation_get_user_data (invocation));
3653 /* called in message handler thread with lock held */
3655 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3656 GDBusMessage *message,
3657 const GDBusInterfaceInfo *introspection_data,
3658 const GDBusInterfaceVTable *vtable,
3659 GMainContext *main_context,
3662 GDBusMethodInvocation *invocation;
3663 const GDBusMethodInfo *method_info;
3664 GDBusMessage *reply;
3665 GVariant *parameters;
3666 GSource *idle_source;
3668 gchar *in_signature;
3672 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3673 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3675 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3676 * error to the caller
3678 if (method_info == NULL)
3680 reply = g_dbus_message_new_method_error (message,
3681 "org.freedesktop.DBus.Error.UnknownMethod",
3682 _("No such method `%s'"),
3683 g_dbus_message_get_member (message));
3684 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3685 g_object_unref (reply);
3690 /* Check that the incoming args are of the right type - if they are not, return
3691 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3693 * TODO: might also be worth caching the combined signature.
3695 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3696 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3698 reply = g_dbus_message_new_method_error (message,
3699 "org.freedesktop.DBus.Error.InvalidArgs",
3700 _("Signature of message, `%s', does not match expected signature `%s'"),
3701 g_dbus_message_get_signature (message),
3703 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3704 g_object_unref (reply);
3705 g_free (in_signature);
3709 g_free (in_signature);
3711 parameters = g_dbus_message_get_body (message);
3712 if (parameters == NULL)
3714 parameters = g_variant_new ("()");
3715 g_variant_ref_sink (parameters);
3719 g_variant_ref (parameters);
3722 /* schedule the call in idle */
3723 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3724 g_dbus_message_get_path (message),
3725 g_dbus_message_get_interface (message),
3726 g_dbus_message_get_member (message),
3732 g_variant_unref (parameters);
3733 g_object_set_data (G_OBJECT (invocation),
3734 "g-dbus-interface-vtable",
3737 idle_source = g_idle_source_new ();
3738 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3739 g_source_set_callback (idle_source,
3740 invoke_method_in_idle_cb,
3743 g_source_attach (idle_source, main_context);
3744 g_source_unref (idle_source);
3753 /* ---------------------------------------------------------------------------------------------------- */
3755 /* called in message handler thread with lock held */
3757 obj_message_func (GDBusConnection *connection,
3759 GDBusMessage *message)
3761 const gchar *interface_name;
3762 const gchar *member;
3763 const gchar *signature;
3768 interface_name = g_dbus_message_get_interface (message);
3769 member = g_dbus_message_get_member (message);
3770 signature = g_dbus_message_get_signature (message);
3772 /* see if we have an interface for handling this call */
3773 if (interface_name != NULL)
3775 ExportedInterface *ei;
3776 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3779 /* we do - invoke the handler in idle in the right thread */
3781 /* handle no vtable or handler being present */
3782 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3785 handled = validate_and_maybe_schedule_method_call (connection,
3787 ei->introspection_data,
3795 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3796 g_strcmp0 (member, "Introspect") == 0 &&
3797 g_strcmp0 (signature, "") == 0)
3799 handled = handle_introspect (connection, eo, message);
3802 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3803 g_strcmp0 (member, "Get") == 0 &&
3804 g_strcmp0 (signature, "ss") == 0)
3806 handled = handle_getset_property (connection, eo, message, TRUE);
3809 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3810 g_strcmp0 (member, "Set") == 0 &&
3811 g_strcmp0 (signature, "ssv") == 0)
3813 handled = handle_getset_property (connection, eo, message, FALSE);
3816 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3817 g_strcmp0 (member, "GetAll") == 0 &&
3818 g_strcmp0 (signature, "s") == 0)
3820 handled = handle_get_all_properties (connection, eo, message);
3829 * g_dbus_connection_register_object:
3830 * @connection: A #GDBusConnection.
3831 * @object_path: The object path to register at.
3832 * @interface_name: The D-Bus interface to register.
3833 * @introspection_data: Introspection data for the interface.
3834 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3835 * @user_data: Data to pass to functions in @vtable.
3836 * @user_data_free_func: Function to call when the object path is unregistered.
3837 * @error: Return location for error or %NULL.
3839 * Registers callbacks for exported objects at @object_path with the
3840 * D-Bus interface @interface_name.
3842 * Calls to functions in @vtable (and @user_data_free_func) will
3843 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3844 * loop</link> of the thread you are calling this method from.
3846 * Note that all #GVariant values passed to functions in @vtable will match
3847 * the signature given in @introspection_data - if a remote caller passes
3848 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3849 * is returned to the remote caller.
3851 * Additionally, if the remote caller attempts to invoke methods or
3852 * access properties not mentioned in @introspection_data the
3853 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3854 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3855 * are returned to the caller.
3857 * It is considered a programming error if the
3858 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3859 * #GVariant of incorrect type.
3861 * If an existing callback is already registered at @object_path and
3862 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3864 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3866 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3867 * that can be used with g_dbus_connection_unregister_object() .
3872 g_dbus_connection_register_object (GDBusConnection *connection,
3873 const gchar *object_path,
3874 const gchar *interface_name,
3875 const GDBusInterfaceInfo *introspection_data,
3876 const GDBusInterfaceVTable *vtable,
3878 GDestroyNotify user_data_free_func,
3882 ExportedInterface *ei;
3885 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3886 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3887 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3888 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3889 g_return_val_if_fail (introspection_data != NULL, 0);
3890 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3894 CONNECTION_LOCK (connection);
3896 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3899 eo = g_new0 (ExportedObject, 1);
3900 eo->object_path = g_strdup (object_path);
3901 eo->connection = connection;
3902 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3905 (GDestroyNotify) exported_interface_free);
3906 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3909 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3915 _("An object is already exported for the interface %s at %s"),
3921 ei = g_new0 (ExportedInterface, 1);
3922 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3924 ei->user_data = user_data;
3925 ei->user_data_free_func = user_data_free_func;
3926 ei->vtable = vtable;
3927 ei->introspection_data = introspection_data;
3928 ei->interface_name = g_strdup (interface_name);
3929 ei->context = g_main_context_get_thread_default ();
3930 if (ei->context != NULL)
3931 g_main_context_ref (ei->context);
3933 g_hash_table_insert (eo->map_if_name_to_ei,
3934 (gpointer) ei->interface_name,
3936 g_hash_table_insert (connection->priv->map_id_to_ei,
3937 GUINT_TO_POINTER (ei->id),
3943 CONNECTION_UNLOCK (connection);
3949 * g_dbus_connection_unregister_object:
3950 * @connection: A #GDBusConnection.
3951 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3953 * Unregisters an object.
3955 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3960 g_dbus_connection_unregister_object (GDBusConnection *connection,
3961 guint registration_id)
3963 ExportedInterface *ei;
3967 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3971 CONNECTION_LOCK (connection);
3973 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
3974 GUINT_TO_POINTER (registration_id));
3982 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
3983 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
3984 /* unregister object path if we have no more exported interfaces */
3985 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
3987 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
3994 CONNECTION_UNLOCK (connection);
3999 /* ---------------------------------------------------------------------------------------------------- */
4002 * g_dbus_connection_emit_signal:
4003 * @connection: A #GDBusConnection.
4004 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4005 * @object_path: Path of remote object.
4006 * @interface_name: D-Bus interface to emit a signal on.
4007 * @signal_name: The name of the signal to emit.
4008 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4009 * @error: Return location for error or %NULL.
4013 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4015 * Returns: %TRUE unless @error is set.
4020 g_dbus_connection_emit_signal (GDBusConnection *connection,
4021 const gchar *destination_bus_name,
4022 const gchar *object_path,
4023 const gchar *interface_name,
4024 const gchar *signal_name,
4025 GVariant *parameters,
4028 GDBusMessage *message;
4034 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4035 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4036 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4037 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4038 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4039 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4041 message = g_dbus_message_new_signal (object_path,
4045 if (destination_bus_name != NULL)
4047 g_dbus_message_set_header (message,
4048 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4049 g_variant_new_string (destination_bus_name));
4052 if (parameters != NULL)
4053 g_dbus_message_set_body (message, parameters);
4055 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4056 g_object_unref (message);
4062 add_invoke_method_flags (GDBusMessage *message,
4063 GDBusInvokeMethodFlags flags)
4065 if (flags & G_DBUS_INVOKE_METHOD_FLAGS_NO_AUTO_START)
4066 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4070 * g_dbus_connection_invoke_method:
4071 * @connection: A #GDBusConnection.
4072 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4073 * @object_path: Path of remote object.
4074 * @interface_name: D-Bus interface to invoke method on.
4075 * @method_name: The name of the method to invoke.
4076 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4077 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4078 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4079 * @cancellable: A #GCancellable or %NULL.
4080 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4081 * care about the result of the method invocation.
4082 * @user_data: The data to pass to @callback.
4084 * Asynchronously invokes the @method_name method on the
4085 * @interface_name D-Bus interface on the remote object at
4086 * @object_path owned by @bus_name.
4088 * If @connection is closed then the operation will fail with
4089 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4090 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4091 * not compatible with the D-Bus protocol, the operation fails with
4092 * %G_IO_ERROR_INVALID_ARGUMENT.
4094 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4095 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4096 * of the thread you are calling this method from. You can then call
4097 * g_dbus_connection_invoke_method_finish() to get the result of the operation.
4098 * See g_dbus_connection_invoke_method_sync() for the synchronous version of this
4104 g_dbus_connection_invoke_method (GDBusConnection *connection,
4105 const gchar *bus_name,
4106 const gchar *object_path,
4107 const gchar *interface_name,
4108 const gchar *method_name,
4109 GVariant *parameters,
4110 GDBusInvokeMethodFlags flags,
4112 GCancellable *cancellable,
4113 GAsyncReadyCallback callback,
4116 GDBusMessage *message;
4118 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4119 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4120 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4121 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4122 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4123 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4124 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4126 message = g_dbus_message_new_method_call (bus_name,
4130 add_invoke_method_flags (message, flags);
4131 if (parameters != NULL)
4132 g_dbus_message_set_body (message, parameters);
4134 g_dbus_connection_send_message_with_reply (connection,
4137 NULL, /* volatile guint32 *out_serial */
4142 if (message != NULL)
4143 g_object_unref (message);
4147 decode_method_reply (GDBusMessage *reply, GError **error)
4152 switch (g_dbus_message_get_type (reply))
4154 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4155 result = g_dbus_message_get_body (reply);
4158 result = g_variant_new ("()");
4159 g_variant_ref_sink (result);
4163 g_variant_ref (result);
4166 case G_DBUS_MESSAGE_TYPE_ERROR:
4167 g_dbus_message_to_gerror (reply, error);
4171 g_assert_not_reached ();
4179 * g_dbus_connection_invoke_method_finish:
4180 * @connection: A #GDBusConnection.
4181 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_invoke_method().
4182 * @error: Return location for error or %NULL.
4184 * Finishes an operation started with g_dbus_connection_invoke_method().
4186 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4187 * return values. Free with g_variant_unref().
4192 g_dbus_connection_invoke_method_finish (GDBusConnection *connection,
4196 GDBusMessage *reply;
4199 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4200 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4201 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4205 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4209 result = decode_method_reply (reply, error);
4211 g_object_unref (reply);
4217 /* ---------------------------------------------------------------------------------------------------- */
4220 * g_dbus_connection_invoke_method_sync:
4221 * @connection: A #GDBusConnection.
4222 * @bus_name: A unique or well-known bus name.
4223 * @object_path: Path of remote object.
4224 * @interface_name: D-Bus interface to invoke method on.
4225 * @method_name: The name of the method to invoke.
4226 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4227 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4228 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4229 * @cancellable: A #GCancellable or %NULL.
4230 * @error: Return location for error or %NULL.
4232 * Synchronously invokes the @method_name method on the
4233 * @interface_name D-Bus interface on the remote object at
4234 * @object_path owned by @bus_name.
4236 * If @connection is closed then the operation will fail with
4237 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4238 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4239 * contains a value not compatible with the D-Bus protocol, the operation
4240 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4242 * The calling thread is blocked until a reply is received. See
4243 * g_dbus_connection_invoke_method() for the asynchronous version of
4246 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4247 * return values. Free with g_variant_unref().
4252 g_dbus_connection_invoke_method_sync (GDBusConnection *connection,
4253 const gchar *bus_name,
4254 const gchar *object_path,
4255 const gchar *interface_name,
4256 const gchar *method_name,
4257 GVariant *parameters,
4258 GDBusInvokeMethodFlags flags,
4260 GCancellable *cancellable,
4263 GDBusMessage *message;
4264 GDBusMessage *reply;
4271 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4272 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4273 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4274 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4275 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4276 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4277 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4279 message = g_dbus_message_new_method_call (bus_name,
4283 add_invoke_method_flags (message, flags);
4284 if (parameters != NULL)
4285 g_dbus_message_set_body (message, parameters);
4287 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4290 NULL, /* volatile guint32 *out_serial */
4297 result = decode_method_reply (reply, error);
4300 if (message != NULL)
4301 g_object_unref (message);
4303 g_object_unref (reply);
4308 /* ---------------------------------------------------------------------------------------------------- */
4310 struct ExportedSubtree
4314 GDBusConnection *connection;
4315 const GDBusSubtreeVTable *vtable;
4316 GDBusSubtreeFlags flags;
4318 GMainContext *context;
4320 GDestroyNotify user_data_free_func;
4324 exported_subtree_free (ExportedSubtree *es)
4326 if (es->user_data_free_func != NULL)
4328 /* TODO: push to thread-default mainloop */
4329 es->user_data_free_func (es->user_data);
4331 if (es->context != NULL)
4333 g_main_context_unref (es->context);
4335 g_free (es->object_path);
4339 /* called without lock held */
4341 handle_subtree_introspect (GDBusConnection *connection,
4342 ExportedSubtree *es,
4343 GDBusMessage *message)
4347 GDBusMessage *reply;
4350 const gchar *sender;
4351 const gchar *requested_object_path;
4352 const gchar *requested_node;
4353 GPtrArray *interfaces;
4355 gchar **subnode_paths;
4359 requested_object_path = g_dbus_message_get_path (message);
4360 sender = g_dbus_message_get_sender (message);
4361 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4363 s = g_string_new (NULL);
4364 introspect_append_header (s);
4366 /* Strictly we don't need the children in dynamic mode, but we avoid the
4367 * conditionals to preserve code clarity
4369 children = es->vtable->enumerate (es->connection,
4376 requested_node = strrchr (requested_object_path, '/') + 1;
4378 /* Assert existence of object if we are not dynamic */
4379 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4380 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4385 requested_node = "/";
4388 interfaces = es->vtable->introspect (es->connection,
4393 if (interfaces != NULL)
4395 if (interfaces->len > 0)
4397 /* we're in business */
4398 introspect_append_standard_interfaces (s);
4400 for (n = 0; n < interfaces->len; n++)
4402 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4403 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4406 g_ptr_array_unref (interfaces);
4409 /* then include <node> entries from the Subtree for the root */
4412 for (n = 0; children != NULL && children[n] != NULL; n++)
4414 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4418 /* finally include nodes registered below us */
4419 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4420 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4422 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4424 g_strfreev (subnode_paths);
4426 g_string_append (s, "</node>\n");
4428 reply = g_dbus_message_new_method_reply (message);
4429 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4430 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4431 g_object_unref (reply);
4436 g_string_free (s, TRUE);
4437 g_strfreev (children);
4441 /* called without lock held */
4443 handle_subtree_method_invocation (GDBusConnection *connection,
4444 ExportedSubtree *es,
4445 GDBusMessage *message)
4448 const gchar *sender;
4449 const gchar *interface_name;
4450 const gchar *member;
4451 const gchar *signature;
4452 const gchar *requested_object_path;
4453 const gchar *requested_node;
4456 const GDBusInterfaceInfo *introspection_data;
4457 const GDBusInterfaceVTable *interface_vtable;
4458 gpointer interface_user_data;
4460 GPtrArray *interfaces;
4461 gboolean is_property_get;
4462 gboolean is_property_set;
4463 gboolean is_property_get_all;
4468 requested_object_path = g_dbus_message_get_path (message);
4469 sender = g_dbus_message_get_sender (message);
4470 interface_name = g_dbus_message_get_interface (message);
4471 member = g_dbus_message_get_member (message);
4472 signature = g_dbus_message_get_signature (message);
4473 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4475 is_property_get = FALSE;
4476 is_property_set = FALSE;
4477 is_property_get_all = FALSE;
4478 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4480 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4482 is_property_get = TRUE;
4484 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4486 is_property_set = TRUE;
4488 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4490 is_property_get_all = TRUE;
4494 children = es->vtable->enumerate (es->connection,
4501 requested_node = strrchr (requested_object_path, '/') + 1;
4503 /* If not dynamic, skip if requested node is not part of children */
4504 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4505 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4510 requested_node = "/";
4513 /* get introspection data for the node */
4514 interfaces = es->vtable->introspect (es->connection,
4516 requested_object_path,
4519 g_assert (interfaces != NULL);
4520 introspection_data = NULL;
4521 for (n = 0; n < interfaces->len; n++)
4523 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4524 if (g_strcmp0 (id_n->name, interface_name) == 0)
4526 introspection_data = id_n;
4530 /* dispatch the call if the user wants to handle it */
4531 if (introspection_data != NULL)
4533 /* figure out where to dispatch the method call */
4534 interface_user_data = NULL;
4535 interface_vtable = es->vtable->dispatch (es->connection,
4540 &interface_user_data,
4542 if (interface_vtable == NULL)
4545 CONNECTION_LOCK (connection);
4546 handled = validate_and_maybe_schedule_method_call (es->connection,
4551 interface_user_data);
4552 CONNECTION_UNLOCK (connection);
4554 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4555 else if (is_property_get || is_property_set || is_property_get_all)
4557 if (is_property_get)
4558 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4559 else if (is_property_set)
4560 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4561 else if (is_property_get_all)
4562 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4564 g_assert_not_reached ();
4566 /* see if the object supports this interface at all */
4567 for (n = 0; n < interfaces->len; n++)
4569 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4570 if (g_strcmp0 (id_n->name, interface_name) == 0)
4572 introspection_data = id_n;
4576 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4577 * claims it won't support the interface
4579 if (introspection_data == NULL)
4581 GDBusMessage *reply;
4582 reply = g_dbus_message_new_method_error (message,
4583 "org.freedesktop.DBus.Error.InvalidArgs",
4584 _("No such interface `%s'"),
4586 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4587 g_object_unref (reply);
4592 /* figure out where to dispatch the property get/set/getall calls */
4593 interface_user_data = NULL;
4594 interface_vtable = es->vtable->dispatch (es->connection,
4599 &interface_user_data,
4601 if (interface_vtable == NULL)
4604 if (is_property_get || is_property_set)
4606 CONNECTION_LOCK (connection);
4607 handled = validate_and_maybe_schedule_property_getset (es->connection,
4613 interface_user_data);
4614 CONNECTION_UNLOCK (connection);
4616 else if (is_property_get_all)
4618 CONNECTION_LOCK (connection);
4619 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4624 interface_user_data);
4625 CONNECTION_UNLOCK (connection);
4630 if (interfaces != NULL)
4631 g_ptr_array_unref (interfaces);
4632 g_strfreev (children);
4638 GDBusMessage *message;
4639 ExportedSubtree *es;
4640 } SubtreeDeferredData;
4643 subtree_deferred_data_free (SubtreeDeferredData *data)
4645 g_object_unref (data->message);
4649 /* called without lock held in the thread where the caller registered the subtree */
4651 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4653 SubtreeDeferredData *data = _data;
4658 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4659 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4660 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4662 handled = handle_subtree_introspect (data->es->connection,
4668 handled = handle_subtree_method_invocation (data->es->connection,
4676 CONNECTION_LOCK (data->es->connection);
4677 handled = handle_generic_unlocked (data->es->connection, data->message);
4678 CONNECTION_UNLOCK (data->es->connection);
4681 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4684 GDBusMessage *reply;
4685 reply = g_dbus_message_new_method_error (data->message,
4686 "org.freedesktop.DBus.Error.UnknownMethod",
4687 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4688 g_dbus_message_get_member (data->message),
4689 g_dbus_message_get_interface (data->message),
4690 g_dbus_message_get_signature (data->message));
4691 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4692 g_object_unref (reply);
4698 /* called in message handler thread with lock held */
4700 subtree_message_func (GDBusConnection *connection,
4701 ExportedSubtree *es,
4702 GDBusMessage *message)
4704 GSource *idle_source;
4705 SubtreeDeferredData *data;
4707 data = g_new0 (SubtreeDeferredData, 1);
4708 data->message = g_object_ref (message);
4711 /* defer this call to an idle handler in the right thread */
4712 idle_source = g_idle_source_new ();
4713 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4714 g_source_set_callback (idle_source,
4715 process_subtree_vtable_message_in_idle_cb,
4717 (GDestroyNotify) subtree_deferred_data_free);
4718 g_source_attach (idle_source, es->context);
4719 g_source_unref (idle_source);
4721 /* since we own the entire subtree, handlers for objects not in the subtree have been
4722 * tried already by libdbus-1 - so we just need to ensure that we're always going
4723 * to reply to the message
4729 * g_dbus_connection_register_subtree:
4730 * @connection: A #GDBusConnection.
4731 * @object_path: The object path to register the subtree at.
4732 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4733 * @flags: Flags used to fine tune the behavior of the subtree.
4734 * @user_data: Data to pass to functions in @vtable.
4735 * @user_data_free_func: Function to call when the subtree is unregistered.
4736 * @error: Return location for error or %NULL.
4738 * Registers a whole subtree of <quote>dynamic</quote> objects.
4740 * The @enumerate and @introspection functions in @vtable are used to
4741 * convey, to remote callers, what nodes exist in the subtree rooted
4744 * When handling remote calls into any node in the subtree, first the
4745 * @enumerate function is used to check if the node exists. If the node exists
4746 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4747 * the @introspection function is used to check if the node supports the
4748 * requested method. If so, the @dispatch function is used to determine
4749 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4750 * #gpointer will be used to call into the interface vtable for processing
4753 * All calls into user-provided code will be invoked in the <link
4754 * linkend="g-main-context-push-thread-default">thread-default main
4755 * loop</link> of the thread you are calling this method from.
4757 * If an existing subtree is already registered at @object_path or
4758 * then @error is set to #G_IO_ERROR_EXISTS.
4760 * Note that it is valid to register regular objects (using
4761 * g_dbus_connection_register_object()) in a subtree registered with
4762 * g_dbus_connection_register_subtree() - if so, the subtree handler
4763 * is tried as the last resort. One way to think about a subtree
4764 * handler is to consider it a <quote>fallback handler</quote>
4765 * for object paths not registered via g_dbus_connection_register_object()
4766 * or other bindings.
4768 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4770 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4771 * that can be used with g_dbus_connection_unregister_subtree() .
4776 g_dbus_connection_register_subtree (GDBusConnection *connection,
4777 const gchar *object_path,
4778 const GDBusSubtreeVTable *vtable,
4779 GDBusSubtreeFlags flags,
4781 GDestroyNotify user_data_free_func,
4785 ExportedSubtree *es;
4787 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4788 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4789 g_return_val_if_fail (vtable != NULL, 0);
4790 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4794 CONNECTION_LOCK (connection);
4796 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4802 _("A subtree is already exported for %s"),
4807 es = g_new0 (ExportedSubtree, 1);
4808 es->object_path = g_strdup (object_path);
4809 es->connection = connection;
4811 es->vtable = vtable;
4813 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4814 es->user_data = user_data;
4815 es->user_data_free_func = user_data_free_func;
4816 es->context = g_main_context_get_thread_default ();
4817 if (es->context != NULL)
4818 g_main_context_ref (es->context);
4820 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4821 g_hash_table_insert (connection->priv->map_id_to_es,
4822 GUINT_TO_POINTER (es->id),
4828 CONNECTION_UNLOCK (connection);
4833 /* ---------------------------------------------------------------------------------------------------- */
4836 * g_dbus_connection_unregister_subtree:
4837 * @connection: A #GDBusConnection.
4838 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4840 * Unregisters a subtree.
4842 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4847 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4848 guint registration_id)
4850 ExportedSubtree *es;
4853 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4857 CONNECTION_LOCK (connection);
4859 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4860 GUINT_TO_POINTER (registration_id));
4866 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4867 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4872 CONNECTION_UNLOCK (connection);
4877 /* ---------------------------------------------------------------------------------------------------- */
4879 /* must be called with lock held */
4881 handle_generic_ping_unlocked (GDBusConnection *connection,
4882 const gchar *object_path,
4883 GDBusMessage *message)
4885 GDBusMessage *reply;
4886 reply = g_dbus_message_new_method_reply (message);
4887 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4888 g_object_unref (reply);
4891 /* must be called with lock held */
4893 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4894 const gchar *object_path,
4895 GDBusMessage *message)
4897 GDBusMessage *reply;
4900 if (connection->priv->machine_id == NULL)
4904 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4905 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4906 &connection->priv->machine_id,
4910 reply = g_dbus_message_new_method_error (message,
4911 "org.freedesktop.DBus.Error.Failed",
4912 _("Unable to load /var/lib/dbus/machine-id: %s"),
4914 g_error_free (error);
4918 g_strstrip (connection->priv->machine_id);
4919 /* TODO: validate value */
4925 reply = g_dbus_message_new_method_reply (message);
4926 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4928 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4929 g_object_unref (reply);
4932 /* must be called with lock held */
4934 handle_generic_introspect_unlocked (GDBusConnection *connection,
4935 const gchar *object_path,
4936 GDBusMessage *message)
4941 GDBusMessage *reply;
4943 /* first the header */
4944 s = g_string_new (NULL);
4945 introspect_append_header (s);
4947 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4948 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4950 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4952 g_strfreev (registered);
4953 g_string_append (s, "</node>\n");
4955 reply = g_dbus_message_new_method_reply (message);
4956 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4957 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4958 g_object_unref (reply);
4959 g_string_free (s, TRUE);
4962 /* must be called with lock held */
4964 handle_generic_unlocked (GDBusConnection *connection,
4965 GDBusMessage *message)
4968 const gchar *interface_name;
4969 const gchar *member;
4970 const gchar *signature;
4973 CONNECTION_ENSURE_LOCK (connection);
4977 interface_name = g_dbus_message_get_interface (message);
4978 member = g_dbus_message_get_member (message);
4979 signature = g_dbus_message_get_signature (message);
4980 path = g_dbus_message_get_path (message);
4982 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4983 g_strcmp0 (member, "Introspect") == 0 &&
4984 g_strcmp0 (signature, "") == 0)
4986 handle_generic_introspect_unlocked (connection, path, message);
4989 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4990 g_strcmp0 (member, "Ping") == 0 &&
4991 g_strcmp0 (signature, "") == 0)
4993 handle_generic_ping_unlocked (connection, path, message);
4996 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4997 g_strcmp0 (member, "GetMachineId") == 0 &&
4998 g_strcmp0 (signature, "") == 0)
5000 handle_generic_get_machine_id_unlocked (connection, path, message);
5007 /* ---------------------------------------------------------------------------------------------------- */
5009 /* called in message handler thread with lock held */
5011 distribute_method_call (GDBusConnection *connection,
5012 GDBusMessage *message)
5015 ExportedSubtree *es;
5016 const gchar *object_path;
5017 const gchar *interface_name;
5018 const gchar *member;
5019 const gchar *signature;
5021 gchar *subtree_path;
5024 g_assert (g_dbus_message_get_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5026 interface_name = g_dbus_message_get_interface (message);
5027 member = g_dbus_message_get_member (message);
5028 signature = g_dbus_message_get_signature (message);
5029 path = g_dbus_message_get_path (message);
5030 subtree_path = g_strdup (path);
5031 needle = strrchr (subtree_path, '/');
5032 if (needle != NULL && needle != subtree_path)
5038 g_free (subtree_path);
5039 subtree_path = NULL;
5043 g_debug ("interface = `%s'", interface_name);
5044 g_debug ("member = `%s'", member);
5045 g_debug ("signature = `%s'", signature);
5046 g_debug ("path = `%s'", path);
5047 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5050 object_path = g_dbus_message_get_path (message);
5051 g_assert (object_path != NULL);
5053 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5056 if (obj_message_func (connection, eo, message))
5060 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5063 if (subtree_message_func (connection, es, message))
5067 if (subtree_path != NULL)
5069 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5072 if (subtree_message_func (connection, es, message))
5077 if (handle_generic_unlocked (connection, message))
5080 /* if we end up here, the message has not been not handled */
5083 g_free (subtree_path);
5086 /* ---------------------------------------------------------------------------------------------------- */
5088 static GDBusConnection **
5089 message_bus_get_singleton (GBusType bus_type,
5092 GDBusConnection **ret;
5093 const gchar *starter_bus;
5100 g_assert_not_reached ();
5103 case G_BUS_TYPE_SESSION:
5104 ret = &the_session_bus;
5107 case G_BUS_TYPE_SYSTEM:
5108 ret = &the_system_bus;
5111 case G_BUS_TYPE_STARTER:
5112 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5113 if (g_strcmp0 (starter_bus, "session") == 0)
5115 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5118 else if (g_strcmp0 (starter_bus, "system") == 0)
5120 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5125 if (starter_bus != NULL)
5129 G_IO_ERROR_INVALID_ARGUMENT,
5130 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5131 " - unknown value `%s'"),
5136 g_set_error_literal (error,
5138 G_IO_ERROR_INVALID_ARGUMENT,
5139 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5140 "variable is not set"));
5149 static GDBusConnection *
5150 get_uninitialized_connection (GBusType bus_type,
5151 GCancellable *cancellable,
5154 GDBusConnection **singleton;
5155 GDBusConnection *ret;
5159 G_LOCK (message_bus_lock);
5160 singleton = message_bus_get_singleton (bus_type, error);
5161 if (singleton == NULL)
5164 if (*singleton == NULL)
5167 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5168 if (address == NULL)
5170 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5172 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5173 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5174 "exit-on-close", TRUE,
5179 ret = g_object_ref (*singleton);
5182 g_assert (ret != NULL);
5185 G_UNLOCK (message_bus_lock);
5191 * @bus_type: A #GBusType.
5192 * @cancellable: A #GCancellable or %NULL.
5193 * @error: Return location for error or %NULL.
5195 * Synchronously connects to the message bus specified by @bus_type.
5196 * Note that the returned object may shared with other callers,
5197 * e.g. if two separate parts of a process calls this function with
5198 * the same @bus_type, they will share the same object.
5200 * This is a synchronous failable function. See g_bus_get() and
5201 * g_bus_get_finish() for the asynchronous version.
5203 * The returned object is a singleton, that is, shared with other
5204 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5205 * event that you need a private message bus connection, use
5206 * g_dbus_address_get_for_bus() and
5207 * g_dbus_connection_new_for_address().
5209 * Note that the returned #GDBusConnection object will (usually) have
5210 * the #GDBusConnection:exit-on-close property set to %TRUE.
5212 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5217 g_bus_get_sync (GBusType bus_type,
5218 GCancellable *cancellable,
5221 GDBusConnection *connection;
5223 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5225 connection = get_uninitialized_connection (bus_type, cancellable, error);
5226 if (connection == NULL)
5229 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5231 g_object_unref (connection);
5240 bus_get_async_initable_cb (GObject *source_object,
5244 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5248 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5252 g_assert (error != NULL);
5253 g_simple_async_result_set_from_error (simple, error);
5254 g_error_free (error);
5255 g_object_unref (source_object);
5259 g_simple_async_result_set_op_res_gpointer (simple,
5263 g_simple_async_result_complete_in_idle (simple);
5264 g_object_unref (simple);
5269 * @bus_type: A #GBusType.
5270 * @cancellable: A #GCancellable or %NULL.
5271 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5272 * @user_data: The data to pass to @callback.
5274 * Asynchronously connects to the message bus specified by @bus_type.
5276 * When the operation is finished, @callback will be invoked. You can
5277 * then call g_bus_get_finish() to get the result of the operation.
5279 * This is a asynchronous failable function. See g_bus_get_sync() for
5280 * the synchronous version.
5285 g_bus_get (GBusType bus_type,
5286 GCancellable *cancellable,
5287 GAsyncReadyCallback callback,
5290 GDBusConnection *connection;
5291 GSimpleAsyncResult *simple;
5294 simple = g_simple_async_result_new (NULL,
5300 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5301 if (connection == NULL)
5303 g_assert (error != NULL);
5304 g_simple_async_result_set_from_error (simple, error);
5305 g_error_free (error);
5306 g_simple_async_result_complete_in_idle (simple);
5307 g_object_unref (simple);
5311 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5314 bus_get_async_initable_cb,
5321 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5322 * @error: Return location for error or %NULL.
5324 * Finishes an operation started with g_bus_get().
5326 * The returned object is a singleton, that is, shared with other
5327 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5328 * event that you need a private message bus connection, use
5329 * g_dbus_address_get_for_bus() and
5330 * g_dbus_connection_new_for_address().
5332 * Note that the returned #GDBusConnection object will (usually) have
5333 * the #GDBusConnection:exit-on-close property set to %TRUE.
5335 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5340 g_bus_get_finish (GAsyncResult *res,
5343 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5345 GDBusConnection *ret;
5347 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5349 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5353 if (g_simple_async_result_propagate_error (simple, error))
5356 object = g_simple_async_result_get_op_res_gpointer (simple);
5357 g_assert (object != NULL);
5358 ret = g_object_ref (G_DBUS_CONNECTION (object));
5364 /* ---------------------------------------------------------------------------------------------------- */