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 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
32 * to specify where the nonce is stored. This will allow people to use
33 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
34 * to easily acheive secure RPC via nonce-tcp.
36 * - need to expose an extension point for resolving D-Bus address and
37 * turning them into GIOStream objects. This will allow us to implement
38 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
40 * - see g_dbus_address_connect() in gdbusaddress.c
42 * - would be cute to use kernel-specific APIs to resolve fds for
43 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
45 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
47 * maybe we can show more information about what fd 21 really is.
48 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
49 * Initial experiments on Linux 2.6 suggests that the symlink looks
54 * e.g. not of much use.
62 #include "gdbusauth.h"
63 #include "gdbusutils.h"
64 #include "gdbusaddress.h"
65 #include "gdbusmessage.h"
66 #include "gdbusconnection.h"
67 #include "gdbuserror.h"
68 #include "gioenumtypes.h"
69 #include "gdbusintrospection.h"
70 #include "gdbusmethodinvocation.h"
71 #include "gdbusprivate.h"
72 #include "gdbusauthobserver.h"
73 #include "gio-marshal.h"
74 #include "ginitable.h"
75 #include "gasyncinitable.h"
76 #include "giostream.h"
77 #include "gasyncresult.h"
78 #include "gsimpleasyncresult.h"
81 #include <gio/gunixconnection.h>
82 #include <gio/gunixfdmessage.h>
84 #include <sys/types.h>
91 * SECTION:gdbusconnection
92 * @short_description: D-Bus Connections
95 * The #GDBusConnection type is used for D-Bus connections to remote
96 * peers such as a message buses. It is a low-level API that offers a
97 * lot of flexibility. For instance, it lets you establish a connection
98 * over any transport that can by represented as an #GIOStream.
100 * This class is rarely used directly in D-Bus clients. If you are writing
101 * an D-Bus client, it is often easier to use the g_bus_own_name(),
102 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
104 * <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>
106 * <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>
108 * <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>
111 /* ---------------------------------------------------------------------------------------------------- */
113 G_LOCK_DEFINE_STATIC (message_bus_lock);
115 static GDBusConnection *the_session_bus = NULL;
116 static GDBusConnection *the_system_bus = NULL;
118 /* ---------------------------------------------------------------------------------------------------- */
121 _g_strv_has_string (const gchar* const *haystack,
126 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
128 if (g_strcmp0 (haystack[n], needle) == 0)
134 /* ---------------------------------------------------------------------------------------------------- */
137 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
139 // TODO: for some reason this doesn't work on Windows
140 #define CONNECTION_ENSURE_LOCK(obj) do { \
141 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
143 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
144 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
149 #define CONNECTION_LOCK(obj) do { \
150 g_mutex_lock ((obj)->priv->lock); \
153 #define CONNECTION_UNLOCK(obj) do { \
154 g_mutex_unlock ((obj)->priv->lock); \
157 struct _GDBusConnectionPrivate
159 /* ------------------------------------------------------------------------ */
160 /* -- General object state ------------------------------------------------ */
161 /* ------------------------------------------------------------------------ */
163 /* object-wide lock */
166 /* A lock used in the init() method of the GInitable interface - see comments
167 * in initable_init() for why a separate lock is needed
171 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
172 * someone calls org.freedesktop.DBus.GetMachineId()
176 /* The underlying stream used for communication */
179 /* The object used for authentication (if any) */
182 /* Set to TRUE if the connection has been closed */
185 /* Last serial used */
188 /* The object used to send/receive message */
191 /* If connected to a message bus, this contains the unique name assigned to
192 * us by the bus (e.g. ":1.42")
194 gchar *bus_unique_name;
196 /* The GUID returned by the other side if we authenticed as a client or
197 * the GUID to use if authenticating as a server
201 /* set to TRUE exactly when initable_init() has finished running */
202 gboolean is_initialized;
204 /* If the connection could not be established during initable_init(), this GError will set */
205 GError *initialization_error;
207 /* The result of g_main_context_get_thread_default() when the object
208 * was created (the GObject _init() function) - this is used for delivery
209 * of the :closed GObject signal.
211 GMainContext *main_context_at_construction;
213 /* construct properties */
215 GDBusConnectionFlags flags;
217 /* Map used for managing method replies */
218 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
220 /* Maps used for managing signal subscription */
221 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
222 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
223 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
225 /* Maps used for managing exported objects and subtrees */
226 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
227 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
228 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
229 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
231 /* Structure used for message filters */
234 /* Whether to exit on close */
235 gboolean exit_on_close;
237 /* Capabilities negotiated during authentication */
238 GDBusCapabilityFlags capabilities;
240 GDBusAuthObserver *authentication_observer;
241 GCredentials *crendentials;
244 typedef struct ExportedObject ExportedObject;
245 static void exported_object_free (ExportedObject *eo);
247 typedef struct ExportedSubtree ExportedSubtree;
248 static void exported_subtree_free (ExportedSubtree *es);
266 PROP_CAPABILITY_FLAGS,
267 PROP_AUTHENTICATION_OBSERVER,
270 static void distribute_signals (GDBusConnection *connection,
271 GDBusMessage *message);
273 static void distribute_method_call (GDBusConnection *connection,
274 GDBusMessage *message);
276 static gboolean handle_generic_unlocked (GDBusConnection *connection,
277 GDBusMessage *message);
280 static void purge_all_signal_subscriptions (GDBusConnection *connection);
281 static void purge_all_filters (GDBusConnection *connection);
283 #define _G_ENSURE_LOCK(name) do { \
284 if (G_UNLIKELY (G_TRYLOCK(name))) \
286 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
287 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
291 static guint signals[LAST_SIGNAL] = { 0 };
293 static void initable_iface_init (GInitableIface *initable_iface);
294 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
296 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
297 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
298 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
302 g_dbus_connection_dispose (GObject *object)
304 GDBusConnection *connection = G_DBUS_CONNECTION (object);
306 G_LOCK (message_bus_lock);
307 //g_debug ("disposing %p", connection);
308 if (connection == the_session_bus)
310 the_session_bus = NULL;
312 else if (connection == the_system_bus)
314 the_system_bus = NULL;
316 if (connection->priv->worker != NULL)
318 _g_dbus_worker_stop (connection->priv->worker);
319 connection->priv->worker = NULL;
321 G_UNLOCK (message_bus_lock);
323 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
324 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
328 g_dbus_connection_finalize (GObject *object)
330 GDBusConnection *connection = G_DBUS_CONNECTION (object);
332 if (connection->priv->authentication_observer != NULL)
333 g_object_unref (connection->priv->authentication_observer);
335 if (connection->priv->auth != NULL)
336 g_object_unref (connection->priv->auth);
338 //g_debug ("finalizing %p", connection);
339 if (connection->priv->stream != NULL)
341 /* We don't really care if closing the stream succeeds or not */
342 g_io_stream_close_async (connection->priv->stream,
344 NULL, /* GCancellable */
345 NULL, /* GAsyncReadyCallback */
346 NULL); /* userdata */
347 g_object_unref (connection->priv->stream);
348 connection->priv->stream = NULL;
351 g_free (connection->priv->address);
353 g_free (connection->priv->guid);
354 g_free (connection->priv->bus_unique_name);
356 if (connection->priv->initialization_error != NULL)
357 g_error_free (connection->priv->initialization_error);
359 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
361 purge_all_signal_subscriptions (connection);
362 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
363 g_hash_table_unref (connection->priv->map_id_to_signal_data);
364 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
366 g_hash_table_unref (connection->priv->map_id_to_ei);
367 g_hash_table_unref (connection->priv->map_object_path_to_eo);
368 g_hash_table_unref (connection->priv->map_id_to_es);
369 g_hash_table_unref (connection->priv->map_object_path_to_es);
371 purge_all_filters (connection);
372 g_ptr_array_unref (connection->priv->filters);
374 if (connection->priv->main_context_at_construction != NULL)
375 g_main_context_unref (connection->priv->main_context_at_construction);
377 g_free (connection->priv->machine_id);
379 g_mutex_free (connection->priv->init_lock);
380 g_mutex_free (connection->priv->lock);
382 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
386 g_dbus_connection_get_property (GObject *object,
391 GDBusConnection *connection = G_DBUS_CONNECTION (object);
396 g_value_set_object (value, g_dbus_connection_get_stream (connection));
400 g_value_set_string (value, g_dbus_connection_get_guid (connection));
403 case PROP_UNIQUE_NAME:
404 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
408 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
411 case PROP_EXIT_ON_CLOSE:
412 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
415 case PROP_CAPABILITY_FLAGS:
416 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
420 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
426 g_dbus_connection_set_property (GObject *object,
431 GDBusConnection *connection = G_DBUS_CONNECTION (object);
436 connection->priv->stream = g_value_dup_object (value);
440 connection->priv->guid = g_value_dup_string (value);
444 connection->priv->address = g_value_dup_string (value);
448 connection->priv->flags = g_value_get_flags (value);
451 case PROP_EXIT_ON_CLOSE:
452 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
455 case PROP_AUTHENTICATION_OBSERVER:
456 connection->priv->authentication_observer = g_value_dup_object (value);
460 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
466 g_dbus_connection_real_closed (GDBusConnection *connection,
467 gboolean remote_peer_vanished,
470 if (remote_peer_vanished && connection->priv->exit_on_close)
472 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
478 g_dbus_connection_class_init (GDBusConnectionClass *klass)
480 GObjectClass *gobject_class;
482 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
484 gobject_class = G_OBJECT_CLASS (klass);
486 gobject_class->finalize = g_dbus_connection_finalize;
487 gobject_class->dispose = g_dbus_connection_dispose;
488 gobject_class->set_property = g_dbus_connection_set_property;
489 gobject_class->get_property = g_dbus_connection_get_property;
491 klass->closed = g_dbus_connection_real_closed;
494 * GDBusConnection:stream:
496 * The underlying #GIOStream used for I/O.
500 g_object_class_install_property (gobject_class,
502 g_param_spec_object ("stream",
504 P_("The underlying streams used for I/O"),
508 G_PARAM_CONSTRUCT_ONLY |
509 G_PARAM_STATIC_NAME |
510 G_PARAM_STATIC_BLURB |
511 G_PARAM_STATIC_NICK));
514 * GDBusConnection:address:
516 * A D-Bus address specifying potential endpoints that can be used
517 * when establishing the connection.
521 g_object_class_install_property (gobject_class,
523 g_param_spec_string ("address",
525 P_("D-Bus address specifying potential socket endpoints"),
528 G_PARAM_CONSTRUCT_ONLY |
529 G_PARAM_STATIC_NAME |
530 G_PARAM_STATIC_BLURB |
531 G_PARAM_STATIC_NICK));
534 * GDBusConnection:flags:
536 * Flags from the #GDBusConnectionFlags enumeration.
540 g_object_class_install_property (gobject_class,
542 g_param_spec_flags ("flags",
545 G_TYPE_DBUS_CONNECTION_FLAGS,
546 G_DBUS_CONNECTION_FLAGS_NONE,
548 G_PARAM_CONSTRUCT_ONLY |
549 G_PARAM_STATIC_NAME |
550 G_PARAM_STATIC_BLURB |
551 G_PARAM_STATIC_NICK));
554 * GDBusConnection:guid:
556 * The GUID of the peer performing the role of server when
559 * If you are constructing a #GDBusConnection and pass
560 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
561 * #GDBusConnection:flags property then you MUST also set this
562 * property to a valid guid.
564 * If you are constructing a #GDBusConnection and pass
565 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
566 * #GDBusConnection:flags property you will be able to read the GUID
567 * of the other peer here after the connection has been successfully
572 g_object_class_install_property (gobject_class,
574 g_param_spec_string ("guid",
576 P_("GUID of the server peer"),
580 G_PARAM_CONSTRUCT_ONLY |
581 G_PARAM_STATIC_NAME |
582 G_PARAM_STATIC_BLURB |
583 G_PARAM_STATIC_NICK));
586 * GDBusConnection:unique-name:
588 * The unique name as assigned by the message bus or %NULL if the
589 * connection is not open or not a message bus connection.
593 g_object_class_install_property (gobject_class,
595 g_param_spec_string ("unique-name",
597 P_("Unique name of bus connection"),
600 G_PARAM_STATIC_NAME |
601 G_PARAM_STATIC_BLURB |
602 G_PARAM_STATIC_NICK));
605 * GDBusConnection:closed:
607 * A boolean specifying whether the connection has been closed.
611 g_object_class_install_property (gobject_class,
613 g_param_spec_boolean ("closed",
615 P_("Whether the connection is closed"),
618 G_PARAM_STATIC_NAME |
619 G_PARAM_STATIC_BLURB |
620 G_PARAM_STATIC_NICK));
623 * GDBusConnection:exit-on-close:
625 * A boolean specifying whether the process will be terminated (by
626 * calling <literal>raise(SIGTERM)</literal>) if the connection
627 * is closed by the remote peer.
631 g_object_class_install_property (gobject_class,
633 g_param_spec_boolean ("exit-on-close",
635 P_("Whether the process is terminated when the connection is closed"),
639 G_PARAM_STATIC_NAME |
640 G_PARAM_STATIC_BLURB |
641 G_PARAM_STATIC_NICK));
644 * GDBusConnection:capabilities:
646 * Flags from the #GDBusCapabilityFlags enumeration
647 * representing connection features negotiated with the other peer.
651 g_object_class_install_property (gobject_class,
652 PROP_CAPABILITY_FLAGS,
653 g_param_spec_flags ("capabilities",
656 G_TYPE_DBUS_CAPABILITY_FLAGS,
657 G_DBUS_CAPABILITY_FLAGS_NONE,
659 G_PARAM_STATIC_NAME |
660 G_PARAM_STATIC_BLURB |
661 G_PARAM_STATIC_NICK));
664 * GDBusConnection:authentication-observer:
666 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
670 g_object_class_install_property (gobject_class,
671 PROP_AUTHENTICATION_OBSERVER,
672 g_param_spec_object ("authentication-observer",
673 P_("Authentication Observer"),
674 P_("Object used to assist in the authentication process"),
675 G_TYPE_DBUS_AUTH_OBSERVER,
677 G_PARAM_CONSTRUCT_ONLY |
678 G_PARAM_STATIC_NAME |
679 G_PARAM_STATIC_BLURB |
680 G_PARAM_STATIC_NICK));
683 * GDBusConnection::closed:
684 * @connection: The #GDBusConnection emitting the signal.
685 * @remote_peer_vanished: %TRUE if @connection is closed because the
686 * remote peer closed its end of the connection.
687 * @error: A #GError with more details about the event or %NULL.
689 * Emitted when the connection is closed.
691 * The cause of this event can be
694 * If g_dbus_connection_close() is called. In this case
695 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
698 * If the remote peer closes the connection. In this case
699 * @remote_peer_vanished is set to %TRUE and @error is set.
702 * If the remote peer sends invalid or malformed data. In this
703 * case @remote_peer_vanished is set to %FALSE and @error
708 * Upon receiving this signal, you should give up your reference to
709 * @connection. You are guaranteed that this signal is emitted only
714 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
715 G_TYPE_DBUS_CONNECTION,
717 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
720 _gio_marshal_VOID__BOOLEAN_BOXED,
728 g_dbus_connection_init (GDBusConnection *connection)
730 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
732 connection->priv->lock = g_mutex_new ();
733 connection->priv->init_lock = g_mutex_new ();
735 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
737 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
739 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
741 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
746 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
749 (GDestroyNotify) exported_object_free);
751 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
754 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
757 (GDestroyNotify) exported_subtree_free);
759 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
762 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
763 if (connection->priv->main_context_at_construction != NULL)
764 g_main_context_ref (connection->priv->main_context_at_construction);
766 connection->priv->filters = g_ptr_array_new ();
770 * g_dbus_connection_get_stream:
771 * @connection: a #GDBusConnection
773 * Gets the underlying stream used for IO.
775 * Returns: the stream used for IO
780 g_dbus_connection_get_stream (GDBusConnection *connection)
782 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
783 return connection->priv->stream;
788 * g_dbus_connection_is_closed:
789 * @connection: A #GDBusConnection.
791 * Gets whether @connection is closed.
793 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
798 g_dbus_connection_is_closed (GDBusConnection *connection)
800 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
801 return connection->priv->closed;
805 * g_dbus_connection_get_capabilities:
806 * @connection: A #GDBusConnection.
808 * Gets the capabilities negotiated with the remote peer
810 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
815 g_dbus_connection_get_capabilities (GDBusConnection *connection)
817 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
818 return connection->priv->capabilities;
822 /* ---------------------------------------------------------------------------------------------------- */
826 GDBusConnection *connection;
828 gboolean remote_peer_vanished;
832 emit_closed_data_free (EmitClosedData *data)
834 g_object_unref (data->connection);
835 if (data->error != NULL)
836 g_error_free (data->error);
841 emit_closed_in_idle (gpointer user_data)
843 EmitClosedData *data = user_data;
846 g_object_notify (G_OBJECT (data->connection), "closed");
847 g_signal_emit (data->connection,
848 signals[CLOSED_SIGNAL],
850 data->remote_peer_vanished,
856 /* Can be called from any thread, must hold lock */
858 set_closed_unlocked (GDBusConnection *connection,
859 gboolean remote_peer_vanished,
862 GSource *idle_source;
863 EmitClosedData *data;
865 CONNECTION_ENSURE_LOCK (connection);
867 g_assert (!connection->priv->closed);
869 connection->priv->closed = TRUE;
871 data = g_new0 (EmitClosedData, 1);
872 data->connection = g_object_ref (connection);
873 data->remote_peer_vanished = remote_peer_vanished;
874 data->error = error != NULL ? g_error_copy (error) : NULL;
876 idle_source = g_idle_source_new ();
877 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
878 g_source_set_callback (idle_source,
881 (GDestroyNotify) emit_closed_data_free);
882 g_source_attach (idle_source, connection->priv->main_context_at_construction);
883 g_source_unref (idle_source);
886 /* ---------------------------------------------------------------------------------------------------- */
889 * g_dbus_connection_close:
890 * @connection: A #GDBusConnection.
892 * Closes @connection. Note that this never causes the process to
893 * exit (this might only happen if the other end of a shared message
894 * bus connection disconnects).
896 * If @connection is already closed, this method does nothing.
901 g_dbus_connection_close (GDBusConnection *connection)
903 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
905 CONNECTION_LOCK (connection);
906 if (!connection->priv->closed)
908 GError *error = NULL;
910 /* TODO: do this async */
911 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
912 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
914 g_warning ("Error closing stream: %s", error->message);
915 g_error_free (error);
918 set_closed_unlocked (connection, FALSE, NULL);
920 CONNECTION_UNLOCK (connection);
923 /* ---------------------------------------------------------------------------------------------------- */
926 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
927 GDBusMessage *message,
928 volatile guint32 *out_serial,
933 guint32 serial_to_use;
936 CONNECTION_ENSURE_LOCK (connection);
938 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
939 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
941 /* TODO: check all necessary headers are present */
946 if (out_serial != NULL)
949 if (connection->priv->closed)
951 g_set_error_literal (error,
954 _("The connection is closed"));
958 blob = g_dbus_message_to_blob (message,
964 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
969 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
972 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
975 g_assert_not_reached ();
980 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
981 blob_size, serial_to_use, connection);
982 g_printerr ("----\n");
983 hexdump (blob, blob_size);
984 g_printerr ("----\n");
987 /* TODO: use connection->priv->auth to encode the blob */
989 if (out_serial != NULL)
990 *out_serial = serial_to_use;
992 g_dbus_message_set_serial (message, serial_to_use);
994 _g_dbus_worker_send_message (connection->priv->worker,
998 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1009 * g_dbus_connection_send_message:
1010 * @connection: A #GDBusConnection.
1011 * @message: A #GDBusMessage
1012 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1013 * @error: Return location for error or %NULL.
1015 * Asynchronously sends @message to the peer represented by @connection.
1017 * If @out_serial is not %NULL, then the serial number assigned to
1018 * @message by @connection will be written to this location prior to
1019 * submitting the message to the underlying transport.
1021 * If @connection is closed then the operation will fail with
1022 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1023 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1024 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1026 * See <xref linkend="gdbus-server"/> and <xref
1027 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1028 * low-level API to send and receive UNIX file descriptors.
1030 * Returns: %TRUE if the message was well-formed and queued for
1031 * transmission, %FALSE if @error is set.
1036 g_dbus_connection_send_message (GDBusConnection *connection,
1037 GDBusMessage *message,
1038 volatile guint32 *out_serial,
1043 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1044 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1045 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1047 CONNECTION_LOCK (connection);
1048 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1049 CONNECTION_UNLOCK (connection);
1053 /* ---------------------------------------------------------------------------------------------------- */
1057 volatile gint ref_count;
1058 GDBusConnection *connection;
1060 GSimpleAsyncResult *simple;
1062 GMainContext *main_context;
1064 GCancellable *cancellable;
1066 gulong cancellable_handler_id;
1068 GSource *timeout_source;
1073 static SendMessageData *
1074 send_message_data_ref (SendMessageData *data)
1076 g_atomic_int_inc (&data->ref_count);
1081 send_message_data_unref (SendMessageData *data)
1083 if (g_atomic_int_dec_and_test (&data->ref_count))
1085 g_assert (data->timeout_source == NULL);
1086 g_assert (data->simple == NULL);
1087 g_assert (data->cancellable_handler_id == 0);
1088 g_object_unref (data->connection);
1089 if (data->cancellable != NULL)
1090 g_object_unref (data->cancellable);
1091 if (data->main_context != NULL)
1092 g_main_context_unref (data->main_context);
1097 /* ---------------------------------------------------------------------------------------------------- */
1099 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1101 send_message_with_reply_deliver (SendMessageData *data)
1103 CONNECTION_ENSURE_LOCK (data->connection);
1105 g_assert (!data->delivered);
1107 data->delivered = TRUE;
1109 g_simple_async_result_complete_in_idle (data->simple);
1110 g_object_unref (data->simple);
1111 data->simple = NULL;
1113 if (data->timeout_source != NULL)
1115 g_source_destroy (data->timeout_source);
1116 data->timeout_source = NULL;
1118 if (data->cancellable_handler_id > 0)
1120 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1121 data->cancellable_handler_id = 0;
1124 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1125 GUINT_TO_POINTER (data->serial)));
1127 send_message_data_unref (data);
1130 /* ---------------------------------------------------------------------------------------------------- */
1132 /* must hold lock */
1134 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1135 GDBusMessage *reply)
1137 if (data->delivered)
1140 g_simple_async_result_set_op_res_gpointer (data->simple,
1141 g_object_ref (reply),
1144 send_message_with_reply_deliver (data);
1150 /* ---------------------------------------------------------------------------------------------------- */
1153 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1155 SendMessageData *data = user_data;
1157 CONNECTION_LOCK (data->connection);
1158 if (data->delivered)
1161 g_simple_async_result_set_error (data->simple,
1163 G_IO_ERROR_CANCELLED,
1164 _("Operation was cancelled"));
1166 send_message_with_reply_deliver (data);
1169 CONNECTION_UNLOCK (data->connection);
1173 /* Can be called from any thread with or without lock held */
1175 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1178 SendMessageData *data = user_data;
1179 GSource *idle_source;
1181 /* postpone cancellation to idle handler since we may be called directly
1182 * via g_cancellable_connect() (e.g. holding lock)
1184 idle_source = g_idle_source_new ();
1185 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1186 g_source_set_callback (idle_source,
1187 send_message_with_reply_cancelled_idle_cb,
1188 send_message_data_ref (data),
1189 (GDestroyNotify) send_message_data_unref);
1190 g_source_attach (idle_source, data->main_context);
1191 g_source_unref (idle_source);
1194 /* ---------------------------------------------------------------------------------------------------- */
1197 send_message_with_reply_timeout_cb (gpointer user_data)
1199 SendMessageData *data = user_data;
1201 CONNECTION_LOCK (data->connection);
1202 if (data->delivered)
1205 g_simple_async_result_set_error (data->simple,
1207 G_IO_ERROR_TIMED_OUT,
1208 _("Timeout was reached"));
1210 send_message_with_reply_deliver (data);
1213 CONNECTION_UNLOCK (data->connection);
1218 /* ---------------------------------------------------------------------------------------------------- */
1221 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1222 GDBusMessage *message,
1224 volatile guint32 *out_serial,
1225 GCancellable *cancellable,
1226 GAsyncReadyCallback callback,
1229 GSimpleAsyncResult *simple;
1230 SendMessageData *data;
1232 volatile guint32 serial;
1236 if (out_serial == NULL)
1237 out_serial = &serial;
1239 if (timeout_msec == -1)
1240 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1242 simple = g_simple_async_result_new (G_OBJECT (connection),
1245 g_dbus_connection_send_message_with_reply);
1247 if (g_cancellable_is_cancelled (cancellable))
1249 g_simple_async_result_set_error (simple,
1251 G_IO_ERROR_CANCELLED,
1252 _("Operation was cancelled"));
1253 g_simple_async_result_complete_in_idle (simple);
1254 g_object_unref (simple);
1258 if (connection->priv->closed)
1260 g_simple_async_result_set_error (simple,
1263 _("The connection is closed"));
1264 g_simple_async_result_complete_in_idle (simple);
1265 g_object_unref (simple);
1270 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1272 g_simple_async_result_set_from_error (simple, error);
1273 g_simple_async_result_complete_in_idle (simple);
1274 g_object_unref (simple);
1278 data = g_new0 (SendMessageData, 1);
1279 data->ref_count = 1;
1280 data->connection = g_object_ref (connection);
1281 data->simple = simple;
1282 data->serial = *out_serial;
1283 data->main_context = g_main_context_get_thread_default ();
1284 if (data->main_context != NULL)
1285 g_main_context_ref (data->main_context);
1287 if (cancellable != NULL)
1289 data->cancellable = g_object_ref (cancellable);
1290 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1291 G_CALLBACK (send_message_with_reply_cancelled_cb),
1292 send_message_data_ref (data),
1293 (GDestroyNotify) send_message_data_unref);
1294 g_object_set_data_full (G_OBJECT (simple),
1296 g_object_ref (cancellable),
1297 (GDestroyNotify) g_object_unref);
1300 data->timeout_source = g_timeout_source_new (timeout_msec);
1301 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1302 g_source_set_callback (data->timeout_source,
1303 send_message_with_reply_timeout_cb,
1304 send_message_data_ref (data),
1305 (GDestroyNotify) send_message_data_unref);
1306 g_source_attach (data->timeout_source, data->main_context);
1307 g_source_unref (data->timeout_source);
1309 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1310 GUINT_TO_POINTER (*out_serial),
1318 * g_dbus_connection_send_message_with_reply:
1319 * @connection: A #GDBusConnection.
1320 * @message: A #GDBusMessage.
1321 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1322 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1323 * @cancellable: A #GCancellable or %NULL.
1324 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1325 * care about the result.
1326 * @user_data: The data to pass to @callback.
1328 * Asynchronously sends @message to the peer represented by @connection.
1330 * If @out_serial is not %NULL, then the serial number assigned to
1331 * @message by @connection will be written to this location prior to
1332 * submitting the message to the underlying transport.
1334 * If @connection is closed then the operation will fail with
1335 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1336 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1337 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1339 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1340 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1341 * of the thread you are calling this method from. You can then call
1342 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1343 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1345 * See <xref linkend="gdbus-server"/> and <xref
1346 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1347 * low-level API to send and receive UNIX file descriptors.
1352 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1353 GDBusMessage *message,
1355 volatile guint32 *out_serial,
1356 GCancellable *cancellable,
1357 GAsyncReadyCallback callback,
1360 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1361 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1362 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1364 CONNECTION_LOCK (connection);
1365 g_dbus_connection_send_message_with_reply_unlocked (connection,
1372 CONNECTION_UNLOCK (connection);
1376 * g_dbus_connection_send_message_with_reply_finish:
1377 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1378 * @error: Return location for error or %NULL.
1380 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1382 * Note that @error is only set if a local in-process error
1383 * occured. That is to say that the returned #GDBusMessage object may
1384 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1385 * g_dbus_message_to_gerror() to transcode this to a #GError.
1387 * See <xref linkend="gdbus-server"/> and <xref
1388 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1389 * low-level API to send and receive UNIX file descriptors.
1391 * Returns: A #GDBusMessage or %NULL if @error is set.
1396 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1400 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1401 GDBusMessage *reply;
1402 GCancellable *cancellable;
1404 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1405 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1409 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1411 if (g_simple_async_result_propagate_error (simple, error))
1414 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1415 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1416 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1418 g_object_unref (reply);
1420 g_set_error_literal (error,
1422 G_IO_ERROR_CANCELLED,
1423 _("Operation was cancelled"));
1429 /* ---------------------------------------------------------------------------------------------------- */
1434 GMainContext *context;
1436 } SendMessageSyncData;
1439 send_message_with_reply_sync_cb (GDBusConnection *connection,
1443 SendMessageSyncData *data = user_data;
1444 data->res = g_object_ref (res);
1445 g_main_loop_quit (data->loop);
1449 * g_dbus_connection_send_message_with_reply_sync:
1450 * @connection: A #GDBusConnection.
1451 * @message: A #GDBusMessage.
1452 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1453 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1454 * @cancellable: A #GCancellable or %NULL.
1455 * @error: Return location for error or %NULL.
1457 * Synchronously sends @message to the peer represented by @connection
1458 * and blocks the calling thread until a reply is received or the
1459 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1460 * for the asynchronous version of this method.
1462 * If @out_serial is not %NULL, then the serial number assigned to
1463 * @message by @connection will be written to this location prior to
1464 * submitting the message to the underlying transport.
1466 * If @connection is closed then the operation will fail with
1467 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1468 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1469 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1471 * Note that @error is only set if a local in-process error
1472 * occured. That is to say that the returned #GDBusMessage object may
1473 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1474 * g_dbus_message_to_gerror() to transcode this to a #GError.
1476 * See <xref linkend="gdbus-server"/> and <xref
1477 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1478 * low-level API to send and receive UNIX file descriptors.
1480 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1485 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1486 GDBusMessage *message,
1488 volatile guint32 *out_serial,
1489 GCancellable *cancellable,
1492 SendMessageSyncData *data;
1493 GDBusMessage *reply;
1495 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1496 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1497 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1498 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1500 data = g_new0 (SendMessageSyncData, 1);
1501 data->context = g_main_context_new ();
1502 data->loop = g_main_loop_new (data->context, FALSE);
1504 g_main_context_push_thread_default (data->context);
1506 g_dbus_connection_send_message_with_reply (connection,
1511 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1513 g_main_loop_run (data->loop);
1514 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1518 g_main_context_pop_thread_default (data->context);
1520 g_main_context_unref (data->context);
1521 g_main_loop_unref (data->loop);
1522 g_object_unref (data->res);
1528 /* ---------------------------------------------------------------------------------------------------- */
1532 GDBusMessageFilterFunction func;
1539 GDBusMessageFilterFunction filter_function;
1541 GDestroyNotify user_data_free_func;
1544 /* Called in worker's thread - we must not block */
1546 on_worker_message_received (GDBusWorker *worker,
1547 GDBusMessage *message,
1550 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1551 FilterCallback *filters;
1552 gboolean consumed_by_filter;
1556 //g_debug ("in on_worker_message_received");
1558 g_object_ref (connection);
1560 /* First collect the set of callback functions */
1561 CONNECTION_LOCK (connection);
1562 num_filters = connection->priv->filters->len;
1563 filters = g_new0 (FilterCallback, num_filters);
1564 for (n = 0; n < num_filters; n++)
1566 FilterData *data = connection->priv->filters->pdata[n];
1567 filters[n].func = data->filter_function;
1568 filters[n].user_data = data->user_data;
1570 CONNECTION_UNLOCK (connection);
1572 /* the call the filters in order (without holding the lock) */
1573 consumed_by_filter = FALSE;
1574 for (n = 0; n < num_filters; n++)
1576 consumed_by_filter = filters[n].func (connection,
1578 filters[n].user_data);
1579 if (consumed_by_filter)
1583 /* Standard dispatch unless the filter ate the message */
1584 if (!consumed_by_filter)
1586 GDBusMessageType message_type;
1588 message_type = g_dbus_message_get_message_type (message);
1589 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1591 guint32 reply_serial;
1592 SendMessageData *send_message_data;
1594 reply_serial = g_dbus_message_get_reply_serial (message);
1595 CONNECTION_LOCK (connection);
1596 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1597 GUINT_TO_POINTER (reply_serial));
1598 if (send_message_data != NULL)
1600 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1601 send_message_data_deliver_reply_unlocked (send_message_data, message);
1605 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1607 CONNECTION_UNLOCK (connection);
1609 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1611 CONNECTION_LOCK (connection);
1612 distribute_signals (connection, message);
1613 CONNECTION_UNLOCK (connection);
1615 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1617 CONNECTION_LOCK (connection);
1618 distribute_method_call (connection, message);
1619 CONNECTION_UNLOCK (connection);
1623 g_object_unref (connection);
1627 /* Called in worker's thread - we must not block */
1629 on_worker_closed (GDBusWorker *worker,
1630 gboolean remote_peer_vanished,
1634 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1636 //g_debug ("in on_worker_closed: %s", error->message);
1638 CONNECTION_LOCK (connection);
1639 if (!connection->priv->closed)
1640 set_closed_unlocked (connection, remote_peer_vanished, error);
1641 CONNECTION_UNLOCK (connection);
1644 /* ---------------------------------------------------------------------------------------------------- */
1646 /* Determines the biggest set of capabilities we can support on this connection */
1647 static GDBusCapabilityFlags
1648 get_offered_capabilities_max (GDBusConnection *connection)
1650 GDBusCapabilityFlags ret;
1651 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1653 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1654 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1660 initable_init (GInitable *initable,
1661 GCancellable *cancellable,
1664 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1667 /* This method needs to be idempotent to work with the singleton
1668 * pattern. See the docs for g_initable_init(). We implement this by
1671 * Unfortunately we can't use the main lock since the on_worker_*()
1672 * callbacks above needs the lock during initialization (for message
1673 * bus connections we do a synchronous Hello() call on the bus).
1675 g_mutex_lock (connection->priv->init_lock);
1679 if (connection->priv->is_initialized)
1681 if (connection->priv->stream != NULL)
1684 g_assert (connection->priv->initialization_error != NULL);
1687 g_assert (connection->priv->initialization_error == NULL);
1689 /* The user can pass multiple (but mutally exclusive) construct
1692 * - stream (of type GIOStream)
1693 * - address (of type gchar*)
1695 * At the end of the day we end up with a non-NULL GIOStream
1696 * object in connection->priv->stream.
1698 if (connection->priv->address != NULL)
1700 g_assert (connection->priv->stream == NULL);
1702 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1703 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1705 g_set_error_literal (error,
1707 G_IO_ERROR_INVALID_ARGUMENT,
1708 _("Unsupported flags encountered when constructing a client-side connection"));
1712 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1713 NULL, /* TODO: out_guid */
1715 &connection->priv->initialization_error);
1716 if (connection->priv->stream == NULL)
1719 else if (connection->priv->stream != NULL)
1725 g_assert_not_reached ();
1728 /* Authenticate the connection */
1729 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1731 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1732 g_assert (connection->priv->guid != NULL);
1733 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1734 if (!_g_dbus_auth_run_server (connection->priv->auth,
1735 connection->priv->authentication_observer,
1736 connection->priv->guid,
1737 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1738 get_offered_capabilities_max (connection),
1739 &connection->priv->capabilities,
1740 &connection->priv->crendentials,
1742 &connection->priv->initialization_error))
1745 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1747 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1748 g_assert (connection->priv->guid == NULL);
1749 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1750 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1751 get_offered_capabilities_max (connection),
1752 &connection->priv->capabilities,
1754 &connection->priv->initialization_error);
1755 if (connection->priv->guid == NULL)
1759 if (connection->priv->authentication_observer != NULL)
1761 g_object_unref (connection->priv->authentication_observer);
1762 connection->priv->authentication_observer = NULL;
1765 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1767 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1771 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1775 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1777 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1780 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1781 connection->priv->capabilities,
1782 on_worker_message_received,
1786 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1787 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1789 GVariant *hello_result;
1792 hello_result = g_dbus_connection_call_sync (connection,
1793 "org.freedesktop.DBus", /* name */
1794 "/org/freedesktop/DBus", /* path */
1795 "org.freedesktop.DBus", /* interface */
1797 NULL, /* parameters */
1798 G_DBUS_CALL_FLAGS_NONE,
1800 NULL, /* TODO: cancellable */
1801 &connection->priv->initialization_error);
1802 if (hello_result == NULL)
1805 g_variant_get (hello_result, "(s)", &s);
1806 connection->priv->bus_unique_name = g_strdup (s);
1807 g_variant_unref (hello_result);
1808 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1811 connection->priv->is_initialized = TRUE;
1817 g_assert (connection->priv->initialization_error != NULL);
1818 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1821 g_mutex_unlock (connection->priv->init_lock);
1827 initable_iface_init (GInitableIface *initable_iface)
1829 initable_iface->init = initable_init;
1832 /* ---------------------------------------------------------------------------------------------------- */
1835 async_init_thread (GSimpleAsyncResult *res,
1837 GCancellable *cancellable)
1839 GError *error = NULL;
1841 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1843 g_simple_async_result_set_from_error (res, error);
1844 g_error_free (error);
1849 async_initable_init_async (GAsyncInitable *initable,
1851 GCancellable *cancellable,
1852 GAsyncReadyCallback callback,
1855 GSimpleAsyncResult *res;
1857 g_return_if_fail (G_IS_INITABLE (initable));
1859 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1860 async_initable_init_async);
1861 g_simple_async_result_run_in_thread (res, async_init_thread,
1862 io_priority, cancellable);
1863 g_object_unref (res);
1867 async_initable_init_finish (GAsyncInitable *initable,
1871 return TRUE; /* Errors handled by base impl */
1875 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1877 /* We basically just want to use GIO's default implementation - though that one is
1878 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1880 async_initable_iface->init_async = async_initable_init_async;
1881 async_initable_iface->init_finish = async_initable_init_finish;
1884 /* ---------------------------------------------------------------------------------------------------- */
1887 * g_dbus_connection_new:
1888 * @stream: A #GIOStream.
1889 * @guid: The GUID to use if a authenticating as a server or %NULL.
1890 * @flags: Flags describing how to make the connection.
1891 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1892 * @cancellable: A #GCancellable or %NULL.
1893 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1894 * @user_data: The data to pass to @callback.
1896 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1897 * with the end represented by @stream.
1899 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1900 * @auth_observer (if not %NULL) is used to assist in the client
1901 * authentication process.
1903 * When the operation is finished, @callback will be invoked. You can
1904 * then call g_dbus_connection_new_finish() to get the result of the
1907 * This is a asynchronous failable constructor. See
1908 * g_dbus_connection_new_sync() for the synchronous
1914 g_dbus_connection_new (GIOStream *stream,
1916 GDBusConnectionFlags flags,
1917 GDBusAuthObserver *authentication_observer,
1918 GCancellable *cancellable,
1919 GAsyncReadyCallback callback,
1922 g_return_if_fail (G_IS_IO_STREAM (stream));
1923 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1931 "authentication-observer", authentication_observer,
1936 * g_dbus_connection_new_finish:
1937 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1938 * @error: Return location for error or %NULL.
1940 * Finishes an operation started with g_dbus_connection_new().
1942 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1947 g_dbus_connection_new_finish (GAsyncResult *res,
1951 GObject *source_object;
1953 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1954 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1956 source_object = g_async_result_get_source_object (res);
1957 g_assert (source_object != NULL);
1958 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1961 g_object_unref (source_object);
1963 return G_DBUS_CONNECTION (object);
1969 * g_dbus_connection_new_sync:
1970 * @stream: A #GIOStream.
1971 * @guid: The GUID to use if a authenticating as a server or %NULL.
1972 * @flags: Flags describing how to make the connection.
1973 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1974 * @cancellable: A #GCancellable or %NULL.
1975 * @error: Return location for error or %NULL.
1977 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
1978 * with the end represented by @stream.
1980 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1981 * @auth_observer (if not %NULL) is used to assist in the client
1982 * authentication process.
1984 * This is a synchronous failable constructor. See
1985 * g_dbus_connection_new() for the asynchronous version.
1987 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1992 g_dbus_connection_new_sync (GIOStream *stream,
1994 GDBusConnectionFlags flags,
1995 GDBusAuthObserver *authentication_observer,
1996 GCancellable *cancellable,
1999 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2000 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2001 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2007 "authentication-observer", authentication_observer,
2011 /* ---------------------------------------------------------------------------------------------------- */
2014 * g_dbus_connection_new_for_address:
2015 * @address: A D-Bus address.
2016 * @flags: Flags describing how to make the connection.
2017 * @cancellable: A #GCancellable or %NULL.
2018 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2019 * @user_data: The data to pass to @callback.
2021 * Asynchronously connects and sets up a D-Bus client connection for
2022 * exchanging D-Bus messages with an endpoint specified by @address
2023 * which must be in the D-Bus address format.
2025 * This constructor can only be used to initiate client-side
2026 * connections - use g_dbus_connection_new() if you need to act as the
2027 * server. In particular, @flags cannot contain the
2028 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2029 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2031 * When the operation is finished, @callback will be invoked. You can
2032 * then call g_dbus_connection_new_finish() to get the result of the
2035 * This is a asynchronous failable constructor. See
2036 * g_dbus_connection_new_for_address_sync() for the synchronous
2042 g_dbus_connection_new_for_address (const gchar *address,
2043 GDBusConnectionFlags flags,
2044 GCancellable *cancellable,
2045 GAsyncReadyCallback callback,
2048 g_return_if_fail (address != NULL);
2049 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2060 * g_dbus_connection_new_for_address_finish:
2061 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2062 * @error: Return location for error or %NULL.
2064 * Finishes an operation started with g_dbus_connection_new_for_address().
2066 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2071 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2075 GObject *source_object;
2077 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2078 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2080 source_object = g_async_result_get_source_object (res);
2081 g_assert (source_object != NULL);
2082 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2085 g_object_unref (source_object);
2087 return G_DBUS_CONNECTION (object);
2093 * g_dbus_connection_new_for_address_sync:
2094 * @address: A D-Bus address.
2095 * @flags: Flags describing how to make the connection.
2096 * @cancellable: A #GCancellable or %NULL.
2097 * @error: Return location for error or %NULL.
2099 * Synchronously connects and sets up a D-Bus client connection for
2100 * exchanging D-Bus messages with an endpoint specified by @address
2101 * which must be in the D-Bus address format.
2103 * This constructor can only be used to initiate client-side
2104 * connections - use g_dbus_connection_new_sync() if you need to act
2105 * as the server. In particular, @flags cannot contain the
2106 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2107 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2109 * This is a synchronous failable constructor. See
2110 * g_dbus_connection_new_for_address() for the asynchronous version.
2112 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2117 g_dbus_connection_new_for_address_sync (const gchar *address,
2118 GDBusConnectionFlags flags,
2119 GCancellable *cancellable,
2122 g_return_val_if_fail (address != NULL, NULL);
2123 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2124 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2132 /* ---------------------------------------------------------------------------------------------------- */
2135 * g_dbus_connection_set_exit_on_close:
2136 * @connection: A #GDBusConnection.
2137 * @exit_on_close: Whether the process should be terminated
2138 * when @connection is closed by the remote peer.
2140 * Sets whether the process should be terminated when @connection is
2141 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2147 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2148 gboolean exit_on_close)
2150 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2151 connection->priv->exit_on_close = exit_on_close;
2155 * g_dbus_connection_get_exit_on_close:
2156 * @connection: A #GDBusConnection.
2158 * Gets whether the process is terminated when @connection is
2159 * closed by the remote peer. See
2160 * #GDBusConnection:exit-on-close for more details.
2162 * Returns: Whether the process is terminated when @connection is
2163 * closed by the remote peer.
2168 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2170 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2171 return connection->priv->exit_on_close;
2175 * g_dbus_connection_get_guid:
2176 * @connection: A #GDBusConnection.
2178 * The GUID of the peer performing the role of server when
2179 * authenticating. See #GDBusConnection:guid for more details.
2181 * Returns: The GUID. Do not free this string, it is owned by
2187 g_dbus_connection_get_guid (GDBusConnection *connection)
2189 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2190 return connection->priv->guid;
2194 * g_dbus_connection_get_unique_name:
2195 * @connection: A #GDBusConnection.
2197 * Gets the unique name of @connection as assigned by the message
2198 * bus. This can also be used to figure out if @connection is a
2199 * message bus connection.
2201 * Returns: The unique name or %NULL if @connection is not a message
2202 * bus connection. Do not free this string, it is owned by
2208 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2210 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2211 return connection->priv->bus_unique_name;
2215 * g_dbus_connection_get_peer_credentials:
2216 * @connection: A #GDBusConnection.
2218 * Gets the credentials of the authenticated peer. This will always
2219 * return %NULL unless @connection acted as a server
2220 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2221 * when set up and the client passed credentials as part of the
2222 * authentication process.
2224 * In a message bus setup, the message bus is always the server and
2225 * each application is a client. So this method will always return
2226 * %NULL for message bus clients.
2228 * Returns: A #GCredentials or %NULL if not available. Do not free
2229 * this object, it is owned by @connection.
2234 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2236 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2237 return connection->priv->crendentials;
2240 /* ---------------------------------------------------------------------------------------------------- */
2242 static guint _global_filter_id = 1;
2245 * g_dbus_connection_add_filter:
2246 * @connection: A #GDBusConnection.
2247 * @filter_function: A filter function.
2248 * @user_data: User data to pass to @filter_function.
2249 * @user_data_free_func: Function to free @user_data with when filter
2250 * is removed or %NULL.
2252 * Adds a message filter. Filters are handlers that are run on all
2253 * incoming messages, prior to standard dispatch. Filters are run in
2254 * the order that they were added. The same handler can be added as a
2255 * filter more than once, in which case it will be run more than once.
2256 * Filters added during a filter callback won't be run on the message
2259 * Note that filters are run in a dedicated message handling thread so
2260 * they can't block and, generally, can't do anything but signal a
2261 * worker thread. Also note that filters are rarely needed - use API
2262 * such as g_dbus_connection_send_message_with_reply(),
2263 * g_dbus_connection_signal_subscribe() or
2264 * g_dbus_connection_call() instead.
2266 * Returns: A filter identifier that can be used with
2267 * g_dbus_connection_remove_filter().
2272 g_dbus_connection_add_filter (GDBusConnection *connection,
2273 GDBusMessageFilterFunction filter_function,
2275 GDestroyNotify user_data_free_func)
2279 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2280 g_return_val_if_fail (filter_function != NULL, 0);
2282 CONNECTION_LOCK (connection);
2283 data = g_new0 (FilterData, 1);
2284 data->id = _global_filter_id++; /* TODO: overflow etc. */
2285 data->filter_function = filter_function;
2286 data->user_data = user_data;
2287 data->user_data_free_func = user_data_free_func;
2288 g_ptr_array_add (connection->priv->filters, data);
2289 CONNECTION_UNLOCK (connection);
2294 /* only called from finalize(), removes all filters */
2296 purge_all_filters (GDBusConnection *connection)
2299 for (n = 0; n < connection->priv->filters->len; n++)
2301 FilterData *data = connection->priv->filters->pdata[n];
2302 if (data->user_data_free_func != NULL)
2303 data->user_data_free_func (data->user_data);
2309 g_dbus_connection_remove_filter (GDBusConnection *connection,
2313 FilterData *to_destroy;
2315 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2317 CONNECTION_LOCK (connection);
2319 for (n = 0; n < connection->priv->filters->len; n++)
2321 FilterData *data = connection->priv->filters->pdata[n];
2322 if (data->id == filter_id)
2324 g_ptr_array_remove_index (connection->priv->filters, n);
2329 CONNECTION_UNLOCK (connection);
2331 /* do free without holding lock */
2332 if (to_destroy != NULL)
2334 if (to_destroy->user_data_free_func != NULL)
2335 to_destroy->user_data_free_func (to_destroy->user_data);
2336 g_free (to_destroy);
2340 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2344 /* ---------------------------------------------------------------------------------------------------- */
2350 gchar *interface_name;
2354 GArray *subscribers;
2359 GDBusSignalCallback callback;
2361 GDestroyNotify user_data_free_func;
2363 GMainContext *context;
2367 signal_data_free (SignalData *data)
2369 g_free (data->rule);
2370 g_free (data->sender);
2371 g_free (data->interface_name);
2372 g_free (data->member);
2373 g_free (data->object_path);
2374 g_free (data->arg0);
2375 g_array_free (data->subscribers, TRUE);
2380 args_to_rule (const gchar *sender,
2381 const gchar *interface_name,
2382 const gchar *member,
2383 const gchar *object_path,
2388 rule = g_string_new ("type='signal'");
2390 g_string_append_printf (rule, ",sender='%s'", sender);
2391 if (interface_name != NULL)
2392 g_string_append_printf (rule, ",interface='%s'", interface_name);
2394 g_string_append_printf (rule, ",member='%s'", member);
2395 if (object_path != NULL)
2396 g_string_append_printf (rule, ",path='%s'", object_path);
2398 g_string_append_printf (rule, ",arg0='%s'", arg0);
2400 return g_string_free (rule, FALSE);
2403 static guint _global_subscriber_id = 1;
2404 static guint _global_registration_id = 1;
2405 static guint _global_subtree_registration_id = 1;
2407 /* ---------------------------------------------------------------------------------------------------- */
2409 /* must hold lock when calling */
2411 add_match_rule (GDBusConnection *connection,
2412 const gchar *match_rule)
2415 GDBusMessage *message;
2417 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2418 "/org/freedesktop/DBus", /* path */
2419 "org.freedesktop.DBus", /* interface */
2421 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2424 if (!g_dbus_connection_send_message_unlocked (connection,
2429 g_critical ("Error while sending AddMatch() message: %s", error->message);
2430 g_error_free (error);
2432 g_object_unref (message);
2435 /* ---------------------------------------------------------------------------------------------------- */
2437 /* must hold lock when calling */
2439 remove_match_rule (GDBusConnection *connection,
2440 const gchar *match_rule)
2443 GDBusMessage *message;
2445 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2446 "/org/freedesktop/DBus", /* path */
2447 "org.freedesktop.DBus", /* interface */
2449 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2452 if (!g_dbus_connection_send_message_unlocked (connection,
2457 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2458 g_error_free (error);
2460 g_object_unref (message);
2463 /* ---------------------------------------------------------------------------------------------------- */
2466 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2468 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2469 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2470 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2471 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2472 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2475 /* ---------------------------------------------------------------------------------------------------- */
2478 * g_dbus_connection_signal_subscribe:
2479 * @connection: A #GDBusConnection.
2480 * @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.
2481 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2482 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2483 * @object_path: Object path to match on or %NULL to match on all object paths.
2484 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2485 * @callback: Callback to invoke when there is a signal matching the requested data.
2486 * @user_data: User data to pass to @callback.
2487 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2489 * Subscribes to signals on @connection and invokes @callback with a
2490 * whenever the signal is received. Note that @callback
2491 * will be invoked in the <link
2492 * linkend="g-main-context-push-thread-default">thread-default main
2493 * loop</link> of the thread you are calling this method from.
2495 * It is considered a programming error to use this function if @connection is closed.
2497 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2498 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2499 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2500 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2501 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2502 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2504 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2509 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2510 const gchar *sender,
2511 const gchar *interface_name,
2512 const gchar *member,
2513 const gchar *object_path,
2515 GDBusSignalCallback callback,
2517 GDestroyNotify user_data_free_func)
2520 SignalData *signal_data;
2521 SignalSubscriber subscriber;
2522 GPtrArray *signal_data_array;
2524 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2525 * an OOM condition. We might want to change that but that would involve making
2526 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2527 * handle that. And there's really no sensible way of handling this short of retrying
2528 * to add the match rule... and then there's the little thing that, hey, maybe there's
2529 * a reason the bus in an OOM condition.
2531 * Doable, but not really sure it's worth it...
2534 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2535 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2536 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2537 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2538 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2539 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2540 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2541 g_return_val_if_fail (callback != NULL, 0);
2543 CONNECTION_LOCK (connection);
2545 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2550 subscriber.callback = callback;
2551 subscriber.user_data = user_data;
2552 subscriber.user_data_free_func = user_data_free_func;
2553 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2554 subscriber.context = g_main_context_get_thread_default ();
2555 if (subscriber.context != NULL)
2556 g_main_context_ref (subscriber.context);
2558 /* see if we've already have this rule */
2559 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2560 if (signal_data != NULL)
2562 g_array_append_val (signal_data->subscribers, subscriber);
2567 signal_data = g_new0 (SignalData, 1);
2568 signal_data->rule = rule;
2569 signal_data->sender = g_strdup (sender);
2570 signal_data->interface_name = g_strdup (interface_name);
2571 signal_data->member = g_strdup (member);
2572 signal_data->object_path = g_strdup (object_path);
2573 signal_data->arg0 = g_strdup (arg0);
2574 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2575 g_array_append_val (signal_data->subscribers, subscriber);
2577 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2581 /* Add the match rule to the bus...
2583 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2584 * always send such messages to us.
2586 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2588 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2589 add_match_rule (connection, signal_data->rule);
2593 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2594 GUINT_TO_POINTER (subscriber.id),
2597 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2598 signal_data->sender);
2599 if (signal_data_array == NULL)
2601 signal_data_array = g_ptr_array_new ();
2602 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2603 g_strdup (signal_data->sender),
2606 g_ptr_array_add (signal_data_array, signal_data);
2608 CONNECTION_UNLOCK (connection);
2610 return subscriber.id;
2613 /* ---------------------------------------------------------------------------------------------------- */
2615 /* must hold lock when calling this */
2617 unsubscribe_id_internal (GDBusConnection *connection,
2618 guint subscription_id,
2619 GArray *out_removed_subscribers)
2621 SignalData *signal_data;
2622 GPtrArray *signal_data_array;
2625 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2626 GUINT_TO_POINTER (subscription_id));
2627 if (signal_data == NULL)
2629 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2633 for (n = 0; n < signal_data->subscribers->len; n++)
2635 SignalSubscriber *subscriber;
2637 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2638 if (subscriber->id != subscription_id)
2641 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2642 GUINT_TO_POINTER (subscription_id)));
2643 g_array_append_val (out_removed_subscribers, *subscriber);
2644 g_array_remove_index (signal_data->subscribers, n);
2646 if (signal_data->subscribers->len == 0)
2647 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2649 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2650 signal_data->sender);
2651 g_warn_if_fail (signal_data_array != NULL);
2652 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2654 if (signal_data_array->len == 0)
2656 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2658 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2659 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2661 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2662 remove_match_rule (connection, signal_data->rule);
2665 signal_data_free (signal_data);
2671 g_assert_not_reached ();
2678 * g_dbus_connection_signal_unsubscribe:
2679 * @connection: A #GDBusConnection.
2680 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2682 * Unsubscribes from signals.
2687 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2688 guint subscription_id)
2690 GArray *subscribers;
2693 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2695 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2697 CONNECTION_LOCK (connection);
2698 unsubscribe_id_internal (connection,
2701 CONNECTION_UNLOCK (connection);
2704 g_assert (subscribers->len == 0 || subscribers->len == 1);
2706 /* call GDestroyNotify without lock held */
2707 for (n = 0; n < subscribers->len; n++)
2709 SignalSubscriber *subscriber;
2710 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2711 if (subscriber->user_data_free_func != NULL)
2712 subscriber->user_data_free_func (subscriber->user_data);
2713 if (subscriber->context != NULL)
2714 g_main_context_unref (subscriber->context);
2717 g_array_free (subscribers, TRUE);
2720 /* ---------------------------------------------------------------------------------------------------- */
2724 guint subscription_id;
2725 GDBusSignalCallback callback;
2727 GDBusMessage *message;
2728 GDBusConnection *connection;
2729 const gchar *sender;
2731 const gchar *interface;
2732 const gchar *member;
2735 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2739 emit_signal_instance_in_idle_cb (gpointer data)
2741 SignalInstance *signal_instance = data;
2742 GVariant *parameters;
2743 gboolean has_subscription;
2745 parameters = g_dbus_message_get_body (signal_instance->message);
2746 if (parameters == NULL)
2748 parameters = g_variant_new ("()");
2749 g_variant_ref_sink (parameters);
2753 g_variant_ref_sink (parameters);
2757 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2758 signal_instance->sender,
2759 signal_instance->path,
2760 signal_instance->interface,
2761 signal_instance->member,
2762 g_variant_print (parameters, TRUE));
2765 /* Careful here, don't do the callback if we no longer has the subscription */
2766 CONNECTION_LOCK (signal_instance->connection);
2767 has_subscription = FALSE;
2768 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2769 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2770 has_subscription = TRUE;
2771 CONNECTION_UNLOCK (signal_instance->connection);
2773 if (has_subscription)
2774 signal_instance->callback (signal_instance->connection,
2775 signal_instance->sender,
2776 signal_instance->path,
2777 signal_instance->interface,
2778 signal_instance->member,
2780 signal_instance->user_data);
2782 if (parameters != NULL)
2783 g_variant_unref (parameters);
2789 signal_instance_free (SignalInstance *signal_instance)
2791 g_object_unref (signal_instance->message);
2792 g_object_unref (signal_instance->connection);
2793 g_free (signal_instance);
2796 /* called in message handler thread WITH lock held */
2798 schedule_callbacks (GDBusConnection *connection,
2799 GPtrArray *signal_data_array,
2800 GDBusMessage *message,
2801 const gchar *sender)
2804 const gchar *interface;
2805 const gchar *member;
2814 interface = g_dbus_message_get_interface (message);
2815 member = g_dbus_message_get_member (message);
2816 path = g_dbus_message_get_path (message);
2817 arg0 = g_dbus_message_get_arg0 (message);
2820 g_debug ("sender = `%s'", sender);
2821 g_debug ("interface = `%s'", interface);
2822 g_debug ("member = `%s'", member);
2823 g_debug ("path = `%s'", path);
2824 g_debug ("arg0 = `%s'", arg0);
2827 /* TODO: if this is slow, then we can change signal_data_array into
2828 * map_object_path_to_signal_data_array or something.
2830 for (n = 0; n < signal_data_array->len; n++)
2832 SignalData *signal_data = signal_data_array->pdata[n];
2834 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2837 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2840 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2843 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2846 for (m = 0; m < signal_data->subscribers->len; m++)
2848 SignalSubscriber *subscriber;
2849 GSource *idle_source;
2850 SignalInstance *signal_instance;
2852 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2854 signal_instance = g_new0 (SignalInstance, 1);
2855 signal_instance->subscription_id = subscriber->id;
2856 signal_instance->callback = subscriber->callback;
2857 signal_instance->user_data = subscriber->user_data;
2858 signal_instance->message = g_object_ref (message);
2859 signal_instance->connection = g_object_ref (connection);
2860 signal_instance->sender = sender;
2861 signal_instance->path = path;
2862 signal_instance->interface = interface;
2863 signal_instance->member = member;
2865 idle_source = g_idle_source_new ();
2866 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2867 g_source_set_callback (idle_source,
2868 emit_signal_instance_in_idle_cb,
2870 (GDestroyNotify) signal_instance_free);
2871 g_source_attach (idle_source, subscriber->context);
2872 g_source_unref (idle_source);
2877 /* called in message handler thread with lock held */
2879 distribute_signals (GDBusConnection *connection,
2880 GDBusMessage *message)
2882 GPtrArray *signal_data_array;
2883 const gchar *sender;
2885 sender = g_dbus_message_get_sender (message);
2887 /* collect subscribers that match on sender */
2890 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2891 if (signal_data_array != NULL)
2892 schedule_callbacks (connection, signal_data_array, message, sender);
2895 /* collect subscribers not matching on sender */
2896 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2897 if (signal_data_array != NULL)
2898 schedule_callbacks (connection, signal_data_array, message, sender);
2901 /* ---------------------------------------------------------------------------------------------------- */
2903 /* only called from finalize(), removes all subscriptions */
2905 purge_all_signal_subscriptions (GDBusConnection *connection)
2907 GHashTableIter iter;
2910 GArray *subscribers;
2913 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2914 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2915 while (g_hash_table_iter_next (&iter, &key, NULL))
2917 guint subscription_id = GPOINTER_TO_UINT (key);
2918 g_array_append_val (ids, subscription_id);
2921 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2922 for (n = 0; n < ids->len; n++)
2924 guint subscription_id = g_array_index (ids, guint, n);
2925 unsubscribe_id_internal (connection,
2929 g_array_free (ids, TRUE);
2931 /* call GDestroyNotify without lock held */
2932 for (n = 0; n < subscribers->len; n++)
2934 SignalSubscriber *subscriber;
2935 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2936 if (subscriber->user_data_free_func != NULL)
2937 subscriber->user_data_free_func (subscriber->user_data);
2938 if (subscriber->context != NULL)
2939 g_main_context_unref (subscriber->context);
2942 g_array_free (subscribers, TRUE);
2945 /* ---------------------------------------------------------------------------------------------------- */
2947 struct ExportedObject
2950 GDBusConnection *connection;
2952 /* maps gchar* -> ExportedInterface* */
2953 GHashTable *map_if_name_to_ei;
2956 /* only called with lock held */
2958 exported_object_free (ExportedObject *eo)
2960 g_free (eo->object_path);
2961 g_hash_table_unref (eo->map_if_name_to_ei);
2970 gchar *interface_name;
2971 const GDBusInterfaceVTable *vtable;
2972 const GDBusInterfaceInfo *introspection_data;
2974 GMainContext *context;
2976 GDestroyNotify user_data_free_func;
2977 } ExportedInterface;
2979 /* called with lock held */
2981 exported_interface_free (ExportedInterface *ei)
2983 if (ei->user_data_free_func != NULL)
2984 /* TODO: push to thread-default mainloop */
2985 ei->user_data_free_func (ei->user_data);
2987 if (ei->context != NULL)
2988 g_main_context_unref (ei->context);
2990 g_free (ei->interface_name);
2994 /* ---------------------------------------------------------------------------------------------------- */
2998 GDBusConnection *connection;
2999 GDBusMessage *message;
3001 const char *property_name;
3002 const GDBusInterfaceVTable *vtable;
3003 const GDBusInterfaceInfo *interface_info;
3004 const GDBusPropertyInfo *property_info;
3008 property_data_free (PropertyData *data)
3010 g_object_unref (data->connection);
3011 g_object_unref (data->message);
3015 /* called in thread where object was registered - no locks held */
3017 invoke_get_property_in_idle_cb (gpointer _data)
3019 PropertyData *data = _data;
3022 GDBusMessage *reply;
3025 value = data->vtable->get_property (data->connection,
3026 g_dbus_message_get_sender (data->message),
3027 g_dbus_message_get_path (data->message),
3028 data->interface_info->name,
3029 data->property_name,
3036 g_assert_no_error (error);
3038 g_variant_ref_sink (value);
3039 reply = g_dbus_message_new_method_reply (data->message);
3040 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3041 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3042 g_variant_unref (value);
3043 g_object_unref (reply);
3047 gchar *dbus_error_name;
3049 g_assert (error != NULL);
3051 dbus_error_name = g_dbus_error_encode_gerror (error);
3052 reply = g_dbus_message_new_method_error_literal (data->message,
3055 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3056 g_free (dbus_error_name);
3057 g_error_free (error);
3058 g_object_unref (reply);
3064 /* called in thread where object was registered - no locks held */
3066 invoke_set_property_in_idle_cb (gpointer _data)
3068 PropertyData *data = _data;
3070 GDBusMessage *reply;
3076 g_variant_get (g_dbus_message_get_body (data->message),
3082 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3083 * of the given value is wrong
3085 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3087 reply = g_dbus_message_new_method_error (data->message,
3088 "org.freedesktop.DBus.Error.InvalidArgs",
3089 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3090 data->property_info->name,
3091 data->property_info->signature,
3092 g_variant_get_type_string (value));
3096 if (!data->vtable->set_property (data->connection,
3097 g_dbus_message_get_sender (data->message),
3098 g_dbus_message_get_path (data->message),
3099 data->interface_info->name,
3100 data->property_name,
3105 gchar *dbus_error_name;
3106 g_assert (error != NULL);
3107 dbus_error_name = g_dbus_error_encode_gerror (error);
3108 reply = g_dbus_message_new_method_error_literal (data->message,
3111 g_free (dbus_error_name);
3112 g_error_free (error);
3116 reply = g_dbus_message_new_method_reply (data->message);
3120 g_assert (reply != NULL);
3121 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3122 g_object_unref (reply);
3127 /* called with lock held */
3129 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3130 GDBusMessage *message,
3132 const GDBusInterfaceInfo *introspection_data,
3133 const GDBusInterfaceVTable *vtable,
3134 GMainContext *main_context,
3138 const char *interface_name;
3139 const char *property_name;
3140 const GDBusPropertyInfo *property_info;
3141 GSource *idle_source;
3142 PropertyData *property_data;
3143 GDBusMessage *reply;
3148 g_variant_get (g_dbus_message_get_body (message),
3153 g_variant_get (g_dbus_message_get_body (message),
3162 if (vtable == NULL || vtable->get_property == NULL)
3167 if (vtable == NULL || vtable->set_property == NULL)
3171 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3173 property_info = NULL;
3175 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3176 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3177 if (property_info == NULL)
3179 reply = g_dbus_message_new_method_error (message,
3180 "org.freedesktop.DBus.Error.InvalidArgs",
3181 _("No such property `%s'"),
3183 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3184 g_object_unref (reply);
3189 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3191 reply = g_dbus_message_new_method_error (message,
3192 "org.freedesktop.DBus.Error.InvalidArgs",
3193 _("Property `%s' is not readable"),
3195 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3196 g_object_unref (reply);
3200 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3202 reply = g_dbus_message_new_method_error (message,
3203 "org.freedesktop.DBus.Error.InvalidArgs",
3204 _("Property `%s' is not writable"),
3206 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3207 g_object_unref (reply);
3212 /* ok, got the property info - call user code in an idle handler */
3213 property_data = g_new0 (PropertyData, 1);
3214 property_data->connection = g_object_ref (connection);
3215 property_data->message = g_object_ref (message);
3216 property_data->user_data = user_data;
3217 property_data->property_name = property_name;
3218 property_data->vtable = vtable;
3219 property_data->interface_info = introspection_data;
3220 property_data->property_info = property_info;
3222 idle_source = g_idle_source_new ();
3223 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3224 g_source_set_callback (idle_source,
3225 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3227 (GDestroyNotify) property_data_free);
3228 g_source_attach (idle_source, main_context);
3229 g_source_unref (idle_source);
3237 /* called with lock held */
3239 handle_getset_property (GDBusConnection *connection,
3241 GDBusMessage *message,
3244 ExportedInterface *ei;
3246 const char *interface_name;
3247 const char *property_name;
3252 g_variant_get (g_dbus_message_get_body (message),
3257 g_variant_get (g_dbus_message_get_body (message),
3263 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3264 * no such interface registered
3266 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3269 GDBusMessage *reply;
3270 reply = g_dbus_message_new_method_error (message,
3271 "org.freedesktop.DBus.Error.InvalidArgs",
3272 _("No such interface `%s'"),
3274 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3275 g_object_unref (reply);
3280 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3283 ei->introspection_data,
3291 /* ---------------------------------------------------------------------------------------------------- */
3295 GDBusConnection *connection;
3296 GDBusMessage *message;
3298 const GDBusInterfaceVTable *vtable;
3299 const GDBusInterfaceInfo *interface_info;
3300 } PropertyGetAllData;
3303 property_get_all_data_free (PropertyData *data)
3305 g_object_unref (data->connection);
3306 g_object_unref (data->message);
3310 /* called in thread where object was registered - no locks held */
3312 invoke_get_all_properties_in_idle_cb (gpointer _data)
3314 PropertyGetAllData *data = _data;
3315 GVariantBuilder *builder;
3319 GDBusMessage *reply;
3324 /* TODO: Right now we never fail this call - we just omit values if
3325 * a get_property() call is failing.
3327 * We could fail the whole call if just a single get_property() call
3328 * returns an error. We need clarification in the D-Bus spec about this.
3330 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3331 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3333 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3336 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3339 value = data->vtable->get_property (data->connection,
3340 g_dbus_message_get_sender (data->message),
3341 g_dbus_message_get_path (data->message),
3342 data->interface_info->name,
3343 property_info->name,
3350 g_variant_ref_sink (value);
3351 g_variant_builder_add (builder,
3353 property_info->name,
3355 g_variant_unref (value);
3357 result = g_variant_builder_end (builder);
3359 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3360 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3361 packed = g_variant_builder_end (builder);
3363 reply = g_dbus_message_new_method_reply (data->message);
3364 g_dbus_message_set_body (reply, packed);
3365 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3366 g_object_unref (reply);
3371 /* called with lock held */
3373 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3374 GDBusMessage *message,
3375 const GDBusInterfaceInfo *introspection_data,
3376 const GDBusInterfaceVTable *vtable,
3377 GMainContext *main_context,
3381 const char *interface_name;
3382 GSource *idle_source;
3383 PropertyGetAllData *property_get_all_data;
3387 g_variant_get (g_dbus_message_get_body (message),
3391 if (vtable == NULL || vtable->get_property == NULL)
3394 /* ok, got the property info - call user in an idle handler */
3395 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3396 property_get_all_data->connection = g_object_ref (connection);
3397 property_get_all_data->message = g_object_ref (message);
3398 property_get_all_data->user_data = user_data;
3399 property_get_all_data->vtable = vtable;
3400 property_get_all_data->interface_info = introspection_data;
3402 idle_source = g_idle_source_new ();
3403 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3404 g_source_set_callback (idle_source,
3405 invoke_get_all_properties_in_idle_cb,
3406 property_get_all_data,
3407 (GDestroyNotify) property_get_all_data_free);
3408 g_source_attach (idle_source, main_context);
3409 g_source_unref (idle_source);
3417 /* called with lock held */
3419 handle_get_all_properties (GDBusConnection *connection,
3421 GDBusMessage *message)
3423 ExportedInterface *ei;
3425 const char *interface_name;
3429 g_variant_get (g_dbus_message_get_body (message),
3433 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3434 * no such interface registered
3436 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3439 GDBusMessage *reply;
3440 reply = g_dbus_message_new_method_error (message,
3441 "org.freedesktop.DBus.Error.InvalidArgs",
3442 _("No such interface"),
3444 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3445 g_object_unref (reply);
3450 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3452 ei->introspection_data,
3460 /* ---------------------------------------------------------------------------------------------------- */
3462 static const gchar introspect_header[] =
3463 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3464 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3465 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3468 static const gchar introspect_tail[] =
3471 static const gchar introspect_standard_interfaces[] =
3472 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3473 " <method name=\"Get\">\n"
3474 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3475 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3476 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3478 " <method name=\"GetAll\">\n"
3479 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3480 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3482 " <method name=\"Set\">\n"
3483 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3484 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3485 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3487 " <signal name=\"PropertiesChanged\">\n"
3488 " <arg type=\"s\" name=\"interface_name\"/>\n"
3489 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3492 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3493 " <method name=\"Introspect\">\n"
3494 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3497 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3498 " <method name=\"Ping\"/>\n"
3499 " <method name=\"GetMachineId\">\n"
3500 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3505 introspect_append_header (GString *s)
3507 g_string_append (s, introspect_header);
3511 introspect_append_standard_interfaces (GString *s)
3513 g_string_append (s, introspect_standard_interfaces);
3517 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3519 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3525 begin = object_path + path_len;
3526 end = strchr (begin, '/');
3529 s = g_strndup (begin, end - begin);
3531 s = g_strdup (begin);
3533 if (g_hash_table_lookup (set, s) == NULL)
3534 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3540 /* TODO: we want a nicer public interface for this */
3542 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3547 GHashTableIter hash_iter;
3548 const gchar *object_path;
3554 CONNECTION_ENSURE_LOCK (connection);
3556 path_len = strlen (path);
3560 set = g_hash_table_new (g_str_hash, g_str_equal);
3562 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3563 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3564 maybe_add_path (path, path_len, object_path, set);
3566 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3567 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3568 maybe_add_path (path, path_len, object_path, set);
3570 p = g_ptr_array_new ();
3571 keys = g_hash_table_get_keys (set);
3572 for (l = keys; l != NULL; l = l->next)
3573 g_ptr_array_add (p, l->data);
3574 g_hash_table_unref (set);
3577 g_ptr_array_add (p, NULL);
3578 ret = (gchar **) g_ptr_array_free (p, FALSE);
3583 g_dbus_connection_list_registered (GDBusConnection *connection,
3587 CONNECTION_LOCK (connection);
3588 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3589 CONNECTION_UNLOCK (connection);
3593 /* called in message handler thread with lock held */
3595 handle_introspect (GDBusConnection *connection,
3597 GDBusMessage *message)
3601 GDBusMessage *reply;
3602 GHashTableIter hash_iter;
3603 ExportedInterface *ei;
3606 /* first the header with the standard interfaces */
3607 s = g_string_sized_new (sizeof (introspect_header) +
3608 sizeof (introspect_standard_interfaces) +
3609 sizeof (introspect_tail));
3610 introspect_append_header (s);
3611 introspect_append_standard_interfaces (s);
3613 /* then include the registered interfaces */
3614 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3615 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3616 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3618 /* finally include nodes registered below us */
3619 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3620 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3621 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3622 g_strfreev (registered);
3623 g_string_append (s, introspect_tail);
3625 reply = g_dbus_message_new_method_reply (message);
3626 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3627 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3628 g_object_unref (reply);
3629 g_string_free (s, TRUE);
3634 /* called in thread where object was registered - no locks held */
3636 call_in_idle_cb (gpointer user_data)
3638 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3639 GDBusInterfaceVTable *vtable;
3641 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3642 g_assert (vtable != NULL && vtable->method_call != NULL);
3644 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3645 g_dbus_method_invocation_get_sender (invocation),
3646 g_dbus_method_invocation_get_object_path (invocation),
3647 g_dbus_method_invocation_get_interface_name (invocation),
3648 g_dbus_method_invocation_get_method_name (invocation),
3649 g_dbus_method_invocation_get_parameters (invocation),
3650 g_object_ref (invocation),
3651 g_dbus_method_invocation_get_user_data (invocation));
3656 /* called in message handler thread with lock held */
3658 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3659 GDBusMessage *message,
3660 const GDBusInterfaceInfo *introspection_data,
3661 const GDBusInterfaceVTable *vtable,
3662 GMainContext *main_context,
3665 GDBusMethodInvocation *invocation;
3666 const GDBusMethodInfo *method_info;
3667 GDBusMessage *reply;
3668 GVariant *parameters;
3669 GSource *idle_source;
3671 gchar *in_signature;
3675 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3676 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3678 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3679 * error to the caller
3681 if (method_info == NULL)
3683 reply = g_dbus_message_new_method_error (message,
3684 "org.freedesktop.DBus.Error.UnknownMethod",
3685 _("No such method `%s'"),
3686 g_dbus_message_get_member (message));
3687 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3688 g_object_unref (reply);
3693 /* Check that the incoming args are of the right type - if they are not, return
3694 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3696 * TODO: might also be worth caching the combined signature.
3698 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3699 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3701 reply = g_dbus_message_new_method_error (message,
3702 "org.freedesktop.DBus.Error.InvalidArgs",
3703 _("Signature of message, `%s', does not match expected signature `%s'"),
3704 g_dbus_message_get_signature (message),
3706 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3707 g_object_unref (reply);
3708 g_free (in_signature);
3712 g_free (in_signature);
3714 parameters = g_dbus_message_get_body (message);
3715 if (parameters == NULL)
3717 parameters = g_variant_new ("()");
3718 g_variant_ref_sink (parameters);
3722 g_variant_ref (parameters);
3725 /* schedule the call in idle */
3726 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3727 g_dbus_message_get_path (message),
3728 g_dbus_message_get_interface (message),
3729 g_dbus_message_get_member (message),
3735 g_variant_unref (parameters);
3736 g_object_set_data (G_OBJECT (invocation),
3737 "g-dbus-interface-vtable",
3740 idle_source = g_idle_source_new ();
3741 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3742 g_source_set_callback (idle_source,
3746 g_source_attach (idle_source, main_context);
3747 g_source_unref (idle_source);
3755 /* ---------------------------------------------------------------------------------------------------- */
3757 /* called in message handler thread with lock held */
3759 obj_message_func (GDBusConnection *connection,
3761 GDBusMessage *message)
3763 const gchar *interface_name;
3764 const gchar *member;
3765 const gchar *signature;
3770 interface_name = g_dbus_message_get_interface (message);
3771 member = g_dbus_message_get_member (message);
3772 signature = g_dbus_message_get_signature (message);
3774 /* see if we have an interface for handling this call */
3775 if (interface_name != NULL)
3777 ExportedInterface *ei;
3778 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3781 /* we do - invoke the handler in idle in the right thread */
3783 /* handle no vtable or handler being present */
3784 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3787 handled = validate_and_maybe_schedule_method_call (connection,
3789 ei->introspection_data,
3797 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3798 g_strcmp0 (member, "Introspect") == 0 &&
3799 g_strcmp0 (signature, "") == 0)
3801 handled = handle_introspect (connection, eo, message);
3804 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3805 g_strcmp0 (member, "Get") == 0 &&
3806 g_strcmp0 (signature, "ss") == 0)
3808 handled = handle_getset_property (connection, eo, message, TRUE);
3811 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3812 g_strcmp0 (member, "Set") == 0 &&
3813 g_strcmp0 (signature, "ssv") == 0)
3815 handled = handle_getset_property (connection, eo, message, FALSE);
3818 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3819 g_strcmp0 (member, "GetAll") == 0 &&
3820 g_strcmp0 (signature, "s") == 0)
3822 handled = handle_get_all_properties (connection, eo, message);
3831 * g_dbus_connection_register_object:
3832 * @connection: A #GDBusConnection.
3833 * @object_path: The object path to register at.
3834 * @interface_name: The D-Bus interface to register.
3835 * @introspection_data: Introspection data for the interface.
3836 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3837 * @user_data: Data to pass to functions in @vtable.
3838 * @user_data_free_func: Function to call when the object path is unregistered.
3839 * @error: Return location for error or %NULL.
3841 * Registers callbacks for exported objects at @object_path with the
3842 * D-Bus interface @interface_name.
3844 * Calls to functions in @vtable (and @user_data_free_func) will
3845 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3846 * loop</link> of the thread you are calling this method from.
3848 * Note that all #GVariant values passed to functions in @vtable will match
3849 * the signature given in @introspection_data - if a remote caller passes
3850 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3851 * is returned to the remote caller.
3853 * Additionally, if the remote caller attempts to invoke methods or
3854 * access properties not mentioned in @introspection_data the
3855 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3856 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3857 * are returned to the caller.
3859 * It is considered a programming error if the
3860 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3861 * #GVariant of incorrect type.
3863 * If an existing callback is already registered at @object_path and
3864 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3866 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3868 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3869 * that can be used with g_dbus_connection_unregister_object() .
3874 g_dbus_connection_register_object (GDBusConnection *connection,
3875 const gchar *object_path,
3876 const gchar *interface_name,
3877 const GDBusInterfaceInfo *introspection_data,
3878 const GDBusInterfaceVTable *vtable,
3880 GDestroyNotify user_data_free_func,
3884 ExportedInterface *ei;
3887 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3888 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3889 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3890 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3891 g_return_val_if_fail (introspection_data != NULL, 0);
3892 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3896 CONNECTION_LOCK (connection);
3898 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3901 eo = g_new0 (ExportedObject, 1);
3902 eo->object_path = g_strdup (object_path);
3903 eo->connection = connection;
3904 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3907 (GDestroyNotify) exported_interface_free);
3908 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3911 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3917 _("An object is already exported for the interface %s at %s"),
3923 ei = g_new0 (ExportedInterface, 1);
3924 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3926 ei->user_data = user_data;
3927 ei->user_data_free_func = user_data_free_func;
3928 ei->vtable = vtable;
3929 ei->introspection_data = introspection_data;
3930 ei->interface_name = g_strdup (interface_name);
3931 ei->context = g_main_context_get_thread_default ();
3932 if (ei->context != NULL)
3933 g_main_context_ref (ei->context);
3935 g_hash_table_insert (eo->map_if_name_to_ei,
3936 (gpointer) ei->interface_name,
3938 g_hash_table_insert (connection->priv->map_id_to_ei,
3939 GUINT_TO_POINTER (ei->id),
3945 CONNECTION_UNLOCK (connection);
3951 * g_dbus_connection_unregister_object:
3952 * @connection: A #GDBusConnection.
3953 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3955 * Unregisters an object.
3957 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3962 g_dbus_connection_unregister_object (GDBusConnection *connection,
3963 guint registration_id)
3965 ExportedInterface *ei;
3969 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3973 CONNECTION_LOCK (connection);
3975 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
3976 GUINT_TO_POINTER (registration_id));
3982 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
3983 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
3984 /* unregister object path if we have no more exported interfaces */
3985 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
3986 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
3992 CONNECTION_UNLOCK (connection);
3997 /* ---------------------------------------------------------------------------------------------------- */
4000 * g_dbus_connection_emit_signal:
4001 * @connection: A #GDBusConnection.
4002 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4003 * @object_path: Path of remote object.
4004 * @interface_name: D-Bus interface to emit a signal on.
4005 * @signal_name: The name of the signal to emit.
4006 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4007 * @error: Return location for error or %NULL.
4011 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4013 * Returns: %TRUE unless @error is set.
4018 g_dbus_connection_emit_signal (GDBusConnection *connection,
4019 const gchar *destination_bus_name,
4020 const gchar *object_path,
4021 const gchar *interface_name,
4022 const gchar *signal_name,
4023 GVariant *parameters,
4026 GDBusMessage *message;
4032 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4033 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4034 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4035 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4036 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4037 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4039 message = g_dbus_message_new_signal (object_path,
4043 if (destination_bus_name != NULL)
4044 g_dbus_message_set_header (message,
4045 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4046 g_variant_new_string (destination_bus_name));
4048 if (parameters != NULL)
4049 g_dbus_message_set_body (message, parameters);
4051 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4052 g_object_unref (message);
4058 add_call_flags (GDBusMessage *message,
4059 GDBusCallFlags flags)
4061 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4062 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4066 * g_dbus_connection_call:
4067 * @connection: A #GDBusConnection.
4068 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4069 * @object_path: Path of remote object.
4070 * @interface_name: D-Bus interface to invoke method on.
4071 * @method_name: The name of the method to invoke.
4072 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4073 * @flags: Flags from the #GDBusCallFlags enumeration.
4074 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4075 * @cancellable: A #GCancellable or %NULL.
4076 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4077 * care about the result of the method invocation.
4078 * @user_data: The data to pass to @callback.
4080 * Asynchronously invokes the @method_name method on the
4081 * @interface_name D-Bus interface on the remote object at
4082 * @object_path owned by @bus_name.
4084 * If @connection is closed then the operation will fail with
4085 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4086 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4087 * not compatible with the D-Bus protocol, the operation fails with
4088 * %G_IO_ERROR_INVALID_ARGUMENT.
4090 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4091 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4092 * of the thread you are calling this method from. You can then call
4093 * g_dbus_connection_call_finish() to get the result of the operation.
4094 * See g_dbus_connection_call_sync() for the synchronous version of this
4100 g_dbus_connection_call (GDBusConnection *connection,
4101 const gchar *bus_name,
4102 const gchar *object_path,
4103 const gchar *interface_name,
4104 const gchar *method_name,
4105 GVariant *parameters,
4106 GDBusCallFlags flags,
4108 GCancellable *cancellable,
4109 GAsyncReadyCallback callback,
4112 GDBusMessage *message;
4114 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4115 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4116 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4117 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4118 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4119 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4120 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4122 message = g_dbus_message_new_method_call (bus_name,
4126 add_call_flags (message, flags);
4127 if (parameters != NULL)
4128 g_dbus_message_set_body (message, parameters);
4130 g_dbus_connection_send_message_with_reply (connection,
4133 NULL, /* volatile guint32 *out_serial */
4138 if (message != NULL)
4139 g_object_unref (message);
4143 decode_method_reply (GDBusMessage *reply,
4149 switch (g_dbus_message_get_message_type (reply))
4151 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4152 result = g_dbus_message_get_body (reply);
4155 result = g_variant_new ("()");
4156 g_variant_ref_sink (result);
4160 g_variant_ref (result);
4164 case G_DBUS_MESSAGE_TYPE_ERROR:
4165 g_dbus_message_to_gerror (reply, error);
4169 g_assert_not_reached ();
4177 * g_dbus_connection_call_finish:
4178 * @connection: A #GDBusConnection.
4179 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4180 * @error: Return location for error or %NULL.
4182 * Finishes an operation started with g_dbus_connection_call().
4184 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4185 * return values. Free with g_variant_unref().
4190 g_dbus_connection_call_finish (GDBusConnection *connection,
4194 GDBusMessage *reply;
4197 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4198 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4199 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4203 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4207 result = decode_method_reply (reply, error);
4209 g_object_unref (reply);
4215 /* ---------------------------------------------------------------------------------------------------- */
4218 * g_dbus_connection_call_sync:
4219 * @connection: A #GDBusConnection.
4220 * @bus_name: A unique or well-known bus name.
4221 * @object_path: Path of remote object.
4222 * @interface_name: D-Bus interface to invoke method on.
4223 * @method_name: The name of the method to invoke.
4224 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4225 * @flags: Flags from the #GDBusCallFlags enumeration.
4226 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4227 * @cancellable: A #GCancellable or %NULL.
4228 * @error: Return location for error or %NULL.
4230 * Synchronously invokes the @method_name method on the
4231 * @interface_name D-Bus interface on the remote object at
4232 * @object_path owned by @bus_name.
4234 * If @connection is closed then the operation will fail with
4235 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4236 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4237 * contains a value not compatible with the D-Bus protocol, the operation
4238 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4240 * The calling thread is blocked until a reply is received. See
4241 * g_dbus_connection_call() for the asynchronous version of
4244 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4245 * return values. Free with g_variant_unref().
4250 g_dbus_connection_call_sync (GDBusConnection *connection,
4251 const gchar *bus_name,
4252 const gchar *object_path,
4253 const gchar *interface_name,
4254 const gchar *method_name,
4255 GVariant *parameters,
4256 GDBusCallFlags flags,
4258 GCancellable *cancellable,
4261 GDBusMessage *message;
4262 GDBusMessage *reply;
4269 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4270 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4271 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4272 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4273 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4274 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4275 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4277 message = g_dbus_message_new_method_call (bus_name,
4281 add_call_flags (message, flags);
4282 if (parameters != NULL)
4283 g_dbus_message_set_body (message, parameters);
4285 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4288 NULL, /* volatile guint32 *out_serial */
4295 result = decode_method_reply (reply, error);
4298 if (message != NULL)
4299 g_object_unref (message);
4301 g_object_unref (reply);
4306 /* ---------------------------------------------------------------------------------------------------- */
4308 struct ExportedSubtree
4312 GDBusConnection *connection;
4313 const GDBusSubtreeVTable *vtable;
4314 GDBusSubtreeFlags flags;
4316 GMainContext *context;
4318 GDestroyNotify user_data_free_func;
4322 exported_subtree_free (ExportedSubtree *es)
4324 if (es->user_data_free_func != NULL)
4325 /* TODO: push to thread-default mainloop */
4326 es->user_data_free_func (es->user_data);
4328 if (es->context != NULL)
4329 g_main_context_unref (es->context);
4331 g_free (es->object_path);
4335 /* called without lock held */
4337 handle_subtree_introspect (GDBusConnection *connection,
4338 ExportedSubtree *es,
4339 GDBusMessage *message)
4343 GDBusMessage *reply;
4346 const gchar *sender;
4347 const gchar *requested_object_path;
4348 const gchar *requested_node;
4349 GPtrArray *interfaces;
4351 gchar **subnode_paths;
4355 requested_object_path = g_dbus_message_get_path (message);
4356 sender = g_dbus_message_get_sender (message);
4357 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4359 s = g_string_new (NULL);
4360 introspect_append_header (s);
4362 /* Strictly we don't need the children in dynamic mode, but we avoid the
4363 * conditionals to preserve code clarity
4365 children = es->vtable->enumerate (es->connection,
4372 requested_node = strrchr (requested_object_path, '/') + 1;
4374 /* Assert existence of object if we are not dynamic */
4375 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4376 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4381 requested_node = "/";
4384 interfaces = es->vtable->introspect (es->connection,
4389 if (interfaces != NULL)
4391 if (interfaces->len > 0)
4393 /* we're in business */
4394 introspect_append_standard_interfaces (s);
4396 for (n = 0; n < interfaces->len; n++)
4398 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4399 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4402 g_ptr_array_unref (interfaces);
4405 /* then include <node> entries from the Subtree for the root */
4408 for (n = 0; children != NULL && children[n] != NULL; n++)
4409 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4412 /* finally include nodes registered below us */
4413 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4414 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4415 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4416 g_strfreev (subnode_paths);
4418 g_string_append (s, "</node>\n");
4420 reply = g_dbus_message_new_method_reply (message);
4421 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4422 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4423 g_object_unref (reply);
4428 g_string_free (s, TRUE);
4429 g_strfreev (children);
4433 /* called without lock held */
4435 handle_subtree_method_invocation (GDBusConnection *connection,
4436 ExportedSubtree *es,
4437 GDBusMessage *message)
4440 const gchar *sender;
4441 const gchar *interface_name;
4442 const gchar *member;
4443 const gchar *signature;
4444 const gchar *requested_object_path;
4445 const gchar *requested_node;
4448 const GDBusInterfaceInfo *introspection_data;
4449 const GDBusInterfaceVTable *interface_vtable;
4450 gpointer interface_user_data;
4452 GPtrArray *interfaces;
4453 gboolean is_property_get;
4454 gboolean is_property_set;
4455 gboolean is_property_get_all;
4460 requested_object_path = g_dbus_message_get_path (message);
4461 sender = g_dbus_message_get_sender (message);
4462 interface_name = g_dbus_message_get_interface (message);
4463 member = g_dbus_message_get_member (message);
4464 signature = g_dbus_message_get_signature (message);
4465 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4467 is_property_get = FALSE;
4468 is_property_set = FALSE;
4469 is_property_get_all = FALSE;
4470 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4472 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4473 is_property_get = TRUE;
4474 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4475 is_property_set = TRUE;
4476 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4477 is_property_get_all = TRUE;
4480 children = es->vtable->enumerate (es->connection,
4487 requested_node = strrchr (requested_object_path, '/') + 1;
4489 /* If not dynamic, skip if requested node is not part of children */
4490 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4491 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4496 requested_node = "/";
4499 /* get introspection data for the node */
4500 interfaces = es->vtable->introspect (es->connection,
4502 requested_object_path,
4505 g_assert (interfaces != NULL);
4506 introspection_data = NULL;
4507 for (n = 0; n < interfaces->len; n++)
4509 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4510 if (g_strcmp0 (id_n->name, interface_name) == 0)
4511 introspection_data = id_n;
4514 /* dispatch the call if the user wants to handle it */
4515 if (introspection_data != NULL)
4517 /* figure out where to dispatch the method call */
4518 interface_user_data = NULL;
4519 interface_vtable = es->vtable->dispatch (es->connection,
4524 &interface_user_data,
4526 if (interface_vtable == NULL)
4529 CONNECTION_LOCK (connection);
4530 handled = validate_and_maybe_schedule_method_call (es->connection,
4535 interface_user_data);
4536 CONNECTION_UNLOCK (connection);
4538 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4539 else if (is_property_get || is_property_set || is_property_get_all)
4541 if (is_property_get)
4542 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4543 else if (is_property_set)
4544 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4545 else if (is_property_get_all)
4546 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4548 g_assert_not_reached ();
4550 /* see if the object supports this interface at all */
4551 for (n = 0; n < interfaces->len; n++)
4553 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4554 if (g_strcmp0 (id_n->name, interface_name) == 0)
4555 introspection_data = id_n;
4558 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4559 * claims it won't support the interface
4561 if (introspection_data == NULL)
4563 GDBusMessage *reply;
4564 reply = g_dbus_message_new_method_error (message,
4565 "org.freedesktop.DBus.Error.InvalidArgs",
4566 _("No such interface `%s'"),
4568 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4569 g_object_unref (reply);
4574 /* figure out where to dispatch the property get/set/getall calls */
4575 interface_user_data = NULL;
4576 interface_vtable = es->vtable->dispatch (es->connection,
4581 &interface_user_data,
4583 if (interface_vtable == NULL)
4586 if (is_property_get || is_property_set)
4588 CONNECTION_LOCK (connection);
4589 handled = validate_and_maybe_schedule_property_getset (es->connection,
4595 interface_user_data);
4596 CONNECTION_UNLOCK (connection);
4598 else if (is_property_get_all)
4600 CONNECTION_LOCK (connection);
4601 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4606 interface_user_data);
4607 CONNECTION_UNLOCK (connection);
4612 if (interfaces != NULL)
4613 g_ptr_array_unref (interfaces);
4614 g_strfreev (children);
4620 GDBusMessage *message;
4621 ExportedSubtree *es;
4622 } SubtreeDeferredData;
4625 subtree_deferred_data_free (SubtreeDeferredData *data)
4627 g_object_unref (data->message);
4631 /* called without lock held in the thread where the caller registered the subtree */
4633 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4635 SubtreeDeferredData *data = _data;
4640 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4641 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4642 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4643 handled = handle_subtree_introspect (data->es->connection,
4647 handled = handle_subtree_method_invocation (data->es->connection,
4653 CONNECTION_LOCK (data->es->connection);
4654 handled = handle_generic_unlocked (data->es->connection, data->message);
4655 CONNECTION_UNLOCK (data->es->connection);
4658 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4661 GDBusMessage *reply;
4662 reply = g_dbus_message_new_method_error (data->message,
4663 "org.freedesktop.DBus.Error.UnknownMethod",
4664 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4665 g_dbus_message_get_member (data->message),
4666 g_dbus_message_get_interface (data->message),
4667 g_dbus_message_get_signature (data->message));
4668 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4669 g_object_unref (reply);
4675 /* called in message handler thread with lock held */
4677 subtree_message_func (GDBusConnection *connection,
4678 ExportedSubtree *es,
4679 GDBusMessage *message)
4681 GSource *idle_source;
4682 SubtreeDeferredData *data;
4684 data = g_new0 (SubtreeDeferredData, 1);
4685 data->message = g_object_ref (message);
4688 /* defer this call to an idle handler in the right thread */
4689 idle_source = g_idle_source_new ();
4690 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4691 g_source_set_callback (idle_source,
4692 process_subtree_vtable_message_in_idle_cb,
4694 (GDestroyNotify) subtree_deferred_data_free);
4695 g_source_attach (idle_source, es->context);
4696 g_source_unref (idle_source);
4698 /* since we own the entire subtree, handlers for objects not in the subtree have been
4699 * tried already by libdbus-1 - so we just need to ensure that we're always going
4700 * to reply to the message
4706 * g_dbus_connection_register_subtree:
4707 * @connection: A #GDBusConnection.
4708 * @object_path: The object path to register the subtree at.
4709 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4710 * @flags: Flags used to fine tune the behavior of the subtree.
4711 * @user_data: Data to pass to functions in @vtable.
4712 * @user_data_free_func: Function to call when the subtree is unregistered.
4713 * @error: Return location for error or %NULL.
4715 * Registers a whole subtree of <quote>dynamic</quote> objects.
4717 * The @enumerate and @introspection functions in @vtable are used to
4718 * convey, to remote callers, what nodes exist in the subtree rooted
4721 * When handling remote calls into any node in the subtree, first the
4722 * @enumerate function is used to check if the node exists. If the node exists
4723 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4724 * the @introspection function is used to check if the node supports the
4725 * requested method. If so, the @dispatch function is used to determine
4726 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4727 * #gpointer will be used to call into the interface vtable for processing
4730 * All calls into user-provided code will be invoked in the <link
4731 * linkend="g-main-context-push-thread-default">thread-default main
4732 * loop</link> of the thread you are calling this method from.
4734 * If an existing subtree is already registered at @object_path or
4735 * then @error is set to #G_IO_ERROR_EXISTS.
4737 * Note that it is valid to register regular objects (using
4738 * g_dbus_connection_register_object()) in a subtree registered with
4739 * g_dbus_connection_register_subtree() - if so, the subtree handler
4740 * is tried as the last resort. One way to think about a subtree
4741 * handler is to consider it a <quote>fallback handler</quote>
4742 * for object paths not registered via g_dbus_connection_register_object()
4743 * or other bindings.
4745 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4747 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4748 * that can be used with g_dbus_connection_unregister_subtree() .
4753 g_dbus_connection_register_subtree (GDBusConnection *connection,
4754 const gchar *object_path,
4755 const GDBusSubtreeVTable *vtable,
4756 GDBusSubtreeFlags flags,
4758 GDestroyNotify user_data_free_func,
4762 ExportedSubtree *es;
4764 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4765 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4766 g_return_val_if_fail (vtable != NULL, 0);
4767 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4771 CONNECTION_LOCK (connection);
4773 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4779 _("A subtree is already exported for %s"),
4784 es = g_new0 (ExportedSubtree, 1);
4785 es->object_path = g_strdup (object_path);
4786 es->connection = connection;
4788 es->vtable = vtable;
4790 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4791 es->user_data = user_data;
4792 es->user_data_free_func = user_data_free_func;
4793 es->context = g_main_context_get_thread_default ();
4794 if (es->context != NULL)
4795 g_main_context_ref (es->context);
4797 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4798 g_hash_table_insert (connection->priv->map_id_to_es,
4799 GUINT_TO_POINTER (es->id),
4805 CONNECTION_UNLOCK (connection);
4810 /* ---------------------------------------------------------------------------------------------------- */
4813 * g_dbus_connection_unregister_subtree:
4814 * @connection: A #GDBusConnection.
4815 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4817 * Unregisters a subtree.
4819 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4824 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4825 guint registration_id)
4827 ExportedSubtree *es;
4830 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4834 CONNECTION_LOCK (connection);
4836 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4837 GUINT_TO_POINTER (registration_id));
4841 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4842 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4847 CONNECTION_UNLOCK (connection);
4852 /* ---------------------------------------------------------------------------------------------------- */
4854 /* must be called with lock held */
4856 handle_generic_ping_unlocked (GDBusConnection *connection,
4857 const gchar *object_path,
4858 GDBusMessage *message)
4860 GDBusMessage *reply;
4861 reply = g_dbus_message_new_method_reply (message);
4862 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4863 g_object_unref (reply);
4866 /* must be called with lock held */
4868 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4869 const gchar *object_path,
4870 GDBusMessage *message)
4872 GDBusMessage *reply;
4875 if (connection->priv->machine_id == NULL)
4879 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4880 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4881 &connection->priv->machine_id,
4885 reply = g_dbus_message_new_method_error (message,
4886 "org.freedesktop.DBus.Error.Failed",
4887 _("Unable to load /var/lib/dbus/machine-id: %s"),
4889 g_error_free (error);
4893 g_strstrip (connection->priv->machine_id);
4894 /* TODO: validate value */
4900 reply = g_dbus_message_new_method_reply (message);
4901 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4903 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4904 g_object_unref (reply);
4907 /* must be called with lock held */
4909 handle_generic_introspect_unlocked (GDBusConnection *connection,
4910 const gchar *object_path,
4911 GDBusMessage *message)
4916 GDBusMessage *reply;
4918 /* first the header */
4919 s = g_string_new (NULL);
4920 introspect_append_header (s);
4922 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4923 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4924 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4925 g_strfreev (registered);
4926 g_string_append (s, "</node>\n");
4928 reply = g_dbus_message_new_method_reply (message);
4929 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4930 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4931 g_object_unref (reply);
4932 g_string_free (s, TRUE);
4935 /* must be called with lock held */
4937 handle_generic_unlocked (GDBusConnection *connection,
4938 GDBusMessage *message)
4941 const gchar *interface_name;
4942 const gchar *member;
4943 const gchar *signature;
4946 CONNECTION_ENSURE_LOCK (connection);
4950 interface_name = g_dbus_message_get_interface (message);
4951 member = g_dbus_message_get_member (message);
4952 signature = g_dbus_message_get_signature (message);
4953 path = g_dbus_message_get_path (message);
4955 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4956 g_strcmp0 (member, "Introspect") == 0 &&
4957 g_strcmp0 (signature, "") == 0)
4959 handle_generic_introspect_unlocked (connection, path, message);
4962 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4963 g_strcmp0 (member, "Ping") == 0 &&
4964 g_strcmp0 (signature, "") == 0)
4966 handle_generic_ping_unlocked (connection, path, message);
4969 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4970 g_strcmp0 (member, "GetMachineId") == 0 &&
4971 g_strcmp0 (signature, "") == 0)
4973 handle_generic_get_machine_id_unlocked (connection, path, message);
4980 /* ---------------------------------------------------------------------------------------------------- */
4982 /* called in message handler thread with lock held */
4984 distribute_method_call (GDBusConnection *connection,
4985 GDBusMessage *message)
4988 ExportedSubtree *es;
4989 const gchar *object_path;
4990 const gchar *interface_name;
4991 const gchar *member;
4992 const gchar *signature;
4994 gchar *subtree_path;
4997 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
4999 interface_name = g_dbus_message_get_interface (message);
5000 member = g_dbus_message_get_member (message);
5001 signature = g_dbus_message_get_signature (message);
5002 path = g_dbus_message_get_path (message);
5003 subtree_path = g_strdup (path);
5004 needle = strrchr (subtree_path, '/');
5005 if (needle != NULL && needle != subtree_path)
5011 g_free (subtree_path);
5012 subtree_path = NULL;
5016 g_debug ("interface = `%s'", interface_name);
5017 g_debug ("member = `%s'", member);
5018 g_debug ("signature = `%s'", signature);
5019 g_debug ("path = `%s'", path);
5020 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5023 object_path = g_dbus_message_get_path (message);
5024 g_assert (object_path != NULL);
5026 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5029 if (obj_message_func (connection, eo, message))
5033 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5036 if (subtree_message_func (connection, es, message))
5040 if (subtree_path != NULL)
5042 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5045 if (subtree_message_func (connection, es, message))
5050 if (handle_generic_unlocked (connection, message))
5053 /* if we end up here, the message has not been not handled */
5056 g_free (subtree_path);
5059 /* ---------------------------------------------------------------------------------------------------- */
5061 static GDBusConnection **
5062 message_bus_get_singleton (GBusType bus_type,
5065 GDBusConnection **ret;
5066 const gchar *starter_bus;
5072 case G_BUS_TYPE_SESSION:
5073 ret = &the_session_bus;
5076 case G_BUS_TYPE_SYSTEM:
5077 ret = &the_system_bus;
5080 case G_BUS_TYPE_STARTER:
5081 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5082 if (g_strcmp0 (starter_bus, "session") == 0)
5084 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5087 else if (g_strcmp0 (starter_bus, "system") == 0)
5089 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5094 if (starter_bus != NULL)
5098 G_IO_ERROR_INVALID_ARGUMENT,
5099 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5100 " - unknown value `%s'"),
5105 g_set_error_literal (error,
5107 G_IO_ERROR_INVALID_ARGUMENT,
5108 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5109 "variable is not set"));
5115 g_assert_not_reached ();
5123 static GDBusConnection *
5124 get_uninitialized_connection (GBusType bus_type,
5125 GCancellable *cancellable,
5128 GDBusConnection **singleton;
5129 GDBusConnection *ret;
5133 G_LOCK (message_bus_lock);
5134 singleton = message_bus_get_singleton (bus_type, error);
5135 if (singleton == NULL)
5138 if (*singleton == NULL)
5141 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5142 if (address == NULL)
5144 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5146 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5147 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5148 "exit-on-close", TRUE,
5153 ret = g_object_ref (*singleton);
5156 g_assert (ret != NULL);
5159 G_UNLOCK (message_bus_lock);
5165 * @bus_type: A #GBusType.
5166 * @cancellable: A #GCancellable or %NULL.
5167 * @error: Return location for error or %NULL.
5169 * Synchronously connects to the message bus specified by @bus_type.
5170 * Note that the returned object may shared with other callers,
5171 * e.g. if two separate parts of a process calls this function with
5172 * the same @bus_type, they will share the same object.
5174 * This is a synchronous failable function. See g_bus_get() and
5175 * g_bus_get_finish() for the asynchronous version.
5177 * The returned object is a singleton, that is, shared with other
5178 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5179 * event that you need a private message bus connection, use
5180 * g_dbus_address_get_for_bus() and
5181 * g_dbus_connection_new_for_address().
5183 * Note that the returned #GDBusConnection object will (usually) have
5184 * the #GDBusConnection:exit-on-close property set to %TRUE.
5186 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5191 g_bus_get_sync (GBusType bus_type,
5192 GCancellable *cancellable,
5195 GDBusConnection *connection;
5197 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5199 connection = get_uninitialized_connection (bus_type, cancellable, error);
5200 if (connection == NULL)
5203 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5205 g_object_unref (connection);
5214 bus_get_async_initable_cb (GObject *source_object,
5218 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5222 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5226 g_assert (error != NULL);
5227 g_simple_async_result_set_from_error (simple, error);
5228 g_error_free (error);
5229 g_object_unref (source_object);
5233 g_simple_async_result_set_op_res_gpointer (simple,
5237 g_simple_async_result_complete_in_idle (simple);
5238 g_object_unref (simple);
5243 * @bus_type: A #GBusType.
5244 * @cancellable: A #GCancellable or %NULL.
5245 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5246 * @user_data: The data to pass to @callback.
5248 * Asynchronously connects to the message bus specified by @bus_type.
5250 * When the operation is finished, @callback will be invoked. You can
5251 * then call g_bus_get_finish() to get the result of the operation.
5253 * This is a asynchronous failable function. See g_bus_get_sync() for
5254 * the synchronous version.
5259 g_bus_get (GBusType bus_type,
5260 GCancellable *cancellable,
5261 GAsyncReadyCallback callback,
5264 GDBusConnection *connection;
5265 GSimpleAsyncResult *simple;
5268 simple = g_simple_async_result_new (NULL,
5274 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5275 if (connection == NULL)
5277 g_assert (error != NULL);
5278 g_simple_async_result_set_from_error (simple, error);
5279 g_error_free (error);
5280 g_simple_async_result_complete_in_idle (simple);
5281 g_object_unref (simple);
5285 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5288 bus_get_async_initable_cb,
5295 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5296 * @error: Return location for error or %NULL.
5298 * Finishes an operation started with g_bus_get().
5300 * The returned object is a singleton, that is, shared with other
5301 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5302 * event that you need a private message bus connection, use
5303 * g_dbus_address_get_for_bus() and
5304 * g_dbus_connection_new_for_address().
5306 * Note that the returned #GDBusConnection object will (usually) have
5307 * the #GDBusConnection:exit-on-close property set to %TRUE.
5309 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5314 g_bus_get_finish (GAsyncResult *res,
5317 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5319 GDBusConnection *ret;
5321 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5323 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5327 if (g_simple_async_result_propagate_error (simple, error))
5330 object = g_simple_async_result_get_op_res_gpointer (simple);
5331 g_assert (object != NULL);
5332 ret = g_object_ref (G_DBUS_CONNECTION (object));
5338 /* ---------------------------------------------------------------------------------------------------- */
5340 #define __G_DBUS_CONNECTION_C__
5341 #include "gioaliasdef.c"