1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - The GDBusProxy::g-properties-changed signal currently looks like this
33 * void user_function (GDBusProxy *proxy,
34 * GHashTable *changed_properties,
35 * gpointer user_data);
37 * which is problematic because some people frown upon GHashTable
38 * usage in public API (in particular some of the JS people). Maybe we
39 * need to rework it, maybe it doesn't matter since GDBusProxy is
40 * a low-level API and, for C code, we expect code generators to
41 * spit out subclasses that automatically hook up to this signal
42 * and does g_object_notify() anyway? Hmm...
44 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
45 * to specify where the nonce is stored. This will allow people to use
46 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
47 * to easily acheive secure RPC via nonce-tcp.
49 * - need to expose an extension point for resolving D-Bus address and
50 * turning them into GIOStream objects. This will allow us to implement
51 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
53 * - see g_dbus_address_connect() in gdbusaddress.c
55 * - would be cute to use kernel-specific APIs to resolve fds for
56 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
58 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
60 * maybe we can show more information about what fd 21 really is.
61 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
62 * Initial experiments on Linux 2.6 suggests that the symlink looks
67 * e.g. not of much use.
75 #include "gdbusauth.h"
76 #include "gdbusutils.h"
77 #include "gdbusaddress.h"
78 #include "gdbusmessage.h"
79 #include "gdbusconnection.h"
80 #include "gdbuserror.h"
81 #include "gioenumtypes.h"
82 #include "gdbusintrospection.h"
83 #include "gdbusmethodinvocation.h"
84 #include "gdbusprivate.h"
85 #include "gdbusauthobserver.h"
86 #include "gio-marshal.h"
87 #include "ginitable.h"
88 #include "gasyncinitable.h"
89 #include "giostream.h"
90 #include "gasyncresult.h"
91 #include "gsimpleasyncresult.h"
94 #include <gio/gunixconnection.h>
95 #include <gio/gunixfdmessage.h>
97 #include <sys/types.h>
100 #include "glibintl.h"
101 #include "gioalias.h"
104 * SECTION:gdbusconnection
105 * @short_description: D-Bus Connections
106 * @include: gio/gio.h
108 * The #GDBusConnection type is used for D-Bus connections to remote
109 * peers such as a message buses. It is a low-level API that offers a
110 * lot of flexibility. For instance, it lets you establish a connection
111 * over any transport that can by represented as an #GIOStream.
113 * This class is rarely used directly in D-Bus clients. If you are writing
114 * an D-Bus client, it is often easier to use the g_bus_own_name(),
115 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
117 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
119 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
121 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
124 /* ---------------------------------------------------------------------------------------------------- */
126 G_LOCK_DEFINE_STATIC (message_bus_lock);
128 static GDBusConnection *the_session_bus = NULL;
129 static GDBusConnection *the_system_bus = NULL;
131 /* ---------------------------------------------------------------------------------------------------- */
134 _g_strv_has_string (const gchar* const * haystack,
139 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
141 if (g_strcmp0 (haystack[n], needle) == 0)
147 /* ---------------------------------------------------------------------------------------------------- */
150 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
152 // TODO: for some reason this doesn't work on Windows
153 #define CONNECTION_ENSURE_LOCK(obj) do { \
154 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
156 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
157 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
162 #define CONNECTION_LOCK(obj) do { \
163 g_mutex_lock ((obj)->priv->lock); \
166 #define CONNECTION_UNLOCK(obj) do { \
167 g_mutex_unlock ((obj)->priv->lock); \
170 struct _GDBusConnectionPrivate
172 /* ------------------------------------------------------------------------ */
173 /* -- General object state ------------------------------------------------ */
174 /* ------------------------------------------------------------------------ */
176 /* object-wide lock */
179 /* A lock used in the init() method of the GInitable interface - see comments
180 * in initable_init() for why a separate lock is needed
184 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
185 * someone calls org.freedesktop.DBus.GetMachineId()
189 /* The underlying stream used for communication */
192 /* The object used for authentication (if any) */
195 /* Set to TRUE if the connection has been closed */
198 /* Last serial used */
201 /* The object used to send/receive message */
204 /* If connected to a message bus, this contains the unique name assigned to
205 * us by the bus (e.g. ":1.42")
207 gchar *bus_unique_name;
209 /* The GUID returned by the other side if we authenticed as a client or
210 * the GUID to use if authenticating as a server
214 /* set to TRUE exactly when initable_init() has finished running */
215 gboolean is_initialized;
217 /* If the connection could not be established during initable_init(), this GError will set */
218 GError *initialization_error;
220 /* The result of g_main_context_get_thread_default() when the object
221 * was created (the GObject _init() function) - this is used for delivery
222 * of the :closed GObject signal.
224 GMainContext *main_context_at_construction;
226 /* construct properties */
228 GDBusConnectionFlags flags;
230 /* Map used for managing method replies */
231 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
233 /* Maps used for managing signal subscription */
234 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
235 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
236 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
238 /* Maps used for managing exported objects and subtrees */
239 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
240 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
241 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
242 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
244 /* Structure used for message filters */
247 /* Whether to exit on close */
248 gboolean exit_on_close;
250 /* Capabilities negotiated during authentication */
251 GDBusCapabilityFlags capabilities;
253 GDBusAuthObserver *authentication_observer;
254 GCredentials *crendentials;
257 typedef struct ExportedObject ExportedObject;
258 static void exported_object_free (ExportedObject *eo);
260 typedef struct ExportedSubtree ExportedSubtree;
261 static void exported_subtree_free (ExportedSubtree *es);
279 PROP_CAPABILITY_FLAGS,
280 PROP_AUTHENTICATION_OBSERVER,
283 static void distribute_signals (GDBusConnection *connection,
284 GDBusMessage *message);
286 static void distribute_method_call (GDBusConnection *connection,
287 GDBusMessage *message);
289 static gboolean handle_generic_unlocked (GDBusConnection *connection,
290 GDBusMessage *message);
293 static void purge_all_signal_subscriptions (GDBusConnection *connection);
294 static void purge_all_filters (GDBusConnection *connection);
296 #define _G_ENSURE_LOCK(name) do { \
297 if (G_UNLIKELY (G_TRYLOCK(name))) \
299 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
300 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
304 static guint signals[LAST_SIGNAL] = { 0 };
306 static void initable_iface_init (GInitableIface *initable_iface);
307 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
309 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
310 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
311 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
315 g_dbus_connection_dispose (GObject *object)
317 GDBusConnection *connection = G_DBUS_CONNECTION (object);
319 G_LOCK (message_bus_lock);
320 //g_debug ("disposing %p", connection);
321 if (connection == the_session_bus)
323 the_session_bus = NULL;
325 else if (connection == the_system_bus)
327 the_system_bus = NULL;
329 if (connection->priv->worker != NULL)
331 _g_dbus_worker_stop (connection->priv->worker);
332 connection->priv->worker = NULL;
334 G_UNLOCK (message_bus_lock);
336 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
337 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
341 g_dbus_connection_finalize (GObject *object)
343 GDBusConnection *connection = G_DBUS_CONNECTION (object);
345 if (connection->priv->authentication_observer != NULL)
346 g_object_unref (connection->priv->authentication_observer);
348 if (connection->priv->auth != NULL)
349 g_object_unref (connection->priv->auth);
351 //g_debug ("finalizing %p", connection);
352 if (connection->priv->stream != NULL)
354 /* We don't really care if closing the stream succeeds or not */
355 g_io_stream_close_async (connection->priv->stream,
357 NULL, /* GCancellable */
358 NULL, /* GAsyncReadyCallback */
359 NULL); /* userdata */
360 g_object_unref (connection->priv->stream);
361 connection->priv->stream = NULL;
364 g_free (connection->priv->address);
366 g_free (connection->priv->guid);
367 g_free (connection->priv->bus_unique_name);
369 if (connection->priv->initialization_error != NULL)
370 g_error_free (connection->priv->initialization_error);
372 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
374 purge_all_signal_subscriptions (connection);
375 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
376 g_hash_table_unref (connection->priv->map_id_to_signal_data);
377 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
379 g_hash_table_unref (connection->priv->map_id_to_ei);
380 g_hash_table_unref (connection->priv->map_object_path_to_eo);
381 g_hash_table_unref (connection->priv->map_id_to_es);
382 g_hash_table_unref (connection->priv->map_object_path_to_es);
384 purge_all_filters (connection);
385 g_ptr_array_unref (connection->priv->filters);
387 if (connection->priv->main_context_at_construction != NULL)
388 g_main_context_unref (connection->priv->main_context_at_construction);
390 g_free (connection->priv->machine_id);
392 g_mutex_free (connection->priv->init_lock);
393 g_mutex_free (connection->priv->lock);
395 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize != NULL)
396 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
400 g_dbus_connection_get_property (GObject *object,
405 GDBusConnection *connection = G_DBUS_CONNECTION (object);
410 g_value_set_object (value, g_dbus_connection_get_stream (connection));
414 g_value_set_string (value, g_dbus_connection_get_guid (connection));
417 case PROP_UNIQUE_NAME:
418 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
422 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
425 case PROP_EXIT_ON_CLOSE:
426 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
429 case PROP_CAPABILITY_FLAGS:
430 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
434 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
440 g_dbus_connection_set_property (GObject *object,
445 GDBusConnection *connection = G_DBUS_CONNECTION (object);
450 connection->priv->stream = g_value_dup_object (value);
454 connection->priv->guid = g_value_dup_string (value);
458 connection->priv->address = g_value_dup_string (value);
462 connection->priv->flags = g_value_get_flags (value);
465 case PROP_EXIT_ON_CLOSE:
466 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
469 case PROP_AUTHENTICATION_OBSERVER:
470 connection->priv->authentication_observer = g_value_dup_object (value);
474 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
480 g_dbus_connection_real_closed (GDBusConnection *connection,
481 gboolean remote_peer_vanished,
484 if (remote_peer_vanished && connection->priv->exit_on_close)
486 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
492 g_dbus_connection_class_init (GDBusConnectionClass *klass)
494 GObjectClass *gobject_class;
496 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
498 gobject_class = G_OBJECT_CLASS (klass);
500 gobject_class->finalize = g_dbus_connection_finalize;
501 gobject_class->dispose = g_dbus_connection_dispose;
502 gobject_class->set_property = g_dbus_connection_set_property;
503 gobject_class->get_property = g_dbus_connection_get_property;
505 klass->closed = g_dbus_connection_real_closed;
508 * GDBusConnection:stream:
510 * The underlying #GIOStream used for I/O.
514 g_object_class_install_property (gobject_class,
516 g_param_spec_object ("stream",
518 _("The underlying streams used for I/O"),
522 G_PARAM_CONSTRUCT_ONLY |
523 G_PARAM_STATIC_NAME |
524 G_PARAM_STATIC_BLURB |
525 G_PARAM_STATIC_NICK));
528 * GDBusConnection:address:
530 * A D-Bus address specifying potential endpoints that can be used
531 * when establishing the connection.
535 g_object_class_install_property (gobject_class,
537 g_param_spec_string ("address",
539 _("D-Bus address specifying potential socket endpoints"),
542 G_PARAM_CONSTRUCT_ONLY |
543 G_PARAM_STATIC_NAME |
544 G_PARAM_STATIC_BLURB |
545 G_PARAM_STATIC_NICK));
548 * GDBusConnection:flags:
550 * Flags from the #GDBusConnectionFlags enumeration.
554 g_object_class_install_property (gobject_class,
556 g_param_spec_flags ("flags",
559 G_TYPE_DBUS_CONNECTION_FLAGS,
560 G_DBUS_CONNECTION_FLAGS_NONE,
562 G_PARAM_CONSTRUCT_ONLY |
563 G_PARAM_STATIC_NAME |
564 G_PARAM_STATIC_BLURB |
565 G_PARAM_STATIC_NICK));
568 * GDBusConnection:guid:
570 * The GUID of the peer performing the role of server when
573 * If you are constructing a #GDBusConnection and pass
574 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
575 * #GDBusConnection:flags property then you MUST also set this
576 * property to a valid guid.
578 * If you are constructing a #GDBusConnection and pass
579 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
580 * #GDBusConnection:flags property you will be able to read the GUID
581 * of the other peer here after the connection has been succesfully
586 g_object_class_install_property (gobject_class,
588 g_param_spec_string ("guid",
590 _("GUID of the server peer"),
594 G_PARAM_CONSTRUCT_ONLY |
595 G_PARAM_STATIC_NAME |
596 G_PARAM_STATIC_BLURB |
597 G_PARAM_STATIC_NICK));
600 * GDBusConnection:unique-name:
602 * The unique name as assigned by the message bus or %NULL if the
603 * connection is not open or not a message bus connection.
607 g_object_class_install_property (gobject_class,
609 g_param_spec_string ("unique-name",
611 _("Unique name of bus connection"),
614 G_PARAM_STATIC_NAME |
615 G_PARAM_STATIC_BLURB |
616 G_PARAM_STATIC_NICK));
619 * GDBusConnection:closed:
621 * A boolean specifying whether the connection has been closed.
625 g_object_class_install_property (gobject_class,
627 g_param_spec_boolean ("closed",
629 _("Whether the connection is closed"),
632 G_PARAM_STATIC_NAME |
633 G_PARAM_STATIC_BLURB |
634 G_PARAM_STATIC_NICK));
637 * GDBusConnection:exit-on-close:
639 * A boolean specifying whether the process will be terminated (by
640 * calling <literal>raise(SIGTERM)</literal>) if the connection
641 * is closed by the remote peer.
645 g_object_class_install_property (gobject_class,
647 g_param_spec_boolean ("exit-on-close",
649 _("Whether the process is terminated when the connection is closed"),
653 G_PARAM_STATIC_NAME |
654 G_PARAM_STATIC_BLURB |
655 G_PARAM_STATIC_NICK));
658 * GDBusConnection:capabilities:
660 * Flags from the #GDBusCapabilityFlags enumeration
661 * representing connection features negotiated with the other peer.
665 g_object_class_install_property (gobject_class,
666 PROP_CAPABILITY_FLAGS,
667 g_param_spec_flags ("capabilities",
670 G_TYPE_DBUS_CAPABILITY_FLAGS,
671 G_DBUS_CAPABILITY_FLAGS_NONE,
673 G_PARAM_STATIC_NAME |
674 G_PARAM_STATIC_BLURB |
675 G_PARAM_STATIC_NICK));
678 * GDBusConnection:authentication-observer:
680 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
684 g_object_class_install_property (gobject_class,
685 PROP_AUTHENTICATION_OBSERVER,
686 g_param_spec_object ("authentication-observer",
687 _("Authentication Observer"),
688 _("Object used to assist in the authentication process"),
689 G_TYPE_DBUS_AUTH_OBSERVER,
691 G_PARAM_CONSTRUCT_ONLY |
692 G_PARAM_STATIC_NAME |
693 G_PARAM_STATIC_BLURB |
694 G_PARAM_STATIC_NICK));
697 * GDBusConnection::closed:
698 * @connection: The #GDBusConnection emitting the signal.
699 * @remote_peer_vanished: %TRUE if @connection is closed because the
700 * remote peer closed its end of the connection.
701 * @error: A #GError with more details about the event or %NULL.
703 * Emitted when the connection is closed.
705 * The cause of this event can be
708 * If g_dbus_connection_close() is called. In this case
709 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
712 * If the remote peer closes the connection. In this case
713 * @remote_peer_vanished is set to %TRUE and @error is set.
716 * If the remote peer sends invalid or malformed data. In this
717 * case @remote_peer_vanished is set to %FALSE and @error
722 * Upon receiving this signal, you should give up your reference to
723 * @connection. You are guaranteed that this signal is emitted only
728 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
729 G_TYPE_DBUS_CONNECTION,
731 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
734 _gio_marshal_VOID__BOOLEAN_BOXED,
742 g_dbus_connection_init (GDBusConnection *connection)
744 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
746 connection->priv->lock = g_mutex_new ();
747 connection->priv->init_lock = g_mutex_new ();
749 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
751 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
753 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
755 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
760 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
763 (GDestroyNotify) exported_object_free);
765 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
768 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
771 (GDestroyNotify) exported_subtree_free);
773 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
776 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
777 if (connection->priv->main_context_at_construction != NULL)
778 g_main_context_ref (connection->priv->main_context_at_construction);
780 connection->priv->filters = g_ptr_array_new ();
784 g_dbus_connection_get_stream (GDBusConnection *connection)
786 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
787 return connection->priv->stream;
792 * g_dbus_connection_is_closed:
793 * @connection: A #GDBusConnection.
795 * Gets whether @connection is closed.
797 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
802 g_dbus_connection_is_closed (GDBusConnection *connection)
804 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
805 return connection->priv->closed;
809 * g_dbus_connection_get_capabilities:
810 * @connection: A #GDBusConnection.
812 * Gets the capabilities negotiated with the remote peer
814 * Returns: One or more flags from the #GDBusCapabilityFlags enumeration.
819 g_dbus_connection_get_capabilities (GDBusConnection *connection)
821 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
822 return connection->priv->capabilities;
826 /* ---------------------------------------------------------------------------------------------------- */
830 GDBusConnection *connection;
832 gboolean remote_peer_vanished;
836 emit_closed_data_free (EmitClosedData *data)
838 g_object_unref (data->connection);
839 if (data->error != NULL)
840 g_error_free (data->error);
845 emit_closed_in_idle (gpointer user_data)
847 EmitClosedData *data = user_data;
850 g_object_notify (G_OBJECT (data->connection), "closed");
851 g_signal_emit (data->connection,
852 signals[CLOSED_SIGNAL],
854 data->remote_peer_vanished,
860 /* Can be called from any thread, must hold lock */
862 set_closed_unlocked (GDBusConnection *connection,
863 gboolean remote_peer_vanished,
866 GSource *idle_source;
867 EmitClosedData *data;
869 CONNECTION_ENSURE_LOCK (connection);
871 g_assert (!connection->priv->closed);
873 connection->priv->closed = TRUE;
875 data = g_new0 (EmitClosedData, 1);
876 data->connection = g_object_ref (connection);
877 data->remote_peer_vanished = remote_peer_vanished;
878 data->error = error != NULL ? g_error_copy (error) : NULL;
880 idle_source = g_idle_source_new ();
881 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
882 g_source_set_callback (idle_source,
885 (GDestroyNotify) emit_closed_data_free);
886 g_source_attach (idle_source, connection->priv->main_context_at_construction);
887 g_source_unref (idle_source);
890 /* ---------------------------------------------------------------------------------------------------- */
893 * g_dbus_connection_close:
894 * @connection: A #GDBusConnection.
896 * Closes @connection. Note that this never causes the process to
897 * exit (this might only happen if the other end of a shared message
898 * bus connection disconnects).
900 * If @connection is already closed, this method does nothing.
905 g_dbus_connection_close (GDBusConnection *connection)
907 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
909 CONNECTION_LOCK (connection);
910 if (!connection->priv->closed)
912 GError *error = NULL;
914 /* TODO: do this async */
915 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
916 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
918 g_warning ("Error closing stream: %s", error->message);
919 g_error_free (error);
922 set_closed_unlocked (connection, FALSE, NULL);
924 CONNECTION_UNLOCK (connection);
927 /* ---------------------------------------------------------------------------------------------------- */
930 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
931 GDBusMessage *message,
932 volatile guint32 *out_serial,
937 guint32 serial_to_use;
940 CONNECTION_ENSURE_LOCK (connection);
942 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
943 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
945 /* TODO: check all necessary headers are present */
950 if (out_serial != NULL)
953 if (connection->priv->closed)
955 g_set_error_literal (error,
958 _("The connection is closed"));
962 blob = g_dbus_message_to_blob (message,
968 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
973 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
976 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
979 g_assert_not_reached ();
984 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
985 blob_size, serial_to_use, connection);
986 g_printerr ("----\n");
987 hexdump (blob, blob_size);
988 g_printerr ("----\n");
991 /* TODO: use connection->priv->auth to encode the blob */
993 if (out_serial != NULL)
995 *out_serial = serial_to_use;
997 g_dbus_message_set_serial (message, serial_to_use);
999 _g_dbus_worker_send_message (connection->priv->worker,
1003 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1014 * g_dbus_connection_send_message:
1015 * @connection: A #GDBusConnection.
1016 * @message: A #GDBusMessage
1017 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1018 * @error: Return location for error or %NULL.
1020 * Asynchronously sends @message to the peer represented by @connection.
1022 * If @out_serial is not %NULL, then the serial number assigned to
1023 * @message by @connection will be written to this location prior to
1024 * submitting the message to the underlying transport.
1026 * If @connection is closed then the operation will fail with
1027 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1028 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1029 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1031 * See <xref linkend="gdbus-server"/> and <xref
1032 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1033 * low-level API to send and receive UNIX file descriptors.
1035 * Returns: %TRUE if the message was well-formed and queued for
1036 * transmission, %FALSE if @error is set.
1041 g_dbus_connection_send_message (GDBusConnection *connection,
1042 GDBusMessage *message,
1043 volatile guint32 *out_serial,
1048 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1049 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1050 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1052 CONNECTION_LOCK (connection);
1053 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1054 CONNECTION_UNLOCK (connection);
1058 /* ---------------------------------------------------------------------------------------------------- */
1062 volatile gint ref_count;
1063 GDBusConnection *connection;
1065 GSimpleAsyncResult *simple;
1067 GMainContext *main_context;
1069 GCancellable *cancellable;
1071 gulong cancellable_handler_id;
1073 GSource *timeout_source;
1078 static SendMessageData *
1079 send_message_data_ref (SendMessageData *data)
1081 g_atomic_int_inc (&data->ref_count);
1086 send_message_data_unref (SendMessageData *data)
1088 if (g_atomic_int_dec_and_test (&data->ref_count))
1090 g_assert (data->timeout_source == NULL);
1091 g_assert (data->simple == NULL);
1092 g_assert (data->cancellable_handler_id == 0);
1093 g_object_unref (data->connection);
1094 if (data->cancellable != NULL)
1095 g_object_unref (data->cancellable);
1096 if (data->main_context != NULL)
1097 g_main_context_unref (data->main_context);
1102 /* ---------------------------------------------------------------------------------------------------- */
1104 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1106 send_message_with_reply_deliver (SendMessageData *data)
1108 CONNECTION_ENSURE_LOCK (data->connection);
1110 g_assert (!data->delivered);
1112 data->delivered = TRUE;
1114 g_simple_async_result_complete_in_idle (data->simple);
1115 g_object_unref (data->simple);
1116 data->simple = NULL;
1118 if (data->timeout_source != NULL)
1120 g_source_destroy (data->timeout_source);
1121 data->timeout_source = NULL;
1123 if (data->cancellable_handler_id > 0)
1125 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1126 data->cancellable_handler_id = 0;
1129 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1130 GUINT_TO_POINTER (data->serial)));
1132 send_message_data_unref (data);
1135 /* ---------------------------------------------------------------------------------------------------- */
1137 /* must hold lock */
1139 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1140 GDBusMessage *reply)
1142 if (data->delivered)
1145 g_simple_async_result_set_op_res_gpointer (data->simple,
1146 g_object_ref (reply),
1149 send_message_with_reply_deliver (data);
1155 /* ---------------------------------------------------------------------------------------------------- */
1158 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1160 SendMessageData *data = user_data;
1162 CONNECTION_LOCK (data->connection);
1163 if (data->delivered)
1166 g_simple_async_result_set_error (data->simple,
1168 G_IO_ERROR_CANCELLED,
1169 _("Operation was cancelled"));
1171 send_message_with_reply_deliver (data);
1174 CONNECTION_UNLOCK (data->connection);
1178 /* Can be called from any thread with or without lock held */
1180 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1183 SendMessageData *data = user_data;
1184 GSource *idle_source;
1186 /* postpone cancellation to idle handler since we may be called directly
1187 * via g_cancellable_connect() (e.g. holding lock)
1189 idle_source = g_idle_source_new ();
1190 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1191 g_source_set_callback (idle_source,
1192 send_message_with_reply_cancelled_idle_cb,
1193 send_message_data_ref (data),
1194 (GDestroyNotify) send_message_data_unref);
1195 g_source_attach (idle_source, data->main_context);
1196 g_source_unref (idle_source);
1199 /* ---------------------------------------------------------------------------------------------------- */
1202 send_message_with_reply_timeout_cb (gpointer user_data)
1204 SendMessageData *data = user_data;
1206 CONNECTION_LOCK (data->connection);
1207 if (data->delivered)
1210 g_simple_async_result_set_error (data->simple,
1212 G_IO_ERROR_TIMED_OUT,
1213 _("Timeout was reached"));
1215 send_message_with_reply_deliver (data);
1218 CONNECTION_UNLOCK (data->connection);
1223 /* ---------------------------------------------------------------------------------------------------- */
1226 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1227 GDBusMessage *message,
1229 volatile guint32 *out_serial,
1230 GCancellable *cancellable,
1231 GAsyncReadyCallback callback,
1234 GSimpleAsyncResult *simple;
1235 SendMessageData *data;
1237 volatile guint32 serial;
1241 if (out_serial == NULL)
1242 out_serial = &serial;
1244 if (timeout_msec == -1)
1245 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1247 simple = g_simple_async_result_new (G_OBJECT (connection),
1250 g_dbus_connection_send_message_with_reply);
1252 if (g_cancellable_is_cancelled (cancellable))
1254 g_simple_async_result_set_error (simple,
1256 G_IO_ERROR_CANCELLED,
1257 _("Operation was cancelled"));
1258 g_simple_async_result_complete_in_idle (simple);
1259 g_object_unref (simple);
1263 if (connection->priv->closed)
1265 g_simple_async_result_set_error (simple,
1268 _("The connection is closed"));
1269 g_simple_async_result_complete_in_idle (simple);
1270 g_object_unref (simple);
1275 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1277 g_simple_async_result_set_from_error (simple, error);
1278 g_simple_async_result_complete_in_idle (simple);
1279 g_object_unref (simple);
1283 data = g_new0 (SendMessageData, 1);
1284 data->ref_count = 1;
1285 data->connection = g_object_ref (connection);
1286 data->simple = simple;
1287 data->serial = *out_serial;
1288 data->main_context = g_main_context_get_thread_default ();
1289 if (data->main_context != NULL)
1290 g_main_context_ref (data->main_context);
1292 if (cancellable != NULL)
1294 data->cancellable = g_object_ref (cancellable);
1295 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1296 G_CALLBACK (send_message_with_reply_cancelled_cb),
1297 send_message_data_ref (data),
1298 (GDestroyNotify) send_message_data_unref);
1299 g_object_set_data_full (G_OBJECT (simple),
1301 g_object_ref (cancellable),
1302 (GDestroyNotify) g_object_unref);
1305 data->timeout_source = g_timeout_source_new (timeout_msec);
1306 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1307 g_source_set_callback (data->timeout_source,
1308 send_message_with_reply_timeout_cb,
1309 send_message_data_ref (data),
1310 (GDestroyNotify) send_message_data_unref);
1311 g_source_attach (data->timeout_source, data->main_context);
1312 g_source_unref (data->timeout_source);
1314 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1315 GUINT_TO_POINTER (*out_serial),
1323 * g_dbus_connection_send_message_with_reply:
1324 * @connection: A #GDBusConnection.
1325 * @message: A #GDBusMessage.
1326 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1327 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1328 * @cancellable: A #GCancellable or %NULL.
1329 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1330 * care about the result.
1331 * @user_data: The data to pass to @callback.
1333 * Asynchronously sends @message to the peer represented by @connection.
1335 * If @out_serial is not %NULL, then the serial number assigned to
1336 * @message by @connection will be written to this location prior to
1337 * submitting the message to the underlying transport.
1339 * If @connection is closed then the operation will fail with
1340 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1341 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1342 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1344 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1345 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1346 * of the thread you are calling this method from. You can then call
1347 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1348 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1350 * See <xref linkend="gdbus-server"/> and <xref
1351 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1352 * low-level API to send and receive UNIX file descriptors.
1357 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1358 GDBusMessage *message,
1360 volatile guint32 *out_serial,
1361 GCancellable *cancellable,
1362 GAsyncReadyCallback callback,
1365 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1366 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1367 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1369 CONNECTION_LOCK (connection);
1370 g_dbus_connection_send_message_with_reply_unlocked (connection,
1377 CONNECTION_UNLOCK (connection);
1381 * g_dbus_connection_send_message_with_reply_finish:
1382 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1383 * @error: Return location for error or %NULL.
1385 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1387 * Note that @error is only set if a local in-process error
1388 * occured. That is to say that the returned #GDBusMessage object may
1389 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1390 * g_dbus_message_to_gerror() to transcode this to a #GError.
1392 * See <xref linkend="gdbus-server"/> and <xref
1393 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1394 * low-level API to send and receive UNIX file descriptors.
1396 * Returns: A #GDBusMessage or %NULL if @error is set.
1401 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1405 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1406 GDBusMessage *reply;
1407 GCancellable *cancellable;
1409 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1410 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1414 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1416 if (g_simple_async_result_propagate_error (simple, error))
1419 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1420 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1421 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1423 g_object_unref (reply);
1425 g_set_error_literal (error,
1427 G_IO_ERROR_CANCELLED,
1428 _("Operation was cancelled"));
1434 /* ---------------------------------------------------------------------------------------------------- */
1439 GMainContext *context;
1441 } SendMessageSyncData;
1444 send_message_with_reply_sync_cb (GDBusConnection *connection,
1448 SendMessageSyncData *data = user_data;
1449 data->res = g_object_ref (res);
1450 g_main_loop_quit (data->loop);
1454 * g_dbus_connection_send_message_with_reply_sync:
1455 * @connection: A #GDBusConnection.
1456 * @message: A #GDBusMessage.
1457 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1458 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1459 * @cancellable: A #GCancellable or %NULL.
1460 * @error: Return location for error or %NULL.
1462 * Synchronously sends @message to the peer represented by @connection
1463 * and blocks the calling thread until a reply is received or the
1464 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1465 * for the asynchronous version of this method.
1467 * If @out_serial is not %NULL, then the serial number assigned to
1468 * @message by @connection will be written to this location prior to
1469 * submitting the message to the underlying transport.
1471 * If @connection is closed then the operation will fail with
1472 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1473 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1474 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1476 * Note that @error is only set if a local in-process error
1477 * occured. That is to say that the returned #GDBusMessage object may
1478 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1479 * g_dbus_message_to_gerror() to transcode this to a #GError.
1481 * See <xref linkend="gdbus-server"/> and <xref
1482 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1483 * low-level API to send and receive UNIX file descriptors.
1485 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1490 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1491 GDBusMessage *message,
1493 volatile guint32 *out_serial,
1494 GCancellable *cancellable,
1497 SendMessageSyncData *data;
1498 GDBusMessage *reply;
1500 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1501 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1502 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1503 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1505 data = g_new0 (SendMessageSyncData, 1);
1506 data->context = g_main_context_new ();
1507 data->loop = g_main_loop_new (data->context, FALSE);
1509 g_main_context_push_thread_default (data->context);
1511 g_dbus_connection_send_message_with_reply (connection,
1516 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1518 g_main_loop_run (data->loop);
1519 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1523 g_main_context_pop_thread_default (data->context);
1525 g_main_context_unref (data->context);
1526 g_main_loop_unref (data->loop);
1527 g_object_unref (data->res);
1533 /* ---------------------------------------------------------------------------------------------------- */
1537 GDBusMessageFilterFunction func;
1544 GDBusMessageFilterFunction filter_function;
1546 GDestroyNotify user_data_free_func;
1549 /* Called in worker's thread - we must not block */
1551 on_worker_message_received (GDBusWorker *worker,
1552 GDBusMessage *message,
1555 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1556 FilterCallback *filters;
1557 gboolean consumed_by_filter;
1561 //g_debug ("in on_worker_message_received");
1563 g_object_ref (connection);
1565 /* First collect the set of callback functions */
1566 CONNECTION_LOCK (connection);
1567 num_filters = connection->priv->filters->len;
1568 filters = g_new0 (FilterCallback, num_filters);
1569 for (n = 0; n < num_filters; n++)
1571 FilterData *data = connection->priv->filters->pdata[n];
1572 filters[n].func = data->filter_function;
1573 filters[n].user_data = data->user_data;
1575 CONNECTION_UNLOCK (connection);
1577 /* the call the filters in order (without holding the lock) */
1578 consumed_by_filter = FALSE;
1579 for (n = 0; n < num_filters; n++)
1581 consumed_by_filter = filters[n].func (connection,
1583 filters[n].user_data);
1584 if (consumed_by_filter)
1588 /* Standard dispatch unless the filter ate the message */
1589 if (!consumed_by_filter)
1591 GDBusMessageType message_type;
1593 message_type = g_dbus_message_get_message_type (message);
1594 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1596 guint32 reply_serial;
1597 SendMessageData *send_message_data;
1599 reply_serial = g_dbus_message_get_reply_serial (message);
1600 CONNECTION_LOCK (connection);
1601 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1602 GUINT_TO_POINTER (reply_serial));
1603 if (send_message_data != NULL)
1605 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1606 send_message_data_deliver_reply_unlocked (send_message_data, message);
1610 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1612 CONNECTION_UNLOCK (connection);
1614 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1616 CONNECTION_LOCK (connection);
1617 distribute_signals (connection, message);
1618 CONNECTION_UNLOCK (connection);
1620 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1622 CONNECTION_LOCK (connection);
1623 distribute_method_call (connection, message);
1624 CONNECTION_UNLOCK (connection);
1628 g_object_unref (connection);
1632 /* Called in worker's thread - we must not block */
1634 on_worker_closed (GDBusWorker *worker,
1635 gboolean remote_peer_vanished,
1639 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1641 //g_debug ("in on_worker_closed: %s", error->message);
1643 CONNECTION_LOCK (connection);
1644 if (!connection->priv->closed)
1645 set_closed_unlocked (connection, remote_peer_vanished, error);
1646 CONNECTION_UNLOCK (connection);
1649 /* ---------------------------------------------------------------------------------------------------- */
1651 /* Determines the biggest set of capabilities we can support on this connection */
1652 static GDBusCapabilityFlags
1653 get_offered_capabilities_max (GDBusConnection *connection)
1655 GDBusCapabilityFlags ret;
1656 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1658 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1660 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1668 initable_init (GInitable *initable,
1669 GCancellable *cancellable,
1672 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1675 /* This method needs to be idempotent to work with the singleton
1676 * pattern. See the docs for g_initable_init(). We implement this by
1679 * Unfortunately we can't use the main lock since the on_worker_*()
1680 * callbacks above needs the lock during initialization (for message
1681 * bus connections we do a synchronous Hello() call on the bus).
1683 g_mutex_lock (connection->priv->init_lock);
1687 if (connection->priv->is_initialized)
1689 if (connection->priv->stream != NULL)
1692 g_assert (connection->priv->initialization_error != NULL);
1695 g_assert (connection->priv->initialization_error == NULL);
1697 /* The user can pass multiple (but mutally exclusive) construct
1700 * - stream (of type GIOStream)
1701 * - address (of type gchar*)
1703 * At the end of the day we end up with a non-NULL GIOStream
1704 * object in connection->priv->stream.
1706 if (connection->priv->address != NULL)
1708 g_assert (connection->priv->stream == NULL);
1710 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1711 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1713 g_set_error_literal (error,
1715 G_IO_ERROR_INVALID_ARGUMENT,
1716 _("Unsupported flags encountered when constructing a client-side connection"));
1720 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1721 NULL, /* TODO: out_guid */
1723 &connection->priv->initialization_error);
1724 if (connection->priv->stream == NULL)
1727 else if (connection->priv->stream != NULL)
1733 g_assert_not_reached ();
1736 /* Authenticate the connection */
1737 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1739 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1740 g_assert (connection->priv->guid != NULL);
1741 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1742 if (!_g_dbus_auth_run_server (connection->priv->auth,
1743 connection->priv->authentication_observer,
1744 connection->priv->guid,
1745 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1746 get_offered_capabilities_max (connection),
1747 &connection->priv->capabilities,
1748 &connection->priv->crendentials,
1750 &connection->priv->initialization_error))
1753 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1755 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1756 g_assert (connection->priv->guid == NULL);
1757 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1758 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1759 get_offered_capabilities_max (connection),
1760 &connection->priv->capabilities,
1762 &connection->priv->initialization_error);
1763 if (connection->priv->guid == NULL)
1767 if (connection->priv->authentication_observer != NULL)
1769 g_object_unref (connection->priv->authentication_observer);
1770 connection->priv->authentication_observer = NULL;
1773 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1775 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1779 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1783 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1785 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1788 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1789 connection->priv->capabilities,
1790 on_worker_message_received,
1794 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1795 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1797 GVariant *hello_result;
1800 hello_result = g_dbus_connection_invoke_method_sync (connection,
1801 "org.freedesktop.DBus", /* name */
1802 "/org/freedesktop/DBus", /* path */
1803 "org.freedesktop.DBus", /* interface */
1805 NULL, /* parameters */
1806 G_DBUS_INVOKE_METHOD_FLAGS_NONE,
1808 NULL, /* TODO: cancellable */
1809 &connection->priv->initialization_error);
1810 if (hello_result == NULL)
1813 g_variant_get (hello_result, "(s)", &s);
1814 connection->priv->bus_unique_name = g_strdup (s);
1815 g_variant_unref (hello_result);
1816 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1819 connection->priv->is_initialized = TRUE;
1825 g_assert (connection->priv->initialization_error != NULL);
1826 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1829 g_mutex_unlock (connection->priv->init_lock);
1835 initable_iface_init (GInitableIface *initable_iface)
1837 initable_iface->init = initable_init;
1840 /* ---------------------------------------------------------------------------------------------------- */
1843 async_init_thread (GSimpleAsyncResult *res,
1845 GCancellable *cancellable)
1847 GError *error = NULL;
1849 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1851 g_simple_async_result_set_from_error (res, error);
1852 g_error_free (error);
1857 async_initable_init_async (GAsyncInitable *initable,
1859 GCancellable *cancellable,
1860 GAsyncReadyCallback callback,
1863 GSimpleAsyncResult *res;
1865 g_return_if_fail (G_IS_INITABLE (initable));
1867 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1868 async_initable_init_async);
1869 g_simple_async_result_run_in_thread (res, async_init_thread,
1870 io_priority, cancellable);
1871 g_object_unref (res);
1875 async_initable_init_finish (GAsyncInitable *initable,
1879 return TRUE; /* Errors handled by base impl */
1883 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1885 /* We basically just want to use GIO's default implementation - though that one is
1886 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1888 async_initable_iface->init_async = async_initable_init_async;
1889 async_initable_iface->init_finish = async_initable_init_finish;
1892 /* ---------------------------------------------------------------------------------------------------- */
1895 * g_dbus_connection_new:
1896 * @stream: A #GIOStream.
1897 * @guid: The GUID to use if a authenticating as a server or %NULL.
1898 * @flags: Flags describing how to make the connection.
1899 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1900 * @cancellable: A #GCancellable or %NULL.
1901 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1902 * @user_data: The data to pass to @callback.
1904 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1905 * with the end represented by @stream.
1907 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1908 * @auth_observer (if not %NULL) is used to assist in the client
1909 * authentication process.
1911 * When the operation is finished, @callback will be invoked. You can
1912 * then call g_dbus_connection_new_finish() to get the result of the
1915 * This is a asynchronous failable constructor. See
1916 * g_dbus_connection_new_sync() for the synchronous
1922 g_dbus_connection_new (GIOStream *stream,
1924 GDBusConnectionFlags flags,
1925 GDBusAuthObserver *authentication_observer,
1926 GCancellable *cancellable,
1927 GAsyncReadyCallback callback,
1930 g_return_if_fail (G_IS_IO_STREAM (stream));
1931 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1939 "authentication-observer", authentication_observer,
1944 * g_dbus_connection_new_finish:
1945 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1946 * @error: Return location for error or %NULL.
1948 * Finishes an operation started with g_dbus_connection_new().
1950 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1955 g_dbus_connection_new_finish (GAsyncResult *res,
1959 GObject *source_object;
1961 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1962 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1964 source_object = g_async_result_get_source_object (res);
1965 g_assert (source_object != NULL);
1966 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1969 g_object_unref (source_object);
1971 return G_DBUS_CONNECTION (object);
1977 * g_dbus_connection_new_sync:
1978 * @stream: A #GIOStream.
1979 * @guid: The GUID to use if a authenticating as a server or %NULL.
1980 * @flags: Flags describing how to make the connection.
1981 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1982 * @cancellable: A #GCancellable or %NULL.
1983 * @error: Return location for error or %NULL.
1985 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1986 * with the end represented by @stream.
1988 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1989 * @auth_observer (if not %NULL) is used to assist in the client
1990 * authentication process.
1992 * This is a synchronous failable constructor. See
1993 * g_dbus_connection_new() for the asynchronous version.
1995 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2000 g_dbus_connection_new_sync (GIOStream *stream,
2002 GDBusConnectionFlags flags,
2003 GDBusAuthObserver *authentication_observer,
2004 GCancellable *cancellable,
2007 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2008 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2009 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2015 "authentication-observer", authentication_observer,
2019 /* ---------------------------------------------------------------------------------------------------- */
2022 * g_dbus_connection_new_for_address:
2023 * @address: A D-Bus address.
2024 * @flags: Flags describing how to make the connection.
2025 * @cancellable: A #GCancellable or %NULL.
2026 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2027 * @user_data: The data to pass to @callback.
2029 * Asynchronously connects and sets up a D-Bus client connection for
2030 * exchanging D-Bus messages with an endpoint specified by @address
2031 * which must be in the D-Bus address format.
2033 * This constructor can only be used to initiate client-side
2034 * connections - use g_dbus_connection_new() if you need to act as the
2035 * server. In particular, @flags cannot contain the
2036 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2037 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2039 * When the operation is finished, @callback will be invoked. You can
2040 * then call g_dbus_connection_new_finish() to get the result of the
2043 * This is a asynchronous failable constructor. See
2044 * g_dbus_connection_new_for_address_sync() for the synchronous
2050 g_dbus_connection_new_for_address (const gchar *address,
2051 GDBusConnectionFlags flags,
2052 GCancellable *cancellable,
2053 GAsyncReadyCallback callback,
2056 g_return_if_fail (address != NULL);
2057 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2068 * g_dbus_connection_new_for_address_finish:
2069 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2070 * @error: Return location for error or %NULL.
2072 * Finishes an operation started with g_dbus_connection_new_for_address().
2074 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2079 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2083 GObject *source_object;
2085 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2086 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2088 source_object = g_async_result_get_source_object (res);
2089 g_assert (source_object != NULL);
2090 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2093 g_object_unref (source_object);
2095 return G_DBUS_CONNECTION (object);
2101 * g_dbus_connection_new_for_address_sync:
2102 * @address: A D-Bus address.
2103 * @flags: Flags describing how to make the connection.
2104 * @cancellable: A #GCancellable or %NULL.
2105 * @error: Return location for error or %NULL.
2107 * Synchronously connects and sets up a D-Bus client connection for
2108 * exchanging D-Bus messages with an endpoint specified by @address
2109 * which must be in the D-Bus address format.
2111 * This constructor can only be used to initiate client-side
2112 * connections - use g_dbus_connection_new_sync() if you need to act
2113 * as the server. In particular, @flags cannot contain the
2114 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2115 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2117 * This is a synchronous failable constructor. See
2118 * g_dbus_connection_new_for_address() for the asynchronous version.
2120 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2125 g_dbus_connection_new_for_address_sync (const gchar *address,
2126 GDBusConnectionFlags flags,
2127 GCancellable *cancellable,
2130 g_return_val_if_fail (address != NULL, NULL);
2131 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2132 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2140 /* ---------------------------------------------------------------------------------------------------- */
2143 * g_dbus_connection_set_exit_on_close:
2144 * @connection: A #GDBusConnection.
2145 * @exit_on_close: Whether the process should be terminated
2146 * when @connection is closed by the remote peer.
2148 * Sets whether the process should be terminated when @connection is
2149 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2155 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2156 gboolean exit_on_close)
2158 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2159 connection->priv->exit_on_close = exit_on_close;
2163 * g_dbus_connection_get_exit_on_close:
2164 * @connection: A #GDBusConnection.
2166 * Gets whether the process is terminated when @connection is
2167 * closed by the remote peer. See
2168 * #GDBusConnection:exit-on-close for more details.
2170 * Returns: Whether the process is terminated when @connection is
2171 * closed by the remote peer.
2176 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2178 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2179 return connection->priv->exit_on_close;
2183 * g_dbus_connection_get_guid:
2184 * @connection: A #GDBusConnection.
2186 * The GUID of the peer performing the role of server when
2187 * authenticating. See #GDBusConnection:guid for more details.
2189 * Returns: The GUID. Do not free this string, it is owned by
2195 g_dbus_connection_get_guid (GDBusConnection *connection)
2197 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2198 return connection->priv->guid;
2202 * g_dbus_connection_get_unique_name:
2203 * @connection: A #GDBusConnection.
2205 * Gets the unique name of @connection as assigned by the message
2206 * bus. This can also be used to figure out if @connection is a
2207 * message bus connection.
2209 * Returns: The unique name or %NULL if @connection is not a message
2210 * bus connection. Do not free this string, it is owned by
2216 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2218 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2219 return connection->priv->bus_unique_name;
2223 * g_dbus_connection_get_peer_credentials:
2224 * @connection: A #GDBusConnection.
2226 * Gets the credentials of the authenticated peer. This will always
2227 * return %NULL unless @connection acted as a server
2228 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2229 * when set up and the client passed credentials as part of the
2230 * authentication process.
2232 * In a message bus setup, the message bus is always the server and
2233 * each application is a client. So this method will always return
2234 * %NULL for message bus clients.
2236 * Returns: A #GCredentials or %NULL if not available. Do not free
2237 * this object, it is owned by @connection.
2242 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2244 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2245 return connection->priv->crendentials;
2248 /* ---------------------------------------------------------------------------------------------------- */
2250 static guint _global_filter_id = 1;
2253 * g_dbus_connection_add_filter:
2254 * @connection: A #GDBusConnection.
2255 * @filter_function: A filter function.
2256 * @user_data: User data to pass to @filter_function.
2257 * @user_data_free_func: Function to free @user_data with when filter
2258 * is removed or %NULL.
2260 * Adds a message filter. Filters are handlers that are run on all
2261 * incoming messages, prior to standard dispatch. Filters are run in
2262 * the order that they were added. The same handler can be added as a
2263 * filter more than once, in which case it will be run more than once.
2264 * Filters added during a filter callback won't be run on the message
2267 * Note that filters are run in a dedicated message handling thread so
2268 * they can't block and, generally, can't do anything but signal a
2269 * worker thread. Also note that filters are rarely needed - use API
2270 * such as g_dbus_connection_send_message_with_reply(),
2271 * g_dbus_connection_signal_subscribe() or
2272 * g_dbus_connection_invoke_method() instead.
2274 * Returns: A filter identifier that can be used with
2275 * g_dbus_connection_remove_filter().
2280 g_dbus_connection_add_filter (GDBusConnection *connection,
2281 GDBusMessageFilterFunction filter_function,
2283 GDestroyNotify user_data_free_func)
2287 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2288 g_return_val_if_fail (filter_function != NULL, 0);
2290 CONNECTION_LOCK (connection);
2291 data = g_new0 (FilterData, 1);
2292 data->id = _global_filter_id++; /* TODO: overflow etc. */
2293 data->filter_function = filter_function;
2294 data->user_data = user_data;
2295 data->user_data_free_func = user_data_free_func;
2296 g_ptr_array_add (connection->priv->filters, data);
2297 CONNECTION_UNLOCK (connection);
2302 /* only called from finalize(), removes all filters */
2304 purge_all_filters (GDBusConnection *connection)
2307 for (n = 0; n < connection->priv->filters->len; n++)
2309 FilterData *data = connection->priv->filters->pdata[n];
2310 if (data->user_data_free_func != NULL)
2311 data->user_data_free_func (data->user_data);
2317 g_dbus_connection_remove_filter (GDBusConnection *connection,
2321 FilterData *to_destroy;
2323 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2325 CONNECTION_LOCK (connection);
2327 for (n = 0; n < connection->priv->filters->len; n++)
2329 FilterData *data = connection->priv->filters->pdata[n];
2330 if (data->id == filter_id)
2332 g_ptr_array_remove_index (connection->priv->filters, n);
2337 CONNECTION_UNLOCK (connection);
2339 /* do free without holding lock */
2340 if (to_destroy != NULL)
2342 if (to_destroy->user_data_free_func != NULL)
2343 to_destroy->user_data_free_func (to_destroy->user_data);
2344 g_free (to_destroy);
2348 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2352 /* ---------------------------------------------------------------------------------------------------- */
2358 gchar *interface_name;
2362 GArray *subscribers;
2367 GDBusSignalCallback callback;
2369 GDestroyNotify user_data_free_func;
2371 GMainContext *context;
2375 signal_data_free (SignalData *data)
2377 g_free (data->rule);
2378 g_free (data->sender);
2379 g_free (data->interface_name);
2380 g_free (data->member);
2381 g_free (data->object_path);
2382 g_free (data->arg0);
2383 g_array_free (data->subscribers, TRUE);
2388 args_to_rule (const gchar *sender,
2389 const gchar *interface_name,
2390 const gchar *member,
2391 const gchar *object_path,
2396 rule = g_string_new ("type='signal'");
2398 g_string_append_printf (rule, ",sender='%s'", sender);
2399 if (interface_name != NULL)
2400 g_string_append_printf (rule, ",interface='%s'", interface_name);
2402 g_string_append_printf (rule, ",member='%s'", member);
2403 if (object_path != NULL)
2404 g_string_append_printf (rule, ",path='%s'", object_path);
2406 g_string_append_printf (rule, ",arg0='%s'", arg0);
2408 return g_string_free (rule, FALSE);
2411 static guint _global_subscriber_id = 1;
2412 static guint _global_registration_id = 1;
2413 static guint _global_subtree_registration_id = 1;
2415 /* ---------------------------------------------------------------------------------------------------- */
2417 /* must hold lock when calling */
2419 add_match_rule (GDBusConnection *connection,
2420 const gchar *match_rule)
2423 GDBusMessage *message;
2425 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2426 "/org/freedesktop/DBus", /* path */
2427 "org.freedesktop.DBus", /* interface */
2429 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2432 if (!g_dbus_connection_send_message_unlocked (connection,
2437 g_critical ("Error while sending AddMatch() message: %s", error->message);
2438 g_error_free (error);
2440 g_object_unref (message);
2443 /* ---------------------------------------------------------------------------------------------------- */
2445 /* must hold lock when calling */
2447 remove_match_rule (GDBusConnection *connection,
2448 const gchar *match_rule)
2451 GDBusMessage *message;
2453 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2454 "/org/freedesktop/DBus", /* path */
2455 "org.freedesktop.DBus", /* interface */
2457 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2460 if (!g_dbus_connection_send_message_unlocked (connection,
2465 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2466 g_error_free (error);
2468 g_object_unref (message);
2471 /* ---------------------------------------------------------------------------------------------------- */
2474 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2476 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2477 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2478 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2479 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2480 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2483 /* ---------------------------------------------------------------------------------------------------- */
2486 * g_dbus_connection_signal_subscribe:
2487 * @connection: A #GDBusConnection.
2488 * @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.
2489 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2490 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2491 * @object_path: Object path to match on or %NULL to match on all object paths.
2492 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2493 * @callback: Callback to invoke when there is a signal matching the requested data.
2494 * @user_data: User data to pass to @callback.
2495 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2497 * Subscribes to signals on @connection and invokes @callback with a
2498 * whenever the signal is received. Note that @callback
2499 * will be invoked in the <link
2500 * linkend="g-main-context-push-thread-default">thread-default main
2501 * loop</link> of the thread you are calling this method from.
2503 * It is considered a programming error to use this function if @connection is closed.
2505 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2506 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2507 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2508 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2509 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2510 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2512 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2517 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2518 const gchar *sender,
2519 const gchar *interface_name,
2520 const gchar *member,
2521 const gchar *object_path,
2523 GDBusSignalCallback callback,
2525 GDestroyNotify user_data_free_func)
2528 SignalData *signal_data;
2529 SignalSubscriber subscriber;
2530 GPtrArray *signal_data_array;
2532 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2533 * an OOM condition. We might want to change that but that would involve making
2534 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2535 * handle that. And there's really no sensible way of handling this short of retrying
2536 * to add the match rule... and then there's the little thing that, hey, maybe there's
2537 * a reason the bus in an OOM condition.
2539 * Doable, but not really sure it's worth it...
2542 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2543 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2544 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2545 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2546 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2547 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2548 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2549 g_return_val_if_fail (callback != NULL, 0);
2551 CONNECTION_LOCK (connection);
2553 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2558 subscriber.callback = callback;
2559 subscriber.user_data = user_data;
2560 subscriber.user_data_free_func = user_data_free_func;
2561 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2562 subscriber.context = g_main_context_get_thread_default ();
2563 if (subscriber.context != NULL)
2564 g_main_context_ref (subscriber.context);
2566 /* see if we've already have this rule */
2567 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2568 if (signal_data != NULL)
2570 g_array_append_val (signal_data->subscribers, subscriber);
2575 signal_data = g_new0 (SignalData, 1);
2576 signal_data->rule = rule;
2577 signal_data->sender = g_strdup (sender);
2578 signal_data->interface_name = g_strdup (interface_name);
2579 signal_data->member = g_strdup (member);
2580 signal_data->object_path = g_strdup (object_path);
2581 signal_data->arg0 = g_strdup (arg0);
2582 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2583 g_array_append_val (signal_data->subscribers, subscriber);
2585 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2589 /* Add the match rule to the bus...
2591 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2592 * always send such messages to to us.
2594 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2596 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2598 add_match_rule (connection, signal_data->rule);
2603 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2604 GUINT_TO_POINTER (subscriber.id),
2607 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2608 signal_data->sender);
2609 if (signal_data_array == NULL)
2611 signal_data_array = g_ptr_array_new ();
2612 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2613 g_strdup (signal_data->sender),
2616 g_ptr_array_add (signal_data_array, signal_data);
2618 CONNECTION_UNLOCK (connection);
2620 return subscriber.id;
2623 /* ---------------------------------------------------------------------------------------------------- */
2625 /* must hold lock when calling this */
2627 unsubscribe_id_internal (GDBusConnection *connection,
2628 guint subscription_id,
2629 GArray *out_removed_subscribers)
2631 SignalData *signal_data;
2632 GPtrArray *signal_data_array;
2635 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2636 GUINT_TO_POINTER (subscription_id));
2637 if (signal_data == NULL)
2639 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2643 for (n = 0; n < signal_data->subscribers->len; n++)
2645 SignalSubscriber *subscriber;
2647 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2648 if (subscriber->id != subscription_id)
2651 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2652 GUINT_TO_POINTER (subscription_id)));
2653 g_array_append_val (out_removed_subscribers, *subscriber);
2654 g_array_remove_index (signal_data->subscribers, n);
2656 if (signal_data->subscribers->len == 0)
2657 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2659 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2660 signal_data->sender);
2661 g_warn_if_fail (signal_data_array != NULL);
2662 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2664 if (signal_data_array->len == 0)
2666 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2668 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2669 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2671 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2673 remove_match_rule (connection, signal_data->rule);
2677 signal_data_free (signal_data);
2683 g_assert_not_reached ();
2690 * g_dbus_connection_signal_unsubscribe:
2691 * @connection: A #GDBusConnection.
2692 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2694 * Unsubscribes from signals.
2699 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2700 guint subscription_id)
2702 GArray *subscribers;
2705 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2707 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2709 CONNECTION_LOCK (connection);
2710 unsubscribe_id_internal (connection,
2713 CONNECTION_UNLOCK (connection);
2716 g_assert (subscribers->len == 0 || subscribers->len == 1);
2718 /* call GDestroyNotify without lock held */
2719 for (n = 0; n < subscribers->len; n++)
2721 SignalSubscriber *subscriber;
2722 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2723 if (subscriber->user_data_free_func != NULL)
2724 subscriber->user_data_free_func (subscriber->user_data);
2725 if (subscriber->context != NULL)
2726 g_main_context_unref (subscriber->context);
2729 g_array_free (subscribers, TRUE);
2732 /* ---------------------------------------------------------------------------------------------------- */
2736 guint subscription_id;
2737 GDBusSignalCallback callback;
2739 GDBusMessage *message;
2740 GDBusConnection *connection;
2741 const gchar *sender;
2743 const gchar *interface;
2744 const gchar *member;
2747 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2751 emit_signal_instance_in_idle_cb (gpointer data)
2753 SignalInstance *signal_instance = data;
2754 GVariant *parameters;
2755 gboolean has_subscription;
2757 parameters = g_dbus_message_get_body (signal_instance->message);
2758 if (parameters == NULL)
2760 parameters = g_variant_new ("()");
2761 g_variant_ref_sink (parameters);
2765 g_variant_ref_sink (parameters);
2769 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2770 signal_instance->sender,
2771 signal_instance->path,
2772 signal_instance->interface,
2773 signal_instance->member,
2774 g_variant_print (parameters, TRUE));
2777 /* Careful here, don't do the callback if we no longer has the subscription */
2778 CONNECTION_LOCK (signal_instance->connection);
2779 has_subscription = FALSE;
2780 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2781 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2782 has_subscription = TRUE;
2783 CONNECTION_UNLOCK (signal_instance->connection);
2785 if (has_subscription)
2787 signal_instance->callback (signal_instance->connection,
2788 signal_instance->sender,
2789 signal_instance->path,
2790 signal_instance->interface,
2791 signal_instance->member,
2793 signal_instance->user_data);
2795 if (parameters != NULL)
2796 g_variant_unref (parameters);
2802 signal_instance_free (SignalInstance *signal_instance)
2804 g_object_unref (signal_instance->message);
2805 g_object_unref (signal_instance->connection);
2806 g_free (signal_instance);
2809 /* called in message handler thread WITH lock held */
2811 schedule_callbacks (GDBusConnection *connection,
2812 GPtrArray *signal_data_array,
2813 GDBusMessage *message,
2814 const gchar *sender)
2817 const gchar *interface;
2818 const gchar *member;
2827 interface = g_dbus_message_get_interface (message);
2828 member = g_dbus_message_get_member (message);
2829 path = g_dbus_message_get_path (message);
2830 arg0 = g_dbus_message_get_arg0 (message);
2833 g_debug ("sender = `%s'", sender);
2834 g_debug ("interface = `%s'", interface);
2835 g_debug ("member = `%s'", member);
2836 g_debug ("path = `%s'", path);
2837 g_debug ("arg0 = `%s'", arg0);
2840 /* TODO: if this is slow, then we can change signal_data_array into
2841 * map_object_path_to_signal_data_array or something.
2843 for (n = 0; n < signal_data_array->len; n++)
2845 SignalData *signal_data = signal_data_array->pdata[n];
2847 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2850 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2853 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2856 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2859 for (m = 0; m < signal_data->subscribers->len; m++)
2861 SignalSubscriber *subscriber;
2862 GSource *idle_source;
2863 SignalInstance *signal_instance;
2865 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2867 signal_instance = g_new0 (SignalInstance, 1);
2868 signal_instance->subscription_id = subscriber->id;
2869 signal_instance->callback = subscriber->callback;
2870 signal_instance->user_data = subscriber->user_data;
2871 signal_instance->message = g_object_ref (message);
2872 signal_instance->connection = g_object_ref (connection);
2873 signal_instance->sender = sender;
2874 signal_instance->path = path;
2875 signal_instance->interface = interface;
2876 signal_instance->member = member;
2878 idle_source = g_idle_source_new ();
2879 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2880 g_source_set_callback (idle_source,
2881 emit_signal_instance_in_idle_cb,
2883 (GDestroyNotify) signal_instance_free);
2884 g_source_attach (idle_source, subscriber->context);
2885 g_source_unref (idle_source);
2890 /* called in message handler thread with lock held */
2892 distribute_signals (GDBusConnection *connection,
2893 GDBusMessage *message)
2895 GPtrArray *signal_data_array;
2896 const gchar *sender;
2898 sender = g_dbus_message_get_sender (message);
2900 /* collect subcsribers that match on sender */
2903 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2904 if (signal_data_array != NULL) {
2905 schedule_callbacks (connection, signal_data_array, message, sender);
2909 /* collect subcsribers not matching on sender */
2910 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2911 if (signal_data_array != NULL)
2913 schedule_callbacks (connection, signal_data_array, message, sender);
2917 /* ---------------------------------------------------------------------------------------------------- */
2919 /* only called from finalize(), removes all subscriptions */
2921 purge_all_signal_subscriptions (GDBusConnection *connection)
2923 GHashTableIter iter;
2926 GArray *subscribers;
2929 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2930 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2931 while (g_hash_table_iter_next (&iter, &key, NULL))
2933 guint subscription_id = GPOINTER_TO_UINT (key);
2934 g_array_append_val (ids, subscription_id);
2937 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2938 for (n = 0; n < ids->len; n++)
2940 guint subscription_id = g_array_index (ids, guint, n);
2941 unsubscribe_id_internal (connection,
2945 g_array_free (ids, TRUE);
2947 /* call GDestroyNotify without lock held */
2948 for (n = 0; n < subscribers->len; n++)
2950 SignalSubscriber *subscriber;
2951 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2952 if (subscriber->user_data_free_func != NULL)
2953 subscriber->user_data_free_func (subscriber->user_data);
2954 if (subscriber->context != NULL)
2955 g_main_context_unref (subscriber->context);
2958 g_array_free (subscribers, TRUE);
2961 /* ---------------------------------------------------------------------------------------------------- */
2963 struct ExportedObject
2966 GDBusConnection *connection;
2968 /* maps gchar* -> ExportedInterface* */
2969 GHashTable *map_if_name_to_ei;
2972 /* only called with lock held */
2974 exported_object_free (ExportedObject *eo)
2976 g_free (eo->object_path);
2977 g_hash_table_unref (eo->map_if_name_to_ei);
2986 gchar *interface_name;
2987 const GDBusInterfaceVTable *vtable;
2988 const GDBusInterfaceInfo *introspection_data;
2990 GMainContext *context;
2992 GDestroyNotify user_data_free_func;
2993 } ExportedInterface;
2995 /* called with lock held */
2997 exported_interface_free (ExportedInterface *ei)
2999 if (ei->user_data_free_func != NULL)
3001 /* TODO: push to thread-default mainloop */
3002 ei->user_data_free_func (ei->user_data);
3004 if (ei->context != NULL)
3006 g_main_context_unref (ei->context);
3008 g_free (ei->interface_name);
3012 /* ---------------------------------------------------------------------------------------------------- */
3016 GDBusConnection *connection;
3017 GDBusMessage *message;
3019 const char *property_name;
3020 const GDBusInterfaceVTable *vtable;
3021 const GDBusInterfaceInfo *interface_info;
3022 const GDBusPropertyInfo *property_info;
3026 property_data_free (PropertyData *data)
3028 g_object_unref (data->connection);
3029 g_object_unref (data->message);
3033 /* called in thread where object was registered - no locks held */
3035 invoke_get_property_in_idle_cb (gpointer _data)
3037 PropertyData *data = _data;
3040 GDBusMessage *reply;
3043 value = data->vtable->get_property (data->connection,
3044 g_dbus_message_get_sender (data->message),
3045 g_dbus_message_get_path (data->message),
3046 data->interface_info->name,
3047 data->property_name,
3054 g_assert_no_error (error);
3056 g_variant_ref_sink (value);
3057 reply = g_dbus_message_new_method_reply (data->message);
3058 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3059 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3060 g_variant_unref (value);
3061 g_object_unref (reply);
3065 gchar *dbus_error_name;
3067 g_assert (error != NULL);
3069 dbus_error_name = g_dbus_error_encode_gerror (error);
3070 reply = g_dbus_message_new_method_error_literal (data->message,
3073 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3074 g_free (dbus_error_name);
3075 g_error_free (error);
3076 g_object_unref (reply);
3082 /* called in thread where object was registered - no locks held */
3084 invoke_set_property_in_idle_cb (gpointer _data)
3086 PropertyData *data = _data;
3088 GDBusMessage *reply;
3094 g_variant_get (g_dbus_message_get_body (data->message),
3100 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3101 * of the given value is wrong
3103 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3105 reply = g_dbus_message_new_method_error (data->message,
3106 "org.freedesktop.DBus.Error.InvalidArgs",
3107 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3108 data->property_info->name,
3109 data->property_info->signature,
3110 g_variant_get_type_string (value));
3114 if (!data->vtable->set_property (data->connection,
3115 g_dbus_message_get_sender (data->message),
3116 g_dbus_message_get_path (data->message),
3117 data->interface_info->name,
3118 data->property_name,
3123 gchar *dbus_error_name;
3124 g_assert (error != NULL);
3125 dbus_error_name = g_dbus_error_encode_gerror (error);
3126 reply = g_dbus_message_new_method_error_literal (data->message,
3129 g_free (dbus_error_name);
3130 g_error_free (error);
3134 reply = g_dbus_message_new_method_reply (data->message);
3138 g_assert (reply != NULL);
3139 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3140 g_object_unref (reply);
3145 /* called with lock held */
3147 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3148 GDBusMessage *message,
3150 const GDBusInterfaceInfo *introspection_data,
3151 const GDBusInterfaceVTable *vtable,
3152 GMainContext *main_context,
3156 const char *interface_name;
3157 const char *property_name;
3158 const GDBusPropertyInfo *property_info;
3159 GSource *idle_source;
3160 PropertyData *property_data;
3161 GDBusMessage *reply;
3166 g_variant_get (g_dbus_message_get_body (message),
3171 g_variant_get (g_dbus_message_get_body (message),
3180 if (vtable == NULL || vtable->get_property == NULL)
3185 if (vtable == NULL || vtable->set_property == NULL)
3189 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3191 property_info = NULL;
3193 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3194 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3195 if (property_info == NULL)
3197 reply = g_dbus_message_new_method_error (message,
3198 "org.freedesktop.DBus.Error.InvalidArgs",
3199 _("No such property `%s'"),
3201 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3202 g_object_unref (reply);
3207 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3209 reply = g_dbus_message_new_method_error (message,
3210 "org.freedesktop.DBus.Error.InvalidArgs",
3211 _("Property `%s' is not readable"),
3213 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3214 g_object_unref (reply);
3218 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3220 reply = g_dbus_message_new_method_error (message,
3221 "org.freedesktop.DBus.Error.InvalidArgs",
3222 _("Property `%s' is not writable"),
3224 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3225 g_object_unref (reply);
3230 /* ok, got the property info - call user code in an idle handler */
3231 property_data = g_new0 (PropertyData, 1);
3232 property_data->connection = g_object_ref (connection);
3233 property_data->message = g_object_ref (message);
3234 property_data->user_data = user_data;
3235 property_data->property_name = property_name;
3236 property_data->vtable = vtable;
3237 property_data->interface_info = introspection_data;
3238 property_data->property_info = property_info;
3240 idle_source = g_idle_source_new ();
3241 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3242 g_source_set_callback (idle_source,
3243 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3245 (GDestroyNotify) property_data_free);
3246 g_source_attach (idle_source, main_context);
3247 g_source_unref (idle_source);
3255 /* called with lock held */
3257 handle_getset_property (GDBusConnection *connection,
3259 GDBusMessage *message,
3262 ExportedInterface *ei;
3264 const char *interface_name;
3265 const char *property_name;
3270 g_variant_get (g_dbus_message_get_body (message),
3275 g_variant_get (g_dbus_message_get_body (message),
3281 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3282 * no such interface registered
3284 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3287 GDBusMessage *reply;
3288 reply = g_dbus_message_new_method_error (message,
3289 "org.freedesktop.DBus.Error.InvalidArgs",
3290 _("No such interface `%s'"),
3292 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3293 g_object_unref (reply);
3298 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3301 ei->introspection_data,
3309 /* ---------------------------------------------------------------------------------------------------- */
3313 GDBusConnection *connection;
3314 GDBusMessage *message;
3316 const GDBusInterfaceVTable *vtable;
3317 const GDBusInterfaceInfo *interface_info;
3318 } PropertyGetAllData;
3321 property_get_all_data_free (PropertyData *data)
3323 g_object_unref (data->connection);
3324 g_object_unref (data->message);
3328 /* called in thread where object was registered - no locks held */
3330 invoke_get_all_properties_in_idle_cb (gpointer _data)
3332 PropertyGetAllData *data = _data;
3333 GVariantBuilder *builder;
3337 GDBusMessage *reply;
3342 /* TODO: Right now we never fail this call - we just omit values if
3343 * a get_property() call is failing.
3345 * We could fail the whole call if just a single get_property() call
3346 * returns an error. We need clarification in the D-Bus spec about this.
3348 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3349 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3351 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3354 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3357 value = data->vtable->get_property (data->connection,
3358 g_dbus_message_get_sender (data->message),
3359 g_dbus_message_get_path (data->message),
3360 data->interface_info->name,
3361 property_info->name,
3368 g_variant_ref_sink (value);
3369 g_variant_builder_add (builder,
3371 property_info->name,
3373 g_variant_unref (value);
3375 result = g_variant_builder_end (builder);
3377 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3378 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3379 packed = g_variant_builder_end (builder);
3381 reply = g_dbus_message_new_method_reply (data->message);
3382 g_dbus_message_set_body (reply, packed);
3383 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3384 g_object_unref (reply);
3389 /* called with lock held */
3391 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3392 GDBusMessage *message,
3393 const GDBusInterfaceInfo *introspection_data,
3394 const GDBusInterfaceVTable *vtable,
3395 GMainContext *main_context,
3399 const char *interface_name;
3400 GSource *idle_source;
3401 PropertyGetAllData *property_get_all_data;
3405 g_variant_get (g_dbus_message_get_body (message),
3409 if (vtable == NULL || vtable->get_property == NULL)
3412 /* ok, got the property info - call user in an idle handler */
3413 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3414 property_get_all_data->connection = g_object_ref (connection);
3415 property_get_all_data->message = g_object_ref (message);
3416 property_get_all_data->user_data = user_data;
3417 property_get_all_data->vtable = vtable;
3418 property_get_all_data->interface_info = introspection_data;
3420 idle_source = g_idle_source_new ();
3421 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3422 g_source_set_callback (idle_source,
3423 invoke_get_all_properties_in_idle_cb,
3424 property_get_all_data,
3425 (GDestroyNotify) property_get_all_data_free);
3426 g_source_attach (idle_source, main_context);
3427 g_source_unref (idle_source);
3435 /* called with lock held */
3437 handle_get_all_properties (GDBusConnection *connection,
3439 GDBusMessage *message)
3441 ExportedInterface *ei;
3443 const char *interface_name;
3447 g_variant_get (g_dbus_message_get_body (message),
3451 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3452 * no such interface registered
3454 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3457 GDBusMessage *reply;
3458 reply = g_dbus_message_new_method_error (message,
3459 "org.freedesktop.DBus.Error.InvalidArgs",
3460 _("No such interface"),
3462 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3463 g_object_unref (reply);
3468 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3470 ei->introspection_data,
3478 /* ---------------------------------------------------------------------------------------------------- */
3480 static const gchar introspect_header[] =
3481 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3482 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3483 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3486 static const gchar introspect_tail[] =
3489 static const gchar introspect_standard_interfaces[] =
3490 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3491 " <method name=\"Get\">\n"
3492 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3493 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3494 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3496 " <method name=\"GetAll\">\n"
3497 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3498 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3500 " <method name=\"Set\">\n"
3501 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3502 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3503 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3505 " <signal name=\"PropertiesChanged\">\n"
3506 " <arg type=\"s\" name=\"interface_name\"/>\n"
3507 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3510 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3511 " <method name=\"Introspect\">\n"
3512 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3515 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3516 " <method name=\"Ping\"/>\n"
3517 " <method name=\"GetMachineId\">\n"
3518 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3523 introspect_append_header (GString *s)
3525 g_string_append (s, introspect_header);
3529 introspect_append_standard_interfaces (GString *s)
3531 g_string_append (s, introspect_standard_interfaces);
3535 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3537 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3543 begin = object_path + path_len;
3544 end = strchr (begin, '/');
3548 s = g_strndup (begin, end - begin);
3552 s = g_strdup (begin);
3555 if (g_hash_table_lookup (set, s) == NULL)
3557 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3566 /* TODO: we want a nicer public interface for this */
3568 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3573 GHashTableIter hash_iter;
3574 const gchar *object_path;
3580 CONNECTION_ENSURE_LOCK (connection);
3582 path_len = strlen (path);
3586 set = g_hash_table_new (g_str_hash, g_str_equal);
3588 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3589 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3590 maybe_add_path (path, path_len, object_path, set);
3592 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3593 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3594 maybe_add_path (path, path_len, object_path, set);
3596 p = g_ptr_array_new ();
3597 keys = g_hash_table_get_keys (set);
3598 for (l = keys; l != NULL; l = l->next)
3600 g_ptr_array_add (p, l->data);
3602 g_hash_table_unref (set);
3605 g_ptr_array_add (p, NULL);
3606 ret = (gchar **) g_ptr_array_free (p, FALSE);
3611 g_dbus_connection_list_registered (GDBusConnection *connection,
3615 CONNECTION_LOCK (connection);
3616 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3617 CONNECTION_UNLOCK (connection);
3621 /* called in message handler thread with lock held */
3623 handle_introspect (GDBusConnection *connection,
3625 GDBusMessage *message)
3629 GDBusMessage *reply;
3630 GHashTableIter hash_iter;
3631 ExportedInterface *ei;
3634 /* first the header with the standard interfaces */
3635 s = g_string_sized_new (sizeof (introspect_header) +
3636 sizeof (introspect_standard_interfaces) +
3637 sizeof (introspect_tail));
3638 introspect_append_header (s);
3639 introspect_append_standard_interfaces (s);
3641 /* then include the registered interfaces */
3642 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3643 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3645 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3648 /* finally include nodes registered below us */
3649 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3650 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3652 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3654 g_strfreev (registered);
3655 g_string_append (s, introspect_tail);
3657 reply = g_dbus_message_new_method_reply (message);
3658 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3659 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3660 g_object_unref (reply);
3661 g_string_free (s, TRUE);
3666 /* called in thread where object was registered - no locks held */
3668 invoke_method_in_idle_cb (gpointer user_data)
3670 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3671 GDBusInterfaceVTable *vtable;
3673 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3674 g_assert (vtable != NULL && vtable->method_call != NULL);
3676 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3677 g_dbus_method_invocation_get_sender (invocation),
3678 g_dbus_method_invocation_get_object_path (invocation),
3679 g_dbus_method_invocation_get_interface_name (invocation),
3680 g_dbus_method_invocation_get_method_name (invocation),
3681 g_dbus_method_invocation_get_parameters (invocation),
3682 g_object_ref (invocation),
3683 g_dbus_method_invocation_get_user_data (invocation));
3688 /* called in message handler thread with lock held */
3690 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3691 GDBusMessage *message,
3692 const GDBusInterfaceInfo *introspection_data,
3693 const GDBusInterfaceVTable *vtable,
3694 GMainContext *main_context,
3697 GDBusMethodInvocation *invocation;
3698 const GDBusMethodInfo *method_info;
3699 GDBusMessage *reply;
3700 GVariant *parameters;
3701 GSource *idle_source;
3703 gchar *in_signature;
3707 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3708 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3710 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3711 * error to the caller
3713 if (method_info == NULL)
3715 reply = g_dbus_message_new_method_error (message,
3716 "org.freedesktop.DBus.Error.UnknownMethod",
3717 _("No such method `%s'"),
3718 g_dbus_message_get_member (message));
3719 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3720 g_object_unref (reply);
3725 /* Check that the incoming args are of the right type - if they are not, return
3726 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3728 * TODO: might also be worth caching the combined signature.
3730 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3731 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3733 reply = g_dbus_message_new_method_error (message,
3734 "org.freedesktop.DBus.Error.InvalidArgs",
3735 _("Signature of message, `%s', does not match expected signature `%s'"),
3736 g_dbus_message_get_signature (message),
3738 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3739 g_object_unref (reply);
3740 g_free (in_signature);
3744 g_free (in_signature);
3746 parameters = g_dbus_message_get_body (message);
3747 if (parameters == NULL)
3749 parameters = g_variant_new ("()");
3750 g_variant_ref_sink (parameters);
3754 g_variant_ref (parameters);
3757 /* schedule the call in idle */
3758 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3759 g_dbus_message_get_path (message),
3760 g_dbus_message_get_interface (message),
3761 g_dbus_message_get_member (message),
3767 g_variant_unref (parameters);
3768 g_object_set_data (G_OBJECT (invocation),
3769 "g-dbus-interface-vtable",
3772 idle_source = g_idle_source_new ();
3773 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3774 g_source_set_callback (idle_source,
3775 invoke_method_in_idle_cb,
3778 g_source_attach (idle_source, main_context);
3779 g_source_unref (idle_source);
3788 /* ---------------------------------------------------------------------------------------------------- */
3790 /* called in message handler thread with lock held */
3792 obj_message_func (GDBusConnection *connection,
3794 GDBusMessage *message)
3796 const gchar *interface_name;
3797 const gchar *member;
3798 const gchar *signature;
3803 interface_name = g_dbus_message_get_interface (message);
3804 member = g_dbus_message_get_member (message);
3805 signature = g_dbus_message_get_signature (message);
3807 /* see if we have an interface for handling this call */
3808 if (interface_name != NULL)
3810 ExportedInterface *ei;
3811 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3814 /* we do - invoke the handler in idle in the right thread */
3816 /* handle no vtable or handler being present */
3817 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3820 handled = validate_and_maybe_schedule_method_call (connection,
3822 ei->introspection_data,
3830 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3831 g_strcmp0 (member, "Introspect") == 0 &&
3832 g_strcmp0 (signature, "") == 0)
3834 handled = handle_introspect (connection, eo, message);
3837 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3838 g_strcmp0 (member, "Get") == 0 &&
3839 g_strcmp0 (signature, "ss") == 0)
3841 handled = handle_getset_property (connection, eo, message, TRUE);
3844 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3845 g_strcmp0 (member, "Set") == 0 &&
3846 g_strcmp0 (signature, "ssv") == 0)
3848 handled = handle_getset_property (connection, eo, message, FALSE);
3851 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3852 g_strcmp0 (member, "GetAll") == 0 &&
3853 g_strcmp0 (signature, "s") == 0)
3855 handled = handle_get_all_properties (connection, eo, message);
3864 * g_dbus_connection_register_object:
3865 * @connection: A #GDBusConnection.
3866 * @object_path: The object path to register at.
3867 * @interface_name: The D-Bus interface to register.
3868 * @introspection_data: Introspection data for the interface.
3869 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3870 * @user_data: Data to pass to functions in @vtable.
3871 * @user_data_free_func: Function to call when the object path is unregistered.
3872 * @error: Return location for error or %NULL.
3874 * Registers callbacks for exported objects at @object_path with the
3875 * D-Bus interface @interface_name.
3877 * Calls to functions in @vtable (and @user_data_free_func) will
3878 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3879 * loop</link> of the thread you are calling this method from.
3881 * Note that all #GVariant values passed to functions in @vtable will match
3882 * the signature given in @introspection_data - if a remote caller passes
3883 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3884 * is returned to the remote caller.
3886 * Additionally, if the remote caller attempts to invoke methods or
3887 * access properties not mentioned in @introspection_data the
3888 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3889 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3890 * are returned to the caller.
3892 * It is considered a programming error if the
3893 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3894 * #GVariant of incorrect type.
3896 * If an existing callback is already registered at @object_path and
3897 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3899 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3901 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3902 * that can be used with g_dbus_connection_unregister_object() .
3907 g_dbus_connection_register_object (GDBusConnection *connection,
3908 const gchar *object_path,
3909 const gchar *interface_name,
3910 const GDBusInterfaceInfo *introspection_data,
3911 const GDBusInterfaceVTable *vtable,
3913 GDestroyNotify user_data_free_func,
3917 ExportedInterface *ei;
3920 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3921 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3922 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3923 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3924 g_return_val_if_fail (introspection_data != NULL, 0);
3925 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3929 CONNECTION_LOCK (connection);
3931 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3934 eo = g_new0 (ExportedObject, 1);
3935 eo->object_path = g_strdup (object_path);
3936 eo->connection = connection;
3937 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3940 (GDestroyNotify) exported_interface_free);
3941 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3944 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3950 _("An object is already exported for the interface %s at %s"),
3956 ei = g_new0 (ExportedInterface, 1);
3957 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3959 ei->user_data = user_data;
3960 ei->user_data_free_func = user_data_free_func;
3961 ei->vtable = vtable;
3962 ei->introspection_data = introspection_data;
3963 ei->interface_name = g_strdup (interface_name);
3964 ei->context = g_main_context_get_thread_default ();
3965 if (ei->context != NULL)
3966 g_main_context_ref (ei->context);
3968 g_hash_table_insert (eo->map_if_name_to_ei,
3969 (gpointer) ei->interface_name,
3971 g_hash_table_insert (connection->priv->map_id_to_ei,
3972 GUINT_TO_POINTER (ei->id),
3978 CONNECTION_UNLOCK (connection);
3984 * g_dbus_connection_unregister_object:
3985 * @connection: A #GDBusConnection.
3986 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3988 * Unregisters an object.
3990 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3995 g_dbus_connection_unregister_object (GDBusConnection *connection,
3996 guint registration_id)
3998 ExportedInterface *ei;
4002 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4006 CONNECTION_LOCK (connection);
4008 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4009 GUINT_TO_POINTER (registration_id));
4017 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4018 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4019 /* unregister object path if we have no more exported interfaces */
4020 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4022 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4029 CONNECTION_UNLOCK (connection);
4034 /* ---------------------------------------------------------------------------------------------------- */
4037 * g_dbus_connection_emit_signal:
4038 * @connection: A #GDBusConnection.
4039 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4040 * @object_path: Path of remote object.
4041 * @interface_name: D-Bus interface to emit a signal on.
4042 * @signal_name: The name of the signal to emit.
4043 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4044 * @error: Return location for error or %NULL.
4048 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4050 * Returns: %TRUE unless @error is set.
4055 g_dbus_connection_emit_signal (GDBusConnection *connection,
4056 const gchar *destination_bus_name,
4057 const gchar *object_path,
4058 const gchar *interface_name,
4059 const gchar *signal_name,
4060 GVariant *parameters,
4063 GDBusMessage *message;
4069 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4070 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4071 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4072 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4073 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4074 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4076 message = g_dbus_message_new_signal (object_path,
4080 if (destination_bus_name != NULL)
4082 g_dbus_message_set_header (message,
4083 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4084 g_variant_new_string (destination_bus_name));
4087 if (parameters != NULL)
4088 g_dbus_message_set_body (message, parameters);
4090 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4091 g_object_unref (message);
4097 add_invoke_method_flags (GDBusMessage *message,
4098 GDBusInvokeMethodFlags flags)
4100 if (flags & G_DBUS_INVOKE_METHOD_FLAGS_NO_AUTO_START)
4101 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4105 * g_dbus_connection_invoke_method:
4106 * @connection: A #GDBusConnection.
4107 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4108 * @object_path: Path of remote object.
4109 * @interface_name: D-Bus interface to invoke method on.
4110 * @method_name: The name of the method to invoke.
4111 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4112 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4113 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4114 * @cancellable: A #GCancellable or %NULL.
4115 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4116 * care about the result of the method invocation.
4117 * @user_data: The data to pass to @callback.
4119 * Asynchronously invokes the @method_name method on the
4120 * @interface_name D-Bus interface on the remote object at
4121 * @object_path owned by @bus_name.
4123 * If @connection is closed then the operation will fail with
4124 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4125 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4126 * not compatible with the D-Bus protocol, the operation fails with
4127 * %G_IO_ERROR_INVALID_ARGUMENT.
4129 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4130 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4131 * of the thread you are calling this method from. You can then call
4132 * g_dbus_connection_invoke_method_finish() to get the result of the operation.
4133 * See g_dbus_connection_invoke_method_sync() for the synchronous version of this
4139 g_dbus_connection_invoke_method (GDBusConnection *connection,
4140 const gchar *bus_name,
4141 const gchar *object_path,
4142 const gchar *interface_name,
4143 const gchar *method_name,
4144 GVariant *parameters,
4145 GDBusInvokeMethodFlags flags,
4147 GCancellable *cancellable,
4148 GAsyncReadyCallback callback,
4151 GDBusMessage *message;
4153 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4154 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4155 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4156 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4157 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4158 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4159 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4161 message = g_dbus_message_new_method_call (bus_name,
4165 add_invoke_method_flags (message, flags);
4166 if (parameters != NULL)
4167 g_dbus_message_set_body (message, parameters);
4169 g_dbus_connection_send_message_with_reply (connection,
4172 NULL, /* volatile guint32 *out_serial */
4177 if (message != NULL)
4178 g_object_unref (message);
4182 decode_method_reply (GDBusMessage *reply, GError **error)
4187 switch (g_dbus_message_get_message_type (reply))
4189 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4190 result = g_dbus_message_get_body (reply);
4193 result = g_variant_new ("()");
4194 g_variant_ref_sink (result);
4198 g_variant_ref (result);
4201 case G_DBUS_MESSAGE_TYPE_ERROR:
4202 g_dbus_message_to_gerror (reply, error);
4206 g_assert_not_reached ();
4214 * g_dbus_connection_invoke_method_finish:
4215 * @connection: A #GDBusConnection.
4216 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_invoke_method().
4217 * @error: Return location for error or %NULL.
4219 * Finishes an operation started with g_dbus_connection_invoke_method().
4221 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4222 * return values. Free with g_variant_unref().
4227 g_dbus_connection_invoke_method_finish (GDBusConnection *connection,
4231 GDBusMessage *reply;
4234 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4235 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4236 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4240 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4244 result = decode_method_reply (reply, error);
4246 g_object_unref (reply);
4252 /* ---------------------------------------------------------------------------------------------------- */
4255 * g_dbus_connection_invoke_method_sync:
4256 * @connection: A #GDBusConnection.
4257 * @bus_name: A unique or well-known bus name.
4258 * @object_path: Path of remote object.
4259 * @interface_name: D-Bus interface to invoke method on.
4260 * @method_name: The name of the method to invoke.
4261 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4262 * @flags: Flags from the #GDBusInvokeMethodFlags enumeration.
4263 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4264 * @cancellable: A #GCancellable or %NULL.
4265 * @error: Return location for error or %NULL.
4267 * Synchronously invokes the @method_name method on the
4268 * @interface_name D-Bus interface on the remote object at
4269 * @object_path owned by @bus_name.
4271 * If @connection is closed then the operation will fail with
4272 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4273 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4274 * contains a value not compatible with the D-Bus protocol, the operation
4275 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4277 * The calling thread is blocked until a reply is received. See
4278 * g_dbus_connection_invoke_method() for the asynchronous version of
4281 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4282 * return values. Free with g_variant_unref().
4287 g_dbus_connection_invoke_method_sync (GDBusConnection *connection,
4288 const gchar *bus_name,
4289 const gchar *object_path,
4290 const gchar *interface_name,
4291 const gchar *method_name,
4292 GVariant *parameters,
4293 GDBusInvokeMethodFlags flags,
4295 GCancellable *cancellable,
4298 GDBusMessage *message;
4299 GDBusMessage *reply;
4306 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4307 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4308 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4309 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4310 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4311 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4312 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4314 message = g_dbus_message_new_method_call (bus_name,
4318 add_invoke_method_flags (message, flags);
4319 if (parameters != NULL)
4320 g_dbus_message_set_body (message, parameters);
4322 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4325 NULL, /* volatile guint32 *out_serial */
4332 result = decode_method_reply (reply, error);
4335 if (message != NULL)
4336 g_object_unref (message);
4338 g_object_unref (reply);
4343 /* ---------------------------------------------------------------------------------------------------- */
4345 struct ExportedSubtree
4349 GDBusConnection *connection;
4350 const GDBusSubtreeVTable *vtable;
4351 GDBusSubtreeFlags flags;
4353 GMainContext *context;
4355 GDestroyNotify user_data_free_func;
4359 exported_subtree_free (ExportedSubtree *es)
4361 if (es->user_data_free_func != NULL)
4363 /* TODO: push to thread-default mainloop */
4364 es->user_data_free_func (es->user_data);
4366 if (es->context != NULL)
4368 g_main_context_unref (es->context);
4370 g_free (es->object_path);
4374 /* called without lock held */
4376 handle_subtree_introspect (GDBusConnection *connection,
4377 ExportedSubtree *es,
4378 GDBusMessage *message)
4382 GDBusMessage *reply;
4385 const gchar *sender;
4386 const gchar *requested_object_path;
4387 const gchar *requested_node;
4388 GPtrArray *interfaces;
4390 gchar **subnode_paths;
4394 requested_object_path = g_dbus_message_get_path (message);
4395 sender = g_dbus_message_get_sender (message);
4396 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4398 s = g_string_new (NULL);
4399 introspect_append_header (s);
4401 /* Strictly we don't need the children in dynamic mode, but we avoid the
4402 * conditionals to preserve code clarity
4404 children = es->vtable->enumerate (es->connection,
4411 requested_node = strrchr (requested_object_path, '/') + 1;
4413 /* Assert existence of object if we are not dynamic */
4414 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4415 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4420 requested_node = "/";
4423 interfaces = es->vtable->introspect (es->connection,
4428 if (interfaces != NULL)
4430 if (interfaces->len > 0)
4432 /* we're in business */
4433 introspect_append_standard_interfaces (s);
4435 for (n = 0; n < interfaces->len; n++)
4437 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4438 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4441 g_ptr_array_unref (interfaces);
4444 /* then include <node> entries from the Subtree for the root */
4447 for (n = 0; children != NULL && children[n] != NULL; n++)
4449 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4453 /* finally include nodes registered below us */
4454 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4455 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4457 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4459 g_strfreev (subnode_paths);
4461 g_string_append (s, "</node>\n");
4463 reply = g_dbus_message_new_method_reply (message);
4464 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4465 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4466 g_object_unref (reply);
4471 g_string_free (s, TRUE);
4472 g_strfreev (children);
4476 /* called without lock held */
4478 handle_subtree_method_invocation (GDBusConnection *connection,
4479 ExportedSubtree *es,
4480 GDBusMessage *message)
4483 const gchar *sender;
4484 const gchar *interface_name;
4485 const gchar *member;
4486 const gchar *signature;
4487 const gchar *requested_object_path;
4488 const gchar *requested_node;
4491 const GDBusInterfaceInfo *introspection_data;
4492 const GDBusInterfaceVTable *interface_vtable;
4493 gpointer interface_user_data;
4495 GPtrArray *interfaces;
4496 gboolean is_property_get;
4497 gboolean is_property_set;
4498 gboolean is_property_get_all;
4503 requested_object_path = g_dbus_message_get_path (message);
4504 sender = g_dbus_message_get_sender (message);
4505 interface_name = g_dbus_message_get_interface (message);
4506 member = g_dbus_message_get_member (message);
4507 signature = g_dbus_message_get_signature (message);
4508 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4510 is_property_get = FALSE;
4511 is_property_set = FALSE;
4512 is_property_get_all = FALSE;
4513 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4515 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4517 is_property_get = TRUE;
4519 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4521 is_property_set = TRUE;
4523 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4525 is_property_get_all = TRUE;
4529 children = es->vtable->enumerate (es->connection,
4536 requested_node = strrchr (requested_object_path, '/') + 1;
4538 /* If not dynamic, skip if requested node is not part of children */
4539 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4540 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4545 requested_node = "/";
4548 /* get introspection data for the node */
4549 interfaces = es->vtable->introspect (es->connection,
4551 requested_object_path,
4554 g_assert (interfaces != NULL);
4555 introspection_data = NULL;
4556 for (n = 0; n < interfaces->len; n++)
4558 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4559 if (g_strcmp0 (id_n->name, interface_name) == 0)
4561 introspection_data = id_n;
4565 /* dispatch the call if the user wants to handle it */
4566 if (introspection_data != NULL)
4568 /* figure out where to dispatch the method call */
4569 interface_user_data = NULL;
4570 interface_vtable = es->vtable->dispatch (es->connection,
4575 &interface_user_data,
4577 if (interface_vtable == NULL)
4580 CONNECTION_LOCK (connection);
4581 handled = validate_and_maybe_schedule_method_call (es->connection,
4586 interface_user_data);
4587 CONNECTION_UNLOCK (connection);
4589 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4590 else if (is_property_get || is_property_set || is_property_get_all)
4592 if (is_property_get)
4593 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4594 else if (is_property_set)
4595 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4596 else if (is_property_get_all)
4597 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4599 g_assert_not_reached ();
4601 /* see if the object supports this interface at all */
4602 for (n = 0; n < interfaces->len; n++)
4604 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4605 if (g_strcmp0 (id_n->name, interface_name) == 0)
4607 introspection_data = id_n;
4611 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4612 * claims it won't support the interface
4614 if (introspection_data == NULL)
4616 GDBusMessage *reply;
4617 reply = g_dbus_message_new_method_error (message,
4618 "org.freedesktop.DBus.Error.InvalidArgs",
4619 _("No such interface `%s'"),
4621 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4622 g_object_unref (reply);
4627 /* figure out where to dispatch the property get/set/getall calls */
4628 interface_user_data = NULL;
4629 interface_vtable = es->vtable->dispatch (es->connection,
4634 &interface_user_data,
4636 if (interface_vtable == NULL)
4639 if (is_property_get || is_property_set)
4641 CONNECTION_LOCK (connection);
4642 handled = validate_and_maybe_schedule_property_getset (es->connection,
4648 interface_user_data);
4649 CONNECTION_UNLOCK (connection);
4651 else if (is_property_get_all)
4653 CONNECTION_LOCK (connection);
4654 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4659 interface_user_data);
4660 CONNECTION_UNLOCK (connection);
4665 if (interfaces != NULL)
4666 g_ptr_array_unref (interfaces);
4667 g_strfreev (children);
4673 GDBusMessage *message;
4674 ExportedSubtree *es;
4675 } SubtreeDeferredData;
4678 subtree_deferred_data_free (SubtreeDeferredData *data)
4680 g_object_unref (data->message);
4684 /* called without lock held in the thread where the caller registered the subtree */
4686 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4688 SubtreeDeferredData *data = _data;
4693 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4694 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4695 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4697 handled = handle_subtree_introspect (data->es->connection,
4703 handled = handle_subtree_method_invocation (data->es->connection,
4711 CONNECTION_LOCK (data->es->connection);
4712 handled = handle_generic_unlocked (data->es->connection, data->message);
4713 CONNECTION_UNLOCK (data->es->connection);
4716 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4719 GDBusMessage *reply;
4720 reply = g_dbus_message_new_method_error (data->message,
4721 "org.freedesktop.DBus.Error.UnknownMethod",
4722 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4723 g_dbus_message_get_member (data->message),
4724 g_dbus_message_get_interface (data->message),
4725 g_dbus_message_get_signature (data->message));
4726 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4727 g_object_unref (reply);
4733 /* called in message handler thread with lock held */
4735 subtree_message_func (GDBusConnection *connection,
4736 ExportedSubtree *es,
4737 GDBusMessage *message)
4739 GSource *idle_source;
4740 SubtreeDeferredData *data;
4742 data = g_new0 (SubtreeDeferredData, 1);
4743 data->message = g_object_ref (message);
4746 /* defer this call to an idle handler in the right thread */
4747 idle_source = g_idle_source_new ();
4748 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4749 g_source_set_callback (idle_source,
4750 process_subtree_vtable_message_in_idle_cb,
4752 (GDestroyNotify) subtree_deferred_data_free);
4753 g_source_attach (idle_source, es->context);
4754 g_source_unref (idle_source);
4756 /* since we own the entire subtree, handlers for objects not in the subtree have been
4757 * tried already by libdbus-1 - so we just need to ensure that we're always going
4758 * to reply to the message
4764 * g_dbus_connection_register_subtree:
4765 * @connection: A #GDBusConnection.
4766 * @object_path: The object path to register the subtree at.
4767 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4768 * @flags: Flags used to fine tune the behavior of the subtree.
4769 * @user_data: Data to pass to functions in @vtable.
4770 * @user_data_free_func: Function to call when the subtree is unregistered.
4771 * @error: Return location for error or %NULL.
4773 * Registers a whole subtree of <quote>dynamic</quote> objects.
4775 * The @enumerate and @introspection functions in @vtable are used to
4776 * convey, to remote callers, what nodes exist in the subtree rooted
4779 * When handling remote calls into any node in the subtree, first the
4780 * @enumerate function is used to check if the node exists. If the node exists
4781 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4782 * the @introspection function is used to check if the node supports the
4783 * requested method. If so, the @dispatch function is used to determine
4784 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4785 * #gpointer will be used to call into the interface vtable for processing
4788 * All calls into user-provided code will be invoked in the <link
4789 * linkend="g-main-context-push-thread-default">thread-default main
4790 * loop</link> of the thread you are calling this method from.
4792 * If an existing subtree is already registered at @object_path or
4793 * then @error is set to #G_IO_ERROR_EXISTS.
4795 * Note that it is valid to register regular objects (using
4796 * g_dbus_connection_register_object()) in a subtree registered with
4797 * g_dbus_connection_register_subtree() - if so, the subtree handler
4798 * is tried as the last resort. One way to think about a subtree
4799 * handler is to consider it a <quote>fallback handler</quote>
4800 * for object paths not registered via g_dbus_connection_register_object()
4801 * or other bindings.
4803 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4805 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4806 * that can be used with g_dbus_connection_unregister_subtree() .
4811 g_dbus_connection_register_subtree (GDBusConnection *connection,
4812 const gchar *object_path,
4813 const GDBusSubtreeVTable *vtable,
4814 GDBusSubtreeFlags flags,
4816 GDestroyNotify user_data_free_func,
4820 ExportedSubtree *es;
4822 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4823 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4824 g_return_val_if_fail (vtable != NULL, 0);
4825 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4829 CONNECTION_LOCK (connection);
4831 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4837 _("A subtree is already exported for %s"),
4842 es = g_new0 (ExportedSubtree, 1);
4843 es->object_path = g_strdup (object_path);
4844 es->connection = connection;
4846 es->vtable = vtable;
4848 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4849 es->user_data = user_data;
4850 es->user_data_free_func = user_data_free_func;
4851 es->context = g_main_context_get_thread_default ();
4852 if (es->context != NULL)
4853 g_main_context_ref (es->context);
4855 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4856 g_hash_table_insert (connection->priv->map_id_to_es,
4857 GUINT_TO_POINTER (es->id),
4863 CONNECTION_UNLOCK (connection);
4868 /* ---------------------------------------------------------------------------------------------------- */
4871 * g_dbus_connection_unregister_subtree:
4872 * @connection: A #GDBusConnection.
4873 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4875 * Unregisters a subtree.
4877 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4882 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4883 guint registration_id)
4885 ExportedSubtree *es;
4888 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4892 CONNECTION_LOCK (connection);
4894 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4895 GUINT_TO_POINTER (registration_id));
4901 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4902 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4907 CONNECTION_UNLOCK (connection);
4912 /* ---------------------------------------------------------------------------------------------------- */
4914 /* must be called with lock held */
4916 handle_generic_ping_unlocked (GDBusConnection *connection,
4917 const gchar *object_path,
4918 GDBusMessage *message)
4920 GDBusMessage *reply;
4921 reply = g_dbus_message_new_method_reply (message);
4922 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4923 g_object_unref (reply);
4926 /* must be called with lock held */
4928 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4929 const gchar *object_path,
4930 GDBusMessage *message)
4932 GDBusMessage *reply;
4935 if (connection->priv->machine_id == NULL)
4939 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4940 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4941 &connection->priv->machine_id,
4945 reply = g_dbus_message_new_method_error (message,
4946 "org.freedesktop.DBus.Error.Failed",
4947 _("Unable to load /var/lib/dbus/machine-id: %s"),
4949 g_error_free (error);
4953 g_strstrip (connection->priv->machine_id);
4954 /* TODO: validate value */
4960 reply = g_dbus_message_new_method_reply (message);
4961 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4963 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4964 g_object_unref (reply);
4967 /* must be called with lock held */
4969 handle_generic_introspect_unlocked (GDBusConnection *connection,
4970 const gchar *object_path,
4971 GDBusMessage *message)
4976 GDBusMessage *reply;
4978 /* first the header */
4979 s = g_string_new (NULL);
4980 introspect_append_header (s);
4982 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4983 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4985 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4987 g_strfreev (registered);
4988 g_string_append (s, "</node>\n");
4990 reply = g_dbus_message_new_method_reply (message);
4991 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4992 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4993 g_object_unref (reply);
4994 g_string_free (s, TRUE);
4997 /* must be called with lock held */
4999 handle_generic_unlocked (GDBusConnection *connection,
5000 GDBusMessage *message)
5003 const gchar *interface_name;
5004 const gchar *member;
5005 const gchar *signature;
5008 CONNECTION_ENSURE_LOCK (connection);
5012 interface_name = g_dbus_message_get_interface (message);
5013 member = g_dbus_message_get_member (message);
5014 signature = g_dbus_message_get_signature (message);
5015 path = g_dbus_message_get_path (message);
5017 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5018 g_strcmp0 (member, "Introspect") == 0 &&
5019 g_strcmp0 (signature, "") == 0)
5021 handle_generic_introspect_unlocked (connection, path, message);
5024 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5025 g_strcmp0 (member, "Ping") == 0 &&
5026 g_strcmp0 (signature, "") == 0)
5028 handle_generic_ping_unlocked (connection, path, message);
5031 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5032 g_strcmp0 (member, "GetMachineId") == 0 &&
5033 g_strcmp0 (signature, "") == 0)
5035 handle_generic_get_machine_id_unlocked (connection, path, message);
5042 /* ---------------------------------------------------------------------------------------------------- */
5044 /* called in message handler thread with lock held */
5046 distribute_method_call (GDBusConnection *connection,
5047 GDBusMessage *message)
5050 ExportedSubtree *es;
5051 const gchar *object_path;
5052 const gchar *interface_name;
5053 const gchar *member;
5054 const gchar *signature;
5056 gchar *subtree_path;
5059 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5061 interface_name = g_dbus_message_get_interface (message);
5062 member = g_dbus_message_get_member (message);
5063 signature = g_dbus_message_get_signature (message);
5064 path = g_dbus_message_get_path (message);
5065 subtree_path = g_strdup (path);
5066 needle = strrchr (subtree_path, '/');
5067 if (needle != NULL && needle != subtree_path)
5073 g_free (subtree_path);
5074 subtree_path = NULL;
5078 g_debug ("interface = `%s'", interface_name);
5079 g_debug ("member = `%s'", member);
5080 g_debug ("signature = `%s'", signature);
5081 g_debug ("path = `%s'", path);
5082 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5085 object_path = g_dbus_message_get_path (message);
5086 g_assert (object_path != NULL);
5088 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5091 if (obj_message_func (connection, eo, message))
5095 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5098 if (subtree_message_func (connection, es, message))
5102 if (subtree_path != NULL)
5104 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5107 if (subtree_message_func (connection, es, message))
5112 if (handle_generic_unlocked (connection, message))
5115 /* if we end up here, the message has not been not handled */
5118 g_free (subtree_path);
5121 /* ---------------------------------------------------------------------------------------------------- */
5123 static GDBusConnection **
5124 message_bus_get_singleton (GBusType bus_type,
5127 GDBusConnection **ret;
5128 const gchar *starter_bus;
5135 g_assert_not_reached ();
5138 case G_BUS_TYPE_SESSION:
5139 ret = &the_session_bus;
5142 case G_BUS_TYPE_SYSTEM:
5143 ret = &the_system_bus;
5146 case G_BUS_TYPE_STARTER:
5147 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5148 if (g_strcmp0 (starter_bus, "session") == 0)
5150 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5153 else if (g_strcmp0 (starter_bus, "system") == 0)
5155 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5160 if (starter_bus != NULL)
5164 G_IO_ERROR_INVALID_ARGUMENT,
5165 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5166 " - unknown value `%s'"),
5171 g_set_error_literal (error,
5173 G_IO_ERROR_INVALID_ARGUMENT,
5174 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5175 "variable is not set"));
5184 static GDBusConnection *
5185 get_uninitialized_connection (GBusType bus_type,
5186 GCancellable *cancellable,
5189 GDBusConnection **singleton;
5190 GDBusConnection *ret;
5194 G_LOCK (message_bus_lock);
5195 singleton = message_bus_get_singleton (bus_type, error);
5196 if (singleton == NULL)
5199 if (*singleton == NULL)
5202 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5203 if (address == NULL)
5205 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5207 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5208 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5209 "exit-on-close", TRUE,
5214 ret = g_object_ref (*singleton);
5217 g_assert (ret != NULL);
5220 G_UNLOCK (message_bus_lock);
5226 * @bus_type: A #GBusType.
5227 * @cancellable: A #GCancellable or %NULL.
5228 * @error: Return location for error or %NULL.
5230 * Synchronously connects to the message bus specified by @bus_type.
5231 * Note that the returned object may shared with other callers,
5232 * e.g. if two separate parts of a process calls this function with
5233 * the same @bus_type, they will share the same object.
5235 * This is a synchronous failable function. See g_bus_get() and
5236 * g_bus_get_finish() for the asynchronous version.
5238 * The returned object is a singleton, that is, shared with other
5239 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5240 * event that you need a private message bus connection, use
5241 * g_dbus_address_get_for_bus() and
5242 * g_dbus_connection_new_for_address().
5244 * Note that the returned #GDBusConnection object will (usually) have
5245 * the #GDBusConnection:exit-on-close property set to %TRUE.
5247 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5252 g_bus_get_sync (GBusType bus_type,
5253 GCancellable *cancellable,
5256 GDBusConnection *connection;
5258 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5260 connection = get_uninitialized_connection (bus_type, cancellable, error);
5261 if (connection == NULL)
5264 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5266 g_object_unref (connection);
5275 bus_get_async_initable_cb (GObject *source_object,
5279 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5283 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5287 g_assert (error != NULL);
5288 g_simple_async_result_set_from_error (simple, error);
5289 g_error_free (error);
5290 g_object_unref (source_object);
5294 g_simple_async_result_set_op_res_gpointer (simple,
5298 g_simple_async_result_complete_in_idle (simple);
5299 g_object_unref (simple);
5304 * @bus_type: A #GBusType.
5305 * @cancellable: A #GCancellable or %NULL.
5306 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5307 * @user_data: The data to pass to @callback.
5309 * Asynchronously connects to the message bus specified by @bus_type.
5311 * When the operation is finished, @callback will be invoked. You can
5312 * then call g_bus_get_finish() to get the result of the operation.
5314 * This is a asynchronous failable function. See g_bus_get_sync() for
5315 * the synchronous version.
5320 g_bus_get (GBusType bus_type,
5321 GCancellable *cancellable,
5322 GAsyncReadyCallback callback,
5325 GDBusConnection *connection;
5326 GSimpleAsyncResult *simple;
5329 simple = g_simple_async_result_new (NULL,
5335 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5336 if (connection == NULL)
5338 g_assert (error != NULL);
5339 g_simple_async_result_set_from_error (simple, error);
5340 g_error_free (error);
5341 g_simple_async_result_complete_in_idle (simple);
5342 g_object_unref (simple);
5346 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5349 bus_get_async_initable_cb,
5356 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5357 * @error: Return location for error or %NULL.
5359 * Finishes an operation started with g_bus_get().
5361 * The returned object is a singleton, that is, shared with other
5362 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5363 * event that you need a private message bus connection, use
5364 * g_dbus_address_get_for_bus() and
5365 * g_dbus_connection_new_for_address().
5367 * Note that the returned #GDBusConnection object will (usually) have
5368 * the #GDBusConnection:exit-on-close property set to %TRUE.
5370 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5375 g_bus_get_finish (GAsyncResult *res,
5378 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5380 GDBusConnection *ret;
5382 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5384 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5388 if (g_simple_async_result_propagate_error (simple, error))
5391 object = g_simple_async_result_get_op_res_gpointer (simple);
5392 g_assert (object != NULL);
5393 ret = g_object_ref (G_DBUS_CONNECTION (object));
5399 /* ---------------------------------------------------------------------------------------------------- */
5401 #define __G_DBUS_CONNECTION_C__
5402 #include "gioaliasdef.c"