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 * - Need to document usage of DBUS_SYSTEM_ADDRESS and
32 * DBUS_SESSION_BUS_ADDRESS environment variables. Also need to
33 * document other mechanisms/sources for determining the D-Bus
34 * address of a well-known bus.
36 * - e.g. on Win32 we need code like from here
38 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
40 * that was never copied over here because it originally was copy-paste
41 * from the GPLv2 / AFL 2.1 libdbus sources.
43 * - on OS X we need to look in launchd for the address
45 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
47 * - on X11 we need to look in a X11 property on the X server
48 * - (we can also just use dbus-launch(1) from the D-Bus
51 * - (ideally) this requires D-Bus spec work because none of
52 * this has never really been specced out properly (excect
55 * - Related to the above, we also need to be able to launch a message bus
56 * instance.... Since we don't want to write our own bus daemon we should
57 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
59 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
60 * to specify where the nonce is stored. This will allow people to use
61 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
62 * to easily acheive secure RPC via nonce-tcp.
64 * - need to expose an extension point for resolving D-Bus address and
65 * turning them into GIOStream objects. This will allow us to implement
66 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
68 * - see g_dbus_address_connect() in gdbusaddress.c
70 * - would be cute to use kernel-specific APIs to resolve fds for
71 * debug output when using G_DBUS_DEBUG=messages, e.g. in addition to
73 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
75 * maybe we can show more information about what fd 21 really is.
76 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
77 * Initial experiments on Linux 2.6 suggests that the symlink looks
82 * e.g. not of much use.
90 #include "gdbusauth.h"
91 #include "gdbusutils.h"
92 #include "gdbusaddress.h"
93 #include "gdbusmessage.h"
94 #include "gdbusconnection.h"
95 #include "gdbuserror.h"
96 #include "gioenumtypes.h"
97 #include "gdbusintrospection.h"
98 #include "gdbusmethodinvocation.h"
99 #include "gdbusprivate.h"
100 #include "gdbusauthobserver.h"
101 #include "gio-marshal.h"
102 #include "ginitable.h"
103 #include "gasyncinitable.h"
104 #include "giostream.h"
105 #include "gasyncresult.h"
106 #include "gsimpleasyncresult.h"
109 #include <gio/gunixconnection.h>
110 #include <gio/gunixfdmessage.h>
112 #include <sys/types.h>
115 #include "glibintl.h"
116 #include "gioalias.h"
119 * SECTION:gdbusconnection
120 * @short_description: D-Bus Connections
121 * @include: gio/gio.h
123 * The #GDBusConnection type is used for D-Bus connections to remote
124 * peers such as a message buses. It is a low-level API that offers a
125 * lot of flexibility. For instance, it lets you establish a connection
126 * over any transport that can by represented as an #GIOStream.
128 * This class is rarely used directly in D-Bus clients. If you are writing
129 * an D-Bus client, it is often easier to use the g_bus_own_name(),
130 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
132 * <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>
134 * <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>
136 * <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>
139 /* ---------------------------------------------------------------------------------------------------- */
141 G_LOCK_DEFINE_STATIC (message_bus_lock);
143 static GDBusConnection *the_session_bus = NULL;
144 static GDBusConnection *the_system_bus = NULL;
146 /* ---------------------------------------------------------------------------------------------------- */
149 _g_strv_has_string (const gchar* const *haystack,
154 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
156 if (g_strcmp0 (haystack[n], needle) == 0)
162 /* ---------------------------------------------------------------------------------------------------- */
165 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
167 // TODO: for some reason this doesn't work on Windows
168 #define CONNECTION_ENSURE_LOCK(obj) do { \
169 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
171 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
172 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
177 #define CONNECTION_LOCK(obj) do { \
178 g_mutex_lock ((obj)->priv->lock); \
181 #define CONNECTION_UNLOCK(obj) do { \
182 g_mutex_unlock ((obj)->priv->lock); \
185 struct _GDBusConnectionPrivate
187 /* ------------------------------------------------------------------------ */
188 /* -- General object state ------------------------------------------------ */
189 /* ------------------------------------------------------------------------ */
191 /* object-wide lock */
194 /* A lock used in the init() method of the GInitable interface - see comments
195 * in initable_init() for why a separate lock is needed
199 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
200 * someone calls org.freedesktop.DBus.GetMachineId()
204 /* The underlying stream used for communication */
207 /* The object used for authentication (if any) */
210 /* Set to TRUE if the connection has been closed */
213 /* Last serial used */
216 /* The object used to send/receive message */
219 /* If connected to a message bus, this contains the unique name assigned to
220 * us by the bus (e.g. ":1.42")
222 gchar *bus_unique_name;
224 /* The GUID returned by the other side if we authenticed as a client or
225 * the GUID to use if authenticating as a server
229 /* set to TRUE exactly when initable_init() has finished running */
230 gboolean is_initialized;
232 /* If the connection could not be established during initable_init(), this GError will set */
233 GError *initialization_error;
235 /* The result of g_main_context_get_thread_default() when the object
236 * was created (the GObject _init() function) - this is used for delivery
237 * of the :closed GObject signal.
239 GMainContext *main_context_at_construction;
241 /* construct properties */
243 GDBusConnectionFlags flags;
245 /* Map used for managing method replies */
246 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
248 /* Maps used for managing signal subscription */
249 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
250 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
251 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
253 /* Maps used for managing exported objects and subtrees */
254 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
255 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
256 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
257 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
259 /* Structure used for message filters */
262 /* Whether to exit on close */
263 gboolean exit_on_close;
265 /* Capabilities negotiated during authentication */
266 GDBusCapabilityFlags capabilities;
268 GDBusAuthObserver *authentication_observer;
269 GCredentials *crendentials;
272 typedef struct ExportedObject ExportedObject;
273 static void exported_object_free (ExportedObject *eo);
275 typedef struct ExportedSubtree ExportedSubtree;
276 static void exported_subtree_free (ExportedSubtree *es);
294 PROP_CAPABILITY_FLAGS,
295 PROP_AUTHENTICATION_OBSERVER,
298 static void distribute_signals (GDBusConnection *connection,
299 GDBusMessage *message);
301 static void distribute_method_call (GDBusConnection *connection,
302 GDBusMessage *message);
304 static gboolean handle_generic_unlocked (GDBusConnection *connection,
305 GDBusMessage *message);
308 static void purge_all_signal_subscriptions (GDBusConnection *connection);
309 static void purge_all_filters (GDBusConnection *connection);
311 #define _G_ENSURE_LOCK(name) do { \
312 if (G_UNLIKELY (G_TRYLOCK(name))) \
314 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
315 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
319 static guint signals[LAST_SIGNAL] = { 0 };
321 static void initable_iface_init (GInitableIface *initable_iface);
322 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
324 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
325 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
326 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
330 g_dbus_connection_dispose (GObject *object)
332 GDBusConnection *connection = G_DBUS_CONNECTION (object);
334 G_LOCK (message_bus_lock);
335 //g_debug ("disposing %p", connection);
336 if (connection == the_session_bus)
338 the_session_bus = NULL;
340 else if (connection == the_system_bus)
342 the_system_bus = NULL;
344 if (connection->priv->worker != NULL)
346 _g_dbus_worker_stop (connection->priv->worker);
347 connection->priv->worker = NULL;
349 G_UNLOCK (message_bus_lock);
351 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
352 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
356 g_dbus_connection_finalize (GObject *object)
358 GDBusConnection *connection = G_DBUS_CONNECTION (object);
360 if (connection->priv->authentication_observer != NULL)
361 g_object_unref (connection->priv->authentication_observer);
363 if (connection->priv->auth != NULL)
364 g_object_unref (connection->priv->auth);
366 //g_debug ("finalizing %p", connection);
367 if (connection->priv->stream != NULL)
369 /* We don't really care if closing the stream succeeds or not */
370 g_io_stream_close_async (connection->priv->stream,
372 NULL, /* GCancellable */
373 NULL, /* GAsyncReadyCallback */
374 NULL); /* userdata */
375 g_object_unref (connection->priv->stream);
376 connection->priv->stream = NULL;
379 g_free (connection->priv->address);
381 g_free (connection->priv->guid);
382 g_free (connection->priv->bus_unique_name);
384 if (connection->priv->initialization_error != NULL)
385 g_error_free (connection->priv->initialization_error);
387 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
389 purge_all_signal_subscriptions (connection);
390 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
391 g_hash_table_unref (connection->priv->map_id_to_signal_data);
392 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
394 g_hash_table_unref (connection->priv->map_id_to_ei);
395 g_hash_table_unref (connection->priv->map_object_path_to_eo);
396 g_hash_table_unref (connection->priv->map_id_to_es);
397 g_hash_table_unref (connection->priv->map_object_path_to_es);
399 purge_all_filters (connection);
400 g_ptr_array_unref (connection->priv->filters);
402 if (connection->priv->main_context_at_construction != NULL)
403 g_main_context_unref (connection->priv->main_context_at_construction);
405 g_free (connection->priv->machine_id);
407 g_mutex_free (connection->priv->init_lock);
408 g_mutex_free (connection->priv->lock);
410 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
414 g_dbus_connection_get_property (GObject *object,
419 GDBusConnection *connection = G_DBUS_CONNECTION (object);
424 g_value_set_object (value, g_dbus_connection_get_stream (connection));
428 g_value_set_string (value, g_dbus_connection_get_guid (connection));
431 case PROP_UNIQUE_NAME:
432 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
436 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
439 case PROP_EXIT_ON_CLOSE:
440 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
443 case PROP_CAPABILITY_FLAGS:
444 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
448 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
454 g_dbus_connection_set_property (GObject *object,
459 GDBusConnection *connection = G_DBUS_CONNECTION (object);
464 connection->priv->stream = g_value_dup_object (value);
468 connection->priv->guid = g_value_dup_string (value);
472 connection->priv->address = g_value_dup_string (value);
476 connection->priv->flags = g_value_get_flags (value);
479 case PROP_EXIT_ON_CLOSE:
480 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
483 case PROP_AUTHENTICATION_OBSERVER:
484 connection->priv->authentication_observer = g_value_dup_object (value);
488 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
494 g_dbus_connection_real_closed (GDBusConnection *connection,
495 gboolean remote_peer_vanished,
498 if (remote_peer_vanished && connection->priv->exit_on_close)
500 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
506 g_dbus_connection_class_init (GDBusConnectionClass *klass)
508 GObjectClass *gobject_class;
510 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
512 gobject_class = G_OBJECT_CLASS (klass);
514 gobject_class->finalize = g_dbus_connection_finalize;
515 gobject_class->dispose = g_dbus_connection_dispose;
516 gobject_class->set_property = g_dbus_connection_set_property;
517 gobject_class->get_property = g_dbus_connection_get_property;
519 klass->closed = g_dbus_connection_real_closed;
522 * GDBusConnection:stream:
524 * The underlying #GIOStream used for I/O.
528 g_object_class_install_property (gobject_class,
530 g_param_spec_object ("stream",
532 P_("The underlying streams used for I/O"),
536 G_PARAM_CONSTRUCT_ONLY |
537 G_PARAM_STATIC_NAME |
538 G_PARAM_STATIC_BLURB |
539 G_PARAM_STATIC_NICK));
542 * GDBusConnection:address:
544 * A D-Bus address specifying potential endpoints that can be used
545 * when establishing the connection.
549 g_object_class_install_property (gobject_class,
551 g_param_spec_string ("address",
553 P_("D-Bus address specifying potential socket endpoints"),
556 G_PARAM_CONSTRUCT_ONLY |
557 G_PARAM_STATIC_NAME |
558 G_PARAM_STATIC_BLURB |
559 G_PARAM_STATIC_NICK));
562 * GDBusConnection:flags:
564 * Flags from the #GDBusConnectionFlags enumeration.
568 g_object_class_install_property (gobject_class,
570 g_param_spec_flags ("flags",
573 G_TYPE_DBUS_CONNECTION_FLAGS,
574 G_DBUS_CONNECTION_FLAGS_NONE,
576 G_PARAM_CONSTRUCT_ONLY |
577 G_PARAM_STATIC_NAME |
578 G_PARAM_STATIC_BLURB |
579 G_PARAM_STATIC_NICK));
582 * GDBusConnection:guid:
584 * The GUID of the peer performing the role of server when
587 * If you are constructing a #GDBusConnection and pass
588 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
589 * #GDBusConnection:flags property then you MUST also set this
590 * property to a valid guid.
592 * If you are constructing a #GDBusConnection and pass
593 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
594 * #GDBusConnection:flags property you will be able to read the GUID
595 * of the other peer here after the connection has been successfully
600 g_object_class_install_property (gobject_class,
602 g_param_spec_string ("guid",
604 P_("GUID of the server peer"),
608 G_PARAM_CONSTRUCT_ONLY |
609 G_PARAM_STATIC_NAME |
610 G_PARAM_STATIC_BLURB |
611 G_PARAM_STATIC_NICK));
614 * GDBusConnection:unique-name:
616 * The unique name as assigned by the message bus or %NULL if the
617 * connection is not open or not a message bus connection.
621 g_object_class_install_property (gobject_class,
623 g_param_spec_string ("unique-name",
625 P_("Unique name of bus connection"),
628 G_PARAM_STATIC_NAME |
629 G_PARAM_STATIC_BLURB |
630 G_PARAM_STATIC_NICK));
633 * GDBusConnection:closed:
635 * A boolean specifying whether the connection has been closed.
639 g_object_class_install_property (gobject_class,
641 g_param_spec_boolean ("closed",
643 P_("Whether the connection is closed"),
646 G_PARAM_STATIC_NAME |
647 G_PARAM_STATIC_BLURB |
648 G_PARAM_STATIC_NICK));
651 * GDBusConnection:exit-on-close:
653 * A boolean specifying whether the process will be terminated (by
654 * calling <literal>raise(SIGTERM)</literal>) if the connection
655 * is closed by the remote peer.
659 g_object_class_install_property (gobject_class,
661 g_param_spec_boolean ("exit-on-close",
663 P_("Whether the process is terminated when the connection is closed"),
667 G_PARAM_STATIC_NAME |
668 G_PARAM_STATIC_BLURB |
669 G_PARAM_STATIC_NICK));
672 * GDBusConnection:capabilities:
674 * Flags from the #GDBusCapabilityFlags enumeration
675 * representing connection features negotiated with the other peer.
679 g_object_class_install_property (gobject_class,
680 PROP_CAPABILITY_FLAGS,
681 g_param_spec_flags ("capabilities",
684 G_TYPE_DBUS_CAPABILITY_FLAGS,
685 G_DBUS_CAPABILITY_FLAGS_NONE,
687 G_PARAM_STATIC_NAME |
688 G_PARAM_STATIC_BLURB |
689 G_PARAM_STATIC_NICK));
692 * GDBusConnection:authentication-observer:
694 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
698 g_object_class_install_property (gobject_class,
699 PROP_AUTHENTICATION_OBSERVER,
700 g_param_spec_object ("authentication-observer",
701 P_("Authentication Observer"),
702 P_("Object used to assist in the authentication process"),
703 G_TYPE_DBUS_AUTH_OBSERVER,
705 G_PARAM_CONSTRUCT_ONLY |
706 G_PARAM_STATIC_NAME |
707 G_PARAM_STATIC_BLURB |
708 G_PARAM_STATIC_NICK));
711 * GDBusConnection::closed:
712 * @connection: The #GDBusConnection emitting the signal.
713 * @remote_peer_vanished: %TRUE if @connection is closed because the
714 * remote peer closed its end of the connection.
715 * @error: A #GError with more details about the event or %NULL.
717 * Emitted when the connection is closed.
719 * The cause of this event can be
722 * If g_dbus_connection_close() is called. In this case
723 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
726 * If the remote peer closes the connection. In this case
727 * @remote_peer_vanished is set to %TRUE and @error is set.
730 * If the remote peer sends invalid or malformed data. In this
731 * case @remote_peer_vanished is set to %FALSE and @error
736 * Upon receiving this signal, you should give up your reference to
737 * @connection. You are guaranteed that this signal is emitted only
742 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
743 G_TYPE_DBUS_CONNECTION,
745 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
748 _gio_marshal_VOID__BOOLEAN_BOXED,
756 g_dbus_connection_init (GDBusConnection *connection)
758 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
760 connection->priv->lock = g_mutex_new ();
761 connection->priv->init_lock = g_mutex_new ();
763 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
765 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
767 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
769 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
774 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
777 (GDestroyNotify) exported_object_free);
779 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
782 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
785 (GDestroyNotify) exported_subtree_free);
787 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
790 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
791 if (connection->priv->main_context_at_construction != NULL)
792 g_main_context_ref (connection->priv->main_context_at_construction);
794 connection->priv->filters = g_ptr_array_new ();
798 * g_dbus_connection_get_stream:
799 * @connection: a #GDBusConnection
801 * Gets the underlying stream used for IO.
803 * Returns: the stream used for IO
808 g_dbus_connection_get_stream (GDBusConnection *connection)
810 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
811 return connection->priv->stream;
816 * g_dbus_connection_is_closed:
817 * @connection: A #GDBusConnection.
819 * Gets whether @connection is closed.
821 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
826 g_dbus_connection_is_closed (GDBusConnection *connection)
828 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
829 return connection->priv->closed;
833 * g_dbus_connection_get_capabilities:
834 * @connection: A #GDBusConnection.
836 * Gets the capabilities negotiated with the remote peer
838 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
843 g_dbus_connection_get_capabilities (GDBusConnection *connection)
845 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
846 return connection->priv->capabilities;
850 /* ---------------------------------------------------------------------------------------------------- */
854 GDBusConnection *connection;
856 gboolean remote_peer_vanished;
860 emit_closed_data_free (EmitClosedData *data)
862 g_object_unref (data->connection);
863 if (data->error != NULL)
864 g_error_free (data->error);
869 emit_closed_in_idle (gpointer user_data)
871 EmitClosedData *data = user_data;
874 g_object_notify (G_OBJECT (data->connection), "closed");
875 g_signal_emit (data->connection,
876 signals[CLOSED_SIGNAL],
878 data->remote_peer_vanished,
884 /* Can be called from any thread, must hold lock */
886 set_closed_unlocked (GDBusConnection *connection,
887 gboolean remote_peer_vanished,
890 GSource *idle_source;
891 EmitClosedData *data;
893 CONNECTION_ENSURE_LOCK (connection);
895 g_assert (!connection->priv->closed);
897 connection->priv->closed = TRUE;
899 data = g_new0 (EmitClosedData, 1);
900 data->connection = g_object_ref (connection);
901 data->remote_peer_vanished = remote_peer_vanished;
902 data->error = error != NULL ? g_error_copy (error) : NULL;
904 idle_source = g_idle_source_new ();
905 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
906 g_source_set_callback (idle_source,
909 (GDestroyNotify) emit_closed_data_free);
910 g_source_attach (idle_source, connection->priv->main_context_at_construction);
911 g_source_unref (idle_source);
914 /* ---------------------------------------------------------------------------------------------------- */
917 * g_dbus_connection_close:
918 * @connection: A #GDBusConnection.
920 * Closes @connection. Note that this never causes the process to
921 * exit (this might only happen if the other end of a shared message
922 * bus connection disconnects).
924 * If @connection is already closed, this method does nothing.
929 g_dbus_connection_close (GDBusConnection *connection)
931 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
933 CONNECTION_LOCK (connection);
934 if (!connection->priv->closed)
936 GError *error = NULL;
938 /* TODO: do this async */
939 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
940 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
942 g_warning ("Error closing stream: %s", error->message);
943 g_error_free (error);
946 set_closed_unlocked (connection, FALSE, NULL);
948 CONNECTION_UNLOCK (connection);
951 /* ---------------------------------------------------------------------------------------------------- */
954 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
955 GDBusMessage *message,
956 volatile guint32 *out_serial,
961 guint32 serial_to_use;
964 CONNECTION_ENSURE_LOCK (connection);
966 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
967 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
969 /* TODO: check all necessary headers are present */
974 if (out_serial != NULL)
977 if (connection->priv->closed)
979 g_set_error_literal (error,
982 _("The connection is closed"));
986 blob = g_dbus_message_to_blob (message,
992 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
997 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1000 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1003 g_assert_not_reached ();
1008 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1009 blob_size, serial_to_use, connection);
1010 g_printerr ("----\n");
1011 hexdump (blob, blob_size);
1012 g_printerr ("----\n");
1015 /* TODO: use connection->priv->auth to encode the blob */
1017 if (out_serial != NULL)
1018 *out_serial = serial_to_use;
1020 g_dbus_message_set_serial (message, serial_to_use);
1022 _g_dbus_worker_send_message (connection->priv->worker,
1026 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1037 * g_dbus_connection_send_message:
1038 * @connection: A #GDBusConnection.
1039 * @message: A #GDBusMessage
1040 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1041 * @error: Return location for error or %NULL.
1043 * Asynchronously sends @message to the peer represented by @connection.
1045 * If @out_serial is not %NULL, then the serial number assigned to
1046 * @message by @connection will be written to this location prior to
1047 * submitting the message to the underlying transport.
1049 * If @connection is closed then the operation will fail with
1050 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1051 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1052 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1054 * See <xref linkend="gdbus-server"/> and <xref
1055 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1056 * low-level API to send and receive UNIX file descriptors.
1058 * Returns: %TRUE if the message was well-formed and queued for
1059 * transmission, %FALSE if @error is set.
1064 g_dbus_connection_send_message (GDBusConnection *connection,
1065 GDBusMessage *message,
1066 volatile guint32 *out_serial,
1071 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1072 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1073 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1075 CONNECTION_LOCK (connection);
1076 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1077 CONNECTION_UNLOCK (connection);
1081 /* ---------------------------------------------------------------------------------------------------- */
1085 volatile gint ref_count;
1086 GDBusConnection *connection;
1088 GSimpleAsyncResult *simple;
1090 GMainContext *main_context;
1092 GCancellable *cancellable;
1094 gulong cancellable_handler_id;
1096 GSource *timeout_source;
1101 static SendMessageData *
1102 send_message_data_ref (SendMessageData *data)
1104 g_atomic_int_inc (&data->ref_count);
1109 send_message_data_unref (SendMessageData *data)
1111 if (g_atomic_int_dec_and_test (&data->ref_count))
1113 g_assert (data->timeout_source == NULL);
1114 g_assert (data->simple == NULL);
1115 g_assert (data->cancellable_handler_id == 0);
1116 g_object_unref (data->connection);
1117 if (data->cancellable != NULL)
1118 g_object_unref (data->cancellable);
1119 if (data->main_context != NULL)
1120 g_main_context_unref (data->main_context);
1125 /* ---------------------------------------------------------------------------------------------------- */
1127 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1129 send_message_with_reply_deliver (SendMessageData *data)
1131 CONNECTION_ENSURE_LOCK (data->connection);
1133 g_assert (!data->delivered);
1135 data->delivered = TRUE;
1137 g_simple_async_result_complete_in_idle (data->simple);
1138 g_object_unref (data->simple);
1139 data->simple = NULL;
1141 if (data->timeout_source != NULL)
1143 g_source_destroy (data->timeout_source);
1144 data->timeout_source = NULL;
1146 if (data->cancellable_handler_id > 0)
1148 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1149 data->cancellable_handler_id = 0;
1152 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1153 GUINT_TO_POINTER (data->serial)));
1155 send_message_data_unref (data);
1158 /* ---------------------------------------------------------------------------------------------------- */
1160 /* must hold lock */
1162 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1163 GDBusMessage *reply)
1165 if (data->delivered)
1168 g_simple_async_result_set_op_res_gpointer (data->simple,
1169 g_object_ref (reply),
1172 send_message_with_reply_deliver (data);
1178 /* ---------------------------------------------------------------------------------------------------- */
1181 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1183 SendMessageData *data = user_data;
1185 CONNECTION_LOCK (data->connection);
1186 if (data->delivered)
1189 g_simple_async_result_set_error (data->simple,
1191 G_IO_ERROR_CANCELLED,
1192 _("Operation was cancelled"));
1194 send_message_with_reply_deliver (data);
1197 CONNECTION_UNLOCK (data->connection);
1201 /* Can be called from any thread with or without lock held */
1203 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1206 SendMessageData *data = user_data;
1207 GSource *idle_source;
1209 /* postpone cancellation to idle handler since we may be called directly
1210 * via g_cancellable_connect() (e.g. holding lock)
1212 idle_source = g_idle_source_new ();
1213 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1214 g_source_set_callback (idle_source,
1215 send_message_with_reply_cancelled_idle_cb,
1216 send_message_data_ref (data),
1217 (GDestroyNotify) send_message_data_unref);
1218 g_source_attach (idle_source, data->main_context);
1219 g_source_unref (idle_source);
1222 /* ---------------------------------------------------------------------------------------------------- */
1225 send_message_with_reply_timeout_cb (gpointer user_data)
1227 SendMessageData *data = user_data;
1229 CONNECTION_LOCK (data->connection);
1230 if (data->delivered)
1233 g_simple_async_result_set_error (data->simple,
1235 G_IO_ERROR_TIMED_OUT,
1236 _("Timeout was reached"));
1238 send_message_with_reply_deliver (data);
1241 CONNECTION_UNLOCK (data->connection);
1246 /* ---------------------------------------------------------------------------------------------------- */
1249 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1250 GDBusMessage *message,
1252 volatile guint32 *out_serial,
1253 GCancellable *cancellable,
1254 GAsyncReadyCallback callback,
1257 GSimpleAsyncResult *simple;
1258 SendMessageData *data;
1260 volatile guint32 serial;
1264 if (out_serial == NULL)
1265 out_serial = &serial;
1267 if (timeout_msec == -1)
1268 timeout_msec = 30 * 1000; /* TODO: check 30 secs is the default timeout */
1270 simple = g_simple_async_result_new (G_OBJECT (connection),
1273 g_dbus_connection_send_message_with_reply);
1275 if (g_cancellable_is_cancelled (cancellable))
1277 g_simple_async_result_set_error (simple,
1279 G_IO_ERROR_CANCELLED,
1280 _("Operation was cancelled"));
1281 g_simple_async_result_complete_in_idle (simple);
1282 g_object_unref (simple);
1286 if (connection->priv->closed)
1288 g_simple_async_result_set_error (simple,
1291 _("The connection is closed"));
1292 g_simple_async_result_complete_in_idle (simple);
1293 g_object_unref (simple);
1298 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1300 g_simple_async_result_set_from_error (simple, error);
1301 g_simple_async_result_complete_in_idle (simple);
1302 g_object_unref (simple);
1306 data = g_new0 (SendMessageData, 1);
1307 data->ref_count = 1;
1308 data->connection = g_object_ref (connection);
1309 data->simple = simple;
1310 data->serial = *out_serial;
1311 data->main_context = g_main_context_get_thread_default ();
1312 if (data->main_context != NULL)
1313 g_main_context_ref (data->main_context);
1315 if (cancellable != NULL)
1317 data->cancellable = g_object_ref (cancellable);
1318 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1319 G_CALLBACK (send_message_with_reply_cancelled_cb),
1320 send_message_data_ref (data),
1321 (GDestroyNotify) send_message_data_unref);
1322 g_object_set_data_full (G_OBJECT (simple),
1324 g_object_ref (cancellable),
1325 (GDestroyNotify) g_object_unref);
1328 data->timeout_source = g_timeout_source_new (timeout_msec);
1329 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1330 g_source_set_callback (data->timeout_source,
1331 send_message_with_reply_timeout_cb,
1332 send_message_data_ref (data),
1333 (GDestroyNotify) send_message_data_unref);
1334 g_source_attach (data->timeout_source, data->main_context);
1335 g_source_unref (data->timeout_source);
1337 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1338 GUINT_TO_POINTER (*out_serial),
1346 * g_dbus_connection_send_message_with_reply:
1347 * @connection: A #GDBusConnection.
1348 * @message: A #GDBusMessage.
1349 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1350 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1351 * @cancellable: A #GCancellable or %NULL.
1352 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1353 * care about the result.
1354 * @user_data: The data to pass to @callback.
1356 * Asynchronously sends @message to the peer represented by @connection.
1358 * If @out_serial is not %NULL, then the serial number assigned to
1359 * @message by @connection will be written to this location prior to
1360 * submitting the message to the underlying transport.
1362 * If @connection is closed then the operation will fail with
1363 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1364 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1365 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1367 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1368 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1369 * of the thread you are calling this method from. You can then call
1370 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1371 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1373 * See <xref linkend="gdbus-server"/> and <xref
1374 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1375 * low-level API to send and receive UNIX file descriptors.
1380 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1381 GDBusMessage *message,
1383 volatile guint32 *out_serial,
1384 GCancellable *cancellable,
1385 GAsyncReadyCallback callback,
1388 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1389 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1390 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1392 CONNECTION_LOCK (connection);
1393 g_dbus_connection_send_message_with_reply_unlocked (connection,
1400 CONNECTION_UNLOCK (connection);
1404 * g_dbus_connection_send_message_with_reply_finish:
1405 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1406 * @error: Return location for error or %NULL.
1408 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1410 * Note that @error is only set if a local in-process error
1411 * occured. That is to say that the returned #GDBusMessage object may
1412 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1413 * g_dbus_message_to_gerror() to transcode this to a #GError.
1415 * See <xref linkend="gdbus-server"/> and <xref
1416 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1417 * low-level API to send and receive UNIX file descriptors.
1419 * Returns: A #GDBusMessage or %NULL if @error is set.
1424 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1428 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1429 GDBusMessage *reply;
1430 GCancellable *cancellable;
1432 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1433 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1437 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1439 if (g_simple_async_result_propagate_error (simple, error))
1442 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1443 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1444 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1446 g_object_unref (reply);
1448 g_set_error_literal (error,
1450 G_IO_ERROR_CANCELLED,
1451 _("Operation was cancelled"));
1457 /* ---------------------------------------------------------------------------------------------------- */
1462 GMainContext *context;
1464 } SendMessageSyncData;
1467 send_message_with_reply_sync_cb (GDBusConnection *connection,
1471 SendMessageSyncData *data = user_data;
1472 data->res = g_object_ref (res);
1473 g_main_loop_quit (data->loop);
1477 * g_dbus_connection_send_message_with_reply_sync:
1478 * @connection: A #GDBusConnection.
1479 * @message: A #GDBusMessage.
1480 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1481 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1482 * @cancellable: A #GCancellable or %NULL.
1483 * @error: Return location for error or %NULL.
1485 * Synchronously sends @message to the peer represented by @connection
1486 * and blocks the calling thread until a reply is received or the
1487 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1488 * for the asynchronous version of this method.
1490 * If @out_serial is not %NULL, then the serial number assigned to
1491 * @message by @connection will be written to this location prior to
1492 * submitting the message to the underlying transport.
1494 * If @connection is closed then the operation will fail with
1495 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1496 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1497 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1499 * Note that @error is only set if a local in-process error
1500 * occured. That is to say that the returned #GDBusMessage object may
1501 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1502 * g_dbus_message_to_gerror() to transcode this to a #GError.
1504 * See <xref linkend="gdbus-server"/> and <xref
1505 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1506 * low-level API to send and receive UNIX file descriptors.
1508 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1513 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1514 GDBusMessage *message,
1516 volatile guint32 *out_serial,
1517 GCancellable *cancellable,
1520 SendMessageSyncData *data;
1521 GDBusMessage *reply;
1523 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1524 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1525 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1526 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1528 data = g_new0 (SendMessageSyncData, 1);
1529 data->context = g_main_context_new ();
1530 data->loop = g_main_loop_new (data->context, FALSE);
1532 g_main_context_push_thread_default (data->context);
1534 g_dbus_connection_send_message_with_reply (connection,
1539 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1541 g_main_loop_run (data->loop);
1542 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1546 g_main_context_pop_thread_default (data->context);
1548 g_main_context_unref (data->context);
1549 g_main_loop_unref (data->loop);
1550 g_object_unref (data->res);
1556 /* ---------------------------------------------------------------------------------------------------- */
1560 GDBusMessageFilterFunction func;
1567 GDBusMessageFilterFunction filter_function;
1569 GDestroyNotify user_data_free_func;
1572 /* Called in worker's thread - we must not block */
1574 on_worker_message_received (GDBusWorker *worker,
1575 GDBusMessage *message,
1578 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1579 FilterCallback *filters;
1580 gboolean consumed_by_filter;
1584 //g_debug ("in on_worker_message_received");
1586 g_object_ref (connection);
1588 /* First collect the set of callback functions */
1589 CONNECTION_LOCK (connection);
1590 num_filters = connection->priv->filters->len;
1591 filters = g_new0 (FilterCallback, num_filters);
1592 for (n = 0; n < num_filters; n++)
1594 FilterData *data = connection->priv->filters->pdata[n];
1595 filters[n].func = data->filter_function;
1596 filters[n].user_data = data->user_data;
1598 CONNECTION_UNLOCK (connection);
1600 /* the call the filters in order (without holding the lock) */
1601 consumed_by_filter = FALSE;
1602 for (n = 0; n < num_filters; n++)
1604 consumed_by_filter = filters[n].func (connection,
1606 filters[n].user_data);
1607 if (consumed_by_filter)
1611 /* Standard dispatch unless the filter ate the message */
1612 if (!consumed_by_filter)
1614 GDBusMessageType message_type;
1616 message_type = g_dbus_message_get_message_type (message);
1617 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1619 guint32 reply_serial;
1620 SendMessageData *send_message_data;
1622 reply_serial = g_dbus_message_get_reply_serial (message);
1623 CONNECTION_LOCK (connection);
1624 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1625 GUINT_TO_POINTER (reply_serial));
1626 if (send_message_data != NULL)
1628 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1629 send_message_data_deliver_reply_unlocked (send_message_data, message);
1633 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1635 CONNECTION_UNLOCK (connection);
1637 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1639 CONNECTION_LOCK (connection);
1640 distribute_signals (connection, message);
1641 CONNECTION_UNLOCK (connection);
1643 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1645 CONNECTION_LOCK (connection);
1646 distribute_method_call (connection, message);
1647 CONNECTION_UNLOCK (connection);
1651 g_object_unref (connection);
1655 /* Called in worker's thread - we must not block */
1657 on_worker_closed (GDBusWorker *worker,
1658 gboolean remote_peer_vanished,
1662 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1664 //g_debug ("in on_worker_closed: %s", error->message);
1666 CONNECTION_LOCK (connection);
1667 if (!connection->priv->closed)
1668 set_closed_unlocked (connection, remote_peer_vanished, error);
1669 CONNECTION_UNLOCK (connection);
1672 /* ---------------------------------------------------------------------------------------------------- */
1674 /* Determines the biggest set of capabilities we can support on this connection */
1675 static GDBusCapabilityFlags
1676 get_offered_capabilities_max (GDBusConnection *connection)
1678 GDBusCapabilityFlags ret;
1679 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1681 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1682 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1688 initable_init (GInitable *initable,
1689 GCancellable *cancellable,
1692 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1695 /* This method needs to be idempotent to work with the singleton
1696 * pattern. See the docs for g_initable_init(). We implement this by
1699 * Unfortunately we can't use the main lock since the on_worker_*()
1700 * callbacks above needs the lock during initialization (for message
1701 * bus connections we do a synchronous Hello() call on the bus).
1703 g_mutex_lock (connection->priv->init_lock);
1707 if (connection->priv->is_initialized)
1709 if (connection->priv->stream != NULL)
1712 g_assert (connection->priv->initialization_error != NULL);
1715 g_assert (connection->priv->initialization_error == NULL);
1717 /* The user can pass multiple (but mutally exclusive) construct
1720 * - stream (of type GIOStream)
1721 * - address (of type gchar*)
1723 * At the end of the day we end up with a non-NULL GIOStream
1724 * object in connection->priv->stream.
1726 if (connection->priv->address != NULL)
1728 g_assert (connection->priv->stream == NULL);
1730 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1731 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1733 g_set_error_literal (error,
1735 G_IO_ERROR_INVALID_ARGUMENT,
1736 _("Unsupported flags encountered when constructing a client-side connection"));
1740 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1741 NULL, /* TODO: out_guid */
1743 &connection->priv->initialization_error);
1744 if (connection->priv->stream == NULL)
1747 else if (connection->priv->stream != NULL)
1753 g_assert_not_reached ();
1756 /* Authenticate the connection */
1757 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1759 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1760 g_assert (connection->priv->guid != NULL);
1761 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1762 if (!_g_dbus_auth_run_server (connection->priv->auth,
1763 connection->priv->authentication_observer,
1764 connection->priv->guid,
1765 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1766 get_offered_capabilities_max (connection),
1767 &connection->priv->capabilities,
1768 &connection->priv->crendentials,
1770 &connection->priv->initialization_error))
1773 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1775 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1776 g_assert (connection->priv->guid == NULL);
1777 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1778 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1779 get_offered_capabilities_max (connection),
1780 &connection->priv->capabilities,
1782 &connection->priv->initialization_error);
1783 if (connection->priv->guid == NULL)
1787 if (connection->priv->authentication_observer != NULL)
1789 g_object_unref (connection->priv->authentication_observer);
1790 connection->priv->authentication_observer = NULL;
1793 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1795 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1799 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1803 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1805 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1808 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1809 connection->priv->capabilities,
1810 on_worker_message_received,
1814 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1815 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1817 GVariant *hello_result;
1820 hello_result = g_dbus_connection_call_sync (connection,
1821 "org.freedesktop.DBus", /* name */
1822 "/org/freedesktop/DBus", /* path */
1823 "org.freedesktop.DBus", /* interface */
1825 NULL, /* parameters */
1826 G_DBUS_CALL_FLAGS_NONE,
1828 NULL, /* TODO: cancellable */
1829 &connection->priv->initialization_error);
1830 if (hello_result == NULL)
1833 g_variant_get (hello_result, "(s)", &s);
1834 connection->priv->bus_unique_name = g_strdup (s);
1835 g_variant_unref (hello_result);
1836 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1839 connection->priv->is_initialized = TRUE;
1845 g_assert (connection->priv->initialization_error != NULL);
1846 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1849 g_mutex_unlock (connection->priv->init_lock);
1855 initable_iface_init (GInitableIface *initable_iface)
1857 initable_iface->init = initable_init;
1860 /* ---------------------------------------------------------------------------------------------------- */
1863 async_init_thread (GSimpleAsyncResult *res,
1865 GCancellable *cancellable)
1867 GError *error = NULL;
1869 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1871 g_simple_async_result_set_from_error (res, error);
1872 g_error_free (error);
1877 async_initable_init_async (GAsyncInitable *initable,
1879 GCancellable *cancellable,
1880 GAsyncReadyCallback callback,
1883 GSimpleAsyncResult *res;
1885 g_return_if_fail (G_IS_INITABLE (initable));
1887 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1888 async_initable_init_async);
1889 g_simple_async_result_run_in_thread (res, async_init_thread,
1890 io_priority, cancellable);
1891 g_object_unref (res);
1895 async_initable_init_finish (GAsyncInitable *initable,
1899 return TRUE; /* Errors handled by base impl */
1903 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1905 /* We basically just want to use GIO's default implementation - though that one is
1906 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1908 async_initable_iface->init_async = async_initable_init_async;
1909 async_initable_iface->init_finish = async_initable_init_finish;
1912 /* ---------------------------------------------------------------------------------------------------- */
1915 * g_dbus_connection_new:
1916 * @stream: A #GIOStream.
1917 * @guid: The GUID to use if a authenticating as a server or %NULL.
1918 * @flags: Flags describing how to make the connection.
1919 * @authentication_observer: A #GDBusAuthObserver or %NULL.
1920 * @cancellable: A #GCancellable or %NULL.
1921 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1922 * @user_data: The data to pass to @callback.
1924 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1925 * with the end represented by @stream.
1927 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
1928 * @auth_observer (if not %NULL) is used to assist in the client
1929 * authentication process.
1931 * When the operation is finished, @callback will be invoked. You can
1932 * then call g_dbus_connection_new_finish() to get the result of the
1935 * This is a asynchronous failable constructor. See
1936 * g_dbus_connection_new_sync() for the synchronous
1942 g_dbus_connection_new (GIOStream *stream,
1944 GDBusConnectionFlags flags,
1945 GDBusAuthObserver *authentication_observer,
1946 GCancellable *cancellable,
1947 GAsyncReadyCallback callback,
1950 g_return_if_fail (G_IS_IO_STREAM (stream));
1951 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1959 "authentication-observer", authentication_observer,
1964 * g_dbus_connection_new_finish:
1965 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1966 * @error: Return location for error or %NULL.
1968 * Finishes an operation started with g_dbus_connection_new().
1970 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1975 g_dbus_connection_new_finish (GAsyncResult *res,
1979 GObject *source_object;
1981 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1982 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1984 source_object = g_async_result_get_source_object (res);
1985 g_assert (source_object != NULL);
1986 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
1989 g_object_unref (source_object);
1991 return G_DBUS_CONNECTION (object);
1997 * g_dbus_connection_new_sync:
1998 * @stream: A #GIOStream.
1999 * @guid: The GUID to use if a authenticating as a server or %NULL.
2000 * @flags: Flags describing how to make the connection.
2001 * @authentication_observer: A #GDBusAuthObserver or %NULL.
2002 * @cancellable: A #GCancellable or %NULL.
2003 * @error: Return location for error or %NULL.
2005 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2006 * with the end represented by @stream.
2008 * If %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER is set in @flags,
2009 * @auth_observer (if not %NULL) is used to assist in the client
2010 * authentication process.
2012 * This is a synchronous failable constructor. See
2013 * g_dbus_connection_new() for the asynchronous version.
2015 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2020 g_dbus_connection_new_sync (GIOStream *stream,
2022 GDBusConnectionFlags flags,
2023 GDBusAuthObserver *authentication_observer,
2024 GCancellable *cancellable,
2027 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2028 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2029 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2035 "authentication-observer", authentication_observer,
2039 /* ---------------------------------------------------------------------------------------------------- */
2042 * g_dbus_connection_new_for_address:
2043 * @address: A D-Bus address.
2044 * @flags: Flags describing how to make the connection.
2045 * @cancellable: A #GCancellable or %NULL.
2046 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2047 * @user_data: The data to pass to @callback.
2049 * Asynchronously connects and sets up a D-Bus client connection for
2050 * exchanging D-Bus messages with an endpoint specified by @address
2051 * which must be in the D-Bus address format.
2053 * This constructor can only be used to initiate client-side
2054 * connections - use g_dbus_connection_new() if you need to act as the
2055 * server. In particular, @flags cannot contain the
2056 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2057 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2059 * When the operation is finished, @callback will be invoked. You can
2060 * then call g_dbus_connection_new_finish() to get the result of the
2063 * This is a asynchronous failable constructor. See
2064 * g_dbus_connection_new_for_address_sync() for the synchronous
2070 g_dbus_connection_new_for_address (const gchar *address,
2071 GDBusConnectionFlags flags,
2072 GCancellable *cancellable,
2073 GAsyncReadyCallback callback,
2076 g_return_if_fail (address != NULL);
2077 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2088 * g_dbus_connection_new_for_address_finish:
2089 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2090 * @error: Return location for error or %NULL.
2092 * Finishes an operation started with g_dbus_connection_new_for_address().
2094 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2099 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2103 GObject *source_object;
2105 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2106 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2108 source_object = g_async_result_get_source_object (res);
2109 g_assert (source_object != NULL);
2110 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2113 g_object_unref (source_object);
2115 return G_DBUS_CONNECTION (object);
2121 * g_dbus_connection_new_for_address_sync:
2122 * @address: A D-Bus address.
2123 * @flags: Flags describing how to make the connection.
2124 * @cancellable: A #GCancellable or %NULL.
2125 * @error: Return location for error or %NULL.
2127 * Synchronously connects and sets up a D-Bus client connection for
2128 * exchanging D-Bus messages with an endpoint specified by @address
2129 * which must be in the D-Bus address format.
2131 * This constructor can only be used to initiate client-side
2132 * connections - use g_dbus_connection_new_sync() if you need to act
2133 * as the server. In particular, @flags cannot contain the
2134 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2135 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2137 * This is a synchronous failable constructor. See
2138 * g_dbus_connection_new_for_address() for the asynchronous version.
2140 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2145 g_dbus_connection_new_for_address_sync (const gchar *address,
2146 GDBusConnectionFlags flags,
2147 GCancellable *cancellable,
2150 g_return_val_if_fail (address != NULL, NULL);
2151 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2152 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2160 /* ---------------------------------------------------------------------------------------------------- */
2163 * g_dbus_connection_set_exit_on_close:
2164 * @connection: A #GDBusConnection.
2165 * @exit_on_close: Whether the process should be terminated
2166 * when @connection is closed by the remote peer.
2168 * Sets whether the process should be terminated when @connection is
2169 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2175 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2176 gboolean exit_on_close)
2178 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2179 connection->priv->exit_on_close = exit_on_close;
2183 * g_dbus_connection_get_exit_on_close:
2184 * @connection: A #GDBusConnection.
2186 * Gets whether the process is terminated when @connection is
2187 * closed by the remote peer. See
2188 * #GDBusConnection:exit-on-close for more details.
2190 * Returns: Whether the process is terminated when @connection is
2191 * closed by the remote peer.
2196 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2198 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2199 return connection->priv->exit_on_close;
2203 * g_dbus_connection_get_guid:
2204 * @connection: A #GDBusConnection.
2206 * The GUID of the peer performing the role of server when
2207 * authenticating. See #GDBusConnection:guid for more details.
2209 * Returns: The GUID. Do not free this string, it is owned by
2215 g_dbus_connection_get_guid (GDBusConnection *connection)
2217 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2218 return connection->priv->guid;
2222 * g_dbus_connection_get_unique_name:
2223 * @connection: A #GDBusConnection.
2225 * Gets the unique name of @connection as assigned by the message
2226 * bus. This can also be used to figure out if @connection is a
2227 * message bus connection.
2229 * Returns: The unique name or %NULL if @connection is not a message
2230 * bus connection. Do not free this string, it is owned by
2236 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2238 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2239 return connection->priv->bus_unique_name;
2243 * g_dbus_connection_get_peer_credentials:
2244 * @connection: A #GDBusConnection.
2246 * Gets the credentials of the authenticated peer. This will always
2247 * return %NULL unless @connection acted as a server
2248 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2249 * when set up and the client passed credentials as part of the
2250 * authentication process.
2252 * In a message bus setup, the message bus is always the server and
2253 * each application is a client. So this method will always return
2254 * %NULL for message bus clients.
2256 * Returns: A #GCredentials or %NULL if not available. Do not free
2257 * this object, it is owned by @connection.
2262 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2264 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2265 return connection->priv->crendentials;
2268 /* ---------------------------------------------------------------------------------------------------- */
2270 static guint _global_filter_id = 1;
2273 * g_dbus_connection_add_filter:
2274 * @connection: A #GDBusConnection.
2275 * @filter_function: A filter function.
2276 * @user_data: User data to pass to @filter_function.
2277 * @user_data_free_func: Function to free @user_data with when filter
2278 * is removed or %NULL.
2280 * Adds a message filter. Filters are handlers that are run on all
2281 * incoming messages, prior to standard dispatch. Filters are run in
2282 * the order that they were added. The same handler can be added as a
2283 * filter more than once, in which case it will be run more than once.
2284 * Filters added during a filter callback won't be run on the message
2287 * Note that filters are run in a dedicated message handling thread so
2288 * they can't block and, generally, can't do anything but signal a
2289 * worker thread. Also note that filters are rarely needed - use API
2290 * such as g_dbus_connection_send_message_with_reply(),
2291 * g_dbus_connection_signal_subscribe() or
2292 * g_dbus_connection_call() instead.
2294 * Returns: A filter identifier that can be used with
2295 * g_dbus_connection_remove_filter().
2300 g_dbus_connection_add_filter (GDBusConnection *connection,
2301 GDBusMessageFilterFunction filter_function,
2303 GDestroyNotify user_data_free_func)
2307 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2308 g_return_val_if_fail (filter_function != NULL, 0);
2310 CONNECTION_LOCK (connection);
2311 data = g_new0 (FilterData, 1);
2312 data->id = _global_filter_id++; /* TODO: overflow etc. */
2313 data->filter_function = filter_function;
2314 data->user_data = user_data;
2315 data->user_data_free_func = user_data_free_func;
2316 g_ptr_array_add (connection->priv->filters, data);
2317 CONNECTION_UNLOCK (connection);
2322 /* only called from finalize(), removes all filters */
2324 purge_all_filters (GDBusConnection *connection)
2327 for (n = 0; n < connection->priv->filters->len; n++)
2329 FilterData *data = connection->priv->filters->pdata[n];
2330 if (data->user_data_free_func != NULL)
2331 data->user_data_free_func (data->user_data);
2337 g_dbus_connection_remove_filter (GDBusConnection *connection,
2341 FilterData *to_destroy;
2343 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2345 CONNECTION_LOCK (connection);
2347 for (n = 0; n < connection->priv->filters->len; n++)
2349 FilterData *data = connection->priv->filters->pdata[n];
2350 if (data->id == filter_id)
2352 g_ptr_array_remove_index (connection->priv->filters, n);
2357 CONNECTION_UNLOCK (connection);
2359 /* do free without holding lock */
2360 if (to_destroy != NULL)
2362 if (to_destroy->user_data_free_func != NULL)
2363 to_destroy->user_data_free_func (to_destroy->user_data);
2364 g_free (to_destroy);
2368 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2372 /* ---------------------------------------------------------------------------------------------------- */
2378 gchar *interface_name;
2382 GArray *subscribers;
2387 GDBusSignalCallback callback;
2389 GDestroyNotify user_data_free_func;
2391 GMainContext *context;
2395 signal_data_free (SignalData *data)
2397 g_free (data->rule);
2398 g_free (data->sender);
2399 g_free (data->interface_name);
2400 g_free (data->member);
2401 g_free (data->object_path);
2402 g_free (data->arg0);
2403 g_array_free (data->subscribers, TRUE);
2408 args_to_rule (const gchar *sender,
2409 const gchar *interface_name,
2410 const gchar *member,
2411 const gchar *object_path,
2416 rule = g_string_new ("type='signal'");
2418 g_string_append_printf (rule, ",sender='%s'", sender);
2419 if (interface_name != NULL)
2420 g_string_append_printf (rule, ",interface='%s'", interface_name);
2422 g_string_append_printf (rule, ",member='%s'", member);
2423 if (object_path != NULL)
2424 g_string_append_printf (rule, ",path='%s'", object_path);
2426 g_string_append_printf (rule, ",arg0='%s'", arg0);
2428 return g_string_free (rule, FALSE);
2431 static guint _global_subscriber_id = 1;
2432 static guint _global_registration_id = 1;
2433 static guint _global_subtree_registration_id = 1;
2435 /* ---------------------------------------------------------------------------------------------------- */
2437 /* must hold lock when calling */
2439 add_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 AddMatch() message: %s", error->message);
2458 g_error_free (error);
2460 g_object_unref (message);
2463 /* ---------------------------------------------------------------------------------------------------- */
2465 /* must hold lock when calling */
2467 remove_match_rule (GDBusConnection *connection,
2468 const gchar *match_rule)
2471 GDBusMessage *message;
2473 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2474 "/org/freedesktop/DBus", /* path */
2475 "org.freedesktop.DBus", /* interface */
2477 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2480 if (!g_dbus_connection_send_message_unlocked (connection,
2485 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2486 g_error_free (error);
2488 g_object_unref (message);
2491 /* ---------------------------------------------------------------------------------------------------- */
2494 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2496 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2497 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2498 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2499 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2500 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2503 /* ---------------------------------------------------------------------------------------------------- */
2506 * g_dbus_connection_signal_subscribe:
2507 * @connection: A #GDBusConnection.
2508 * @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.
2509 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2510 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2511 * @object_path: Object path to match on or %NULL to match on all object paths.
2512 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2513 * @callback: Callback to invoke when there is a signal matching the requested data.
2514 * @user_data: User data to pass to @callback.
2515 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2517 * Subscribes to signals on @connection and invokes @callback with a
2518 * whenever the signal is received. Note that @callback
2519 * will be invoked in the <link
2520 * linkend="g-main-context-push-thread-default">thread-default main
2521 * loop</link> of the thread you are calling this method from.
2523 * It is considered a programming error to use this function if @connection is closed.
2525 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2526 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2527 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2528 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2529 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2530 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2532 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2537 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2538 const gchar *sender,
2539 const gchar *interface_name,
2540 const gchar *member,
2541 const gchar *object_path,
2543 GDBusSignalCallback callback,
2545 GDestroyNotify user_data_free_func)
2548 SignalData *signal_data;
2549 SignalSubscriber subscriber;
2550 GPtrArray *signal_data_array;
2552 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2553 * an OOM condition. We might want to change that but that would involve making
2554 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2555 * handle that. And there's really no sensible way of handling this short of retrying
2556 * to add the match rule... and then there's the little thing that, hey, maybe there's
2557 * a reason the bus in an OOM condition.
2559 * Doable, but not really sure it's worth it...
2562 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2563 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2564 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2565 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2566 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2567 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2568 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2569 g_return_val_if_fail (callback != NULL, 0);
2571 CONNECTION_LOCK (connection);
2573 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2578 subscriber.callback = callback;
2579 subscriber.user_data = user_data;
2580 subscriber.user_data_free_func = user_data_free_func;
2581 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2582 subscriber.context = g_main_context_get_thread_default ();
2583 if (subscriber.context != NULL)
2584 g_main_context_ref (subscriber.context);
2586 /* see if we've already have this rule */
2587 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2588 if (signal_data != NULL)
2590 g_array_append_val (signal_data->subscribers, subscriber);
2595 signal_data = g_new0 (SignalData, 1);
2596 signal_data->rule = rule;
2597 signal_data->sender = g_strdup (sender);
2598 signal_data->interface_name = g_strdup (interface_name);
2599 signal_data->member = g_strdup (member);
2600 signal_data->object_path = g_strdup (object_path);
2601 signal_data->arg0 = g_strdup (arg0);
2602 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2603 g_array_append_val (signal_data->subscribers, subscriber);
2605 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2609 /* Add the match rule to the bus...
2611 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2612 * always send such messages to us.
2614 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2616 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2617 add_match_rule (connection, signal_data->rule);
2621 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2622 GUINT_TO_POINTER (subscriber.id),
2625 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2626 signal_data->sender);
2627 if (signal_data_array == NULL)
2629 signal_data_array = g_ptr_array_new ();
2630 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2631 g_strdup (signal_data->sender),
2634 g_ptr_array_add (signal_data_array, signal_data);
2636 CONNECTION_UNLOCK (connection);
2638 return subscriber.id;
2641 /* ---------------------------------------------------------------------------------------------------- */
2643 /* must hold lock when calling this */
2645 unsubscribe_id_internal (GDBusConnection *connection,
2646 guint subscription_id,
2647 GArray *out_removed_subscribers)
2649 SignalData *signal_data;
2650 GPtrArray *signal_data_array;
2653 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2654 GUINT_TO_POINTER (subscription_id));
2655 if (signal_data == NULL)
2657 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2661 for (n = 0; n < signal_data->subscribers->len; n++)
2663 SignalSubscriber *subscriber;
2665 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2666 if (subscriber->id != subscription_id)
2669 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2670 GUINT_TO_POINTER (subscription_id)));
2671 g_array_append_val (out_removed_subscribers, *subscriber);
2672 g_array_remove_index (signal_data->subscribers, n);
2674 if (signal_data->subscribers->len == 0)
2675 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2677 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2678 signal_data->sender);
2679 g_warn_if_fail (signal_data_array != NULL);
2680 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2682 if (signal_data_array->len == 0)
2684 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2686 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2687 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2689 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2690 remove_match_rule (connection, signal_data->rule);
2693 signal_data_free (signal_data);
2699 g_assert_not_reached ();
2706 * g_dbus_connection_signal_unsubscribe:
2707 * @connection: A #GDBusConnection.
2708 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2710 * Unsubscribes from signals.
2715 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2716 guint subscription_id)
2718 GArray *subscribers;
2721 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2723 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2725 CONNECTION_LOCK (connection);
2726 unsubscribe_id_internal (connection,
2729 CONNECTION_UNLOCK (connection);
2732 g_assert (subscribers->len == 0 || subscribers->len == 1);
2734 /* call GDestroyNotify without lock held */
2735 for (n = 0; n < subscribers->len; n++)
2737 SignalSubscriber *subscriber;
2738 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2739 if (subscriber->user_data_free_func != NULL)
2740 subscriber->user_data_free_func (subscriber->user_data);
2741 if (subscriber->context != NULL)
2742 g_main_context_unref (subscriber->context);
2745 g_array_free (subscribers, TRUE);
2748 /* ---------------------------------------------------------------------------------------------------- */
2752 guint subscription_id;
2753 GDBusSignalCallback callback;
2755 GDBusMessage *message;
2756 GDBusConnection *connection;
2757 const gchar *sender;
2759 const gchar *interface;
2760 const gchar *member;
2763 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2767 emit_signal_instance_in_idle_cb (gpointer data)
2769 SignalInstance *signal_instance = data;
2770 GVariant *parameters;
2771 gboolean has_subscription;
2773 parameters = g_dbus_message_get_body (signal_instance->message);
2774 if (parameters == NULL)
2776 parameters = g_variant_new ("()");
2777 g_variant_ref_sink (parameters);
2781 g_variant_ref_sink (parameters);
2785 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2786 signal_instance->sender,
2787 signal_instance->path,
2788 signal_instance->interface,
2789 signal_instance->member,
2790 g_variant_print (parameters, TRUE));
2793 /* Careful here, don't do the callback if we no longer has the subscription */
2794 CONNECTION_LOCK (signal_instance->connection);
2795 has_subscription = FALSE;
2796 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2797 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2798 has_subscription = TRUE;
2799 CONNECTION_UNLOCK (signal_instance->connection);
2801 if (has_subscription)
2802 signal_instance->callback (signal_instance->connection,
2803 signal_instance->sender,
2804 signal_instance->path,
2805 signal_instance->interface,
2806 signal_instance->member,
2808 signal_instance->user_data);
2810 if (parameters != NULL)
2811 g_variant_unref (parameters);
2817 signal_instance_free (SignalInstance *signal_instance)
2819 g_object_unref (signal_instance->message);
2820 g_object_unref (signal_instance->connection);
2821 g_free (signal_instance);
2824 /* called in message handler thread WITH lock held */
2826 schedule_callbacks (GDBusConnection *connection,
2827 GPtrArray *signal_data_array,
2828 GDBusMessage *message,
2829 const gchar *sender)
2832 const gchar *interface;
2833 const gchar *member;
2842 interface = g_dbus_message_get_interface (message);
2843 member = g_dbus_message_get_member (message);
2844 path = g_dbus_message_get_path (message);
2845 arg0 = g_dbus_message_get_arg0 (message);
2848 g_debug ("sender = `%s'", sender);
2849 g_debug ("interface = `%s'", interface);
2850 g_debug ("member = `%s'", member);
2851 g_debug ("path = `%s'", path);
2852 g_debug ("arg0 = `%s'", arg0);
2855 /* TODO: if this is slow, then we can change signal_data_array into
2856 * map_object_path_to_signal_data_array or something.
2858 for (n = 0; n < signal_data_array->len; n++)
2860 SignalData *signal_data = signal_data_array->pdata[n];
2862 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2865 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2868 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2871 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2874 for (m = 0; m < signal_data->subscribers->len; m++)
2876 SignalSubscriber *subscriber;
2877 GSource *idle_source;
2878 SignalInstance *signal_instance;
2880 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2882 signal_instance = g_new0 (SignalInstance, 1);
2883 signal_instance->subscription_id = subscriber->id;
2884 signal_instance->callback = subscriber->callback;
2885 signal_instance->user_data = subscriber->user_data;
2886 signal_instance->message = g_object_ref (message);
2887 signal_instance->connection = g_object_ref (connection);
2888 signal_instance->sender = sender;
2889 signal_instance->path = path;
2890 signal_instance->interface = interface;
2891 signal_instance->member = member;
2893 idle_source = g_idle_source_new ();
2894 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2895 g_source_set_callback (idle_source,
2896 emit_signal_instance_in_idle_cb,
2898 (GDestroyNotify) signal_instance_free);
2899 g_source_attach (idle_source, subscriber->context);
2900 g_source_unref (idle_source);
2905 /* called in message handler thread with lock held */
2907 distribute_signals (GDBusConnection *connection,
2908 GDBusMessage *message)
2910 GPtrArray *signal_data_array;
2911 const gchar *sender;
2913 sender = g_dbus_message_get_sender (message);
2915 /* collect subscribers that match on sender */
2918 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2919 if (signal_data_array != NULL)
2920 schedule_callbacks (connection, signal_data_array, message, sender);
2923 /* collect subscribers not matching on sender */
2924 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2925 if (signal_data_array != NULL)
2926 schedule_callbacks (connection, signal_data_array, message, sender);
2929 /* ---------------------------------------------------------------------------------------------------- */
2931 /* only called from finalize(), removes all subscriptions */
2933 purge_all_signal_subscriptions (GDBusConnection *connection)
2935 GHashTableIter iter;
2938 GArray *subscribers;
2941 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2942 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2943 while (g_hash_table_iter_next (&iter, &key, NULL))
2945 guint subscription_id = GPOINTER_TO_UINT (key);
2946 g_array_append_val (ids, subscription_id);
2949 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2950 for (n = 0; n < ids->len; n++)
2952 guint subscription_id = g_array_index (ids, guint, n);
2953 unsubscribe_id_internal (connection,
2957 g_array_free (ids, TRUE);
2959 /* call GDestroyNotify without lock held */
2960 for (n = 0; n < subscribers->len; n++)
2962 SignalSubscriber *subscriber;
2963 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2964 if (subscriber->user_data_free_func != NULL)
2965 subscriber->user_data_free_func (subscriber->user_data);
2966 if (subscriber->context != NULL)
2967 g_main_context_unref (subscriber->context);
2970 g_array_free (subscribers, TRUE);
2973 /* ---------------------------------------------------------------------------------------------------- */
2975 struct ExportedObject
2978 GDBusConnection *connection;
2980 /* maps gchar* -> ExportedInterface* */
2981 GHashTable *map_if_name_to_ei;
2984 /* only called with lock held */
2986 exported_object_free (ExportedObject *eo)
2988 g_free (eo->object_path);
2989 g_hash_table_unref (eo->map_if_name_to_ei);
2998 gchar *interface_name;
2999 const GDBusInterfaceVTable *vtable;
3000 const GDBusInterfaceInfo *introspection_data;
3002 GMainContext *context;
3004 GDestroyNotify user_data_free_func;
3005 } ExportedInterface;
3007 /* called with lock held */
3009 exported_interface_free (ExportedInterface *ei)
3011 if (ei->user_data_free_func != NULL)
3012 /* TODO: push to thread-default mainloop */
3013 ei->user_data_free_func (ei->user_data);
3015 if (ei->context != NULL)
3016 g_main_context_unref (ei->context);
3018 g_free (ei->interface_name);
3022 /* ---------------------------------------------------------------------------------------------------- */
3026 GDBusConnection *connection;
3027 GDBusMessage *message;
3029 const char *property_name;
3030 const GDBusInterfaceVTable *vtable;
3031 const GDBusInterfaceInfo *interface_info;
3032 const GDBusPropertyInfo *property_info;
3036 property_data_free (PropertyData *data)
3038 g_object_unref (data->connection);
3039 g_object_unref (data->message);
3043 /* called in thread where object was registered - no locks held */
3045 invoke_get_property_in_idle_cb (gpointer _data)
3047 PropertyData *data = _data;
3050 GDBusMessage *reply;
3053 value = data->vtable->get_property (data->connection,
3054 g_dbus_message_get_sender (data->message),
3055 g_dbus_message_get_path (data->message),
3056 data->interface_info->name,
3057 data->property_name,
3064 g_assert_no_error (error);
3066 g_variant_ref_sink (value);
3067 reply = g_dbus_message_new_method_reply (data->message);
3068 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3069 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3070 g_variant_unref (value);
3071 g_object_unref (reply);
3075 gchar *dbus_error_name;
3077 g_assert (error != NULL);
3079 dbus_error_name = g_dbus_error_encode_gerror (error);
3080 reply = g_dbus_message_new_method_error_literal (data->message,
3083 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3084 g_free (dbus_error_name);
3085 g_error_free (error);
3086 g_object_unref (reply);
3092 /* called in thread where object was registered - no locks held */
3094 invoke_set_property_in_idle_cb (gpointer _data)
3096 PropertyData *data = _data;
3098 GDBusMessage *reply;
3104 g_variant_get (g_dbus_message_get_body (data->message),
3110 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3111 * of the given value is wrong
3113 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3115 reply = g_dbus_message_new_method_error (data->message,
3116 "org.freedesktop.DBus.Error.InvalidArgs",
3117 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3118 data->property_info->name,
3119 data->property_info->signature,
3120 g_variant_get_type_string (value));
3124 if (!data->vtable->set_property (data->connection,
3125 g_dbus_message_get_sender (data->message),
3126 g_dbus_message_get_path (data->message),
3127 data->interface_info->name,
3128 data->property_name,
3133 gchar *dbus_error_name;
3134 g_assert (error != NULL);
3135 dbus_error_name = g_dbus_error_encode_gerror (error);
3136 reply = g_dbus_message_new_method_error_literal (data->message,
3139 g_free (dbus_error_name);
3140 g_error_free (error);
3144 reply = g_dbus_message_new_method_reply (data->message);
3148 g_assert (reply != NULL);
3149 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3150 g_object_unref (reply);
3155 /* called with lock held */
3157 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3158 GDBusMessage *message,
3160 const GDBusInterfaceInfo *introspection_data,
3161 const GDBusInterfaceVTable *vtable,
3162 GMainContext *main_context,
3166 const char *interface_name;
3167 const char *property_name;
3168 const GDBusPropertyInfo *property_info;
3169 GSource *idle_source;
3170 PropertyData *property_data;
3171 GDBusMessage *reply;
3176 g_variant_get (g_dbus_message_get_body (message),
3181 g_variant_get (g_dbus_message_get_body (message),
3190 if (vtable == NULL || vtable->get_property == NULL)
3195 if (vtable == NULL || vtable->set_property == NULL)
3199 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3201 property_info = NULL;
3203 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3204 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3205 if (property_info == NULL)
3207 reply = g_dbus_message_new_method_error (message,
3208 "org.freedesktop.DBus.Error.InvalidArgs",
3209 _("No such property `%s'"),
3211 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3212 g_object_unref (reply);
3217 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3219 reply = g_dbus_message_new_method_error (message,
3220 "org.freedesktop.DBus.Error.InvalidArgs",
3221 _("Property `%s' is not readable"),
3223 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3224 g_object_unref (reply);
3228 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3230 reply = g_dbus_message_new_method_error (message,
3231 "org.freedesktop.DBus.Error.InvalidArgs",
3232 _("Property `%s' is not writable"),
3234 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3235 g_object_unref (reply);
3240 /* ok, got the property info - call user code in an idle handler */
3241 property_data = g_new0 (PropertyData, 1);
3242 property_data->connection = g_object_ref (connection);
3243 property_data->message = g_object_ref (message);
3244 property_data->user_data = user_data;
3245 property_data->property_name = property_name;
3246 property_data->vtable = vtable;
3247 property_data->interface_info = introspection_data;
3248 property_data->property_info = property_info;
3250 idle_source = g_idle_source_new ();
3251 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3252 g_source_set_callback (idle_source,
3253 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3255 (GDestroyNotify) property_data_free);
3256 g_source_attach (idle_source, main_context);
3257 g_source_unref (idle_source);
3265 /* called with lock held */
3267 handle_getset_property (GDBusConnection *connection,
3269 GDBusMessage *message,
3272 ExportedInterface *ei;
3274 const char *interface_name;
3275 const char *property_name;
3280 g_variant_get (g_dbus_message_get_body (message),
3285 g_variant_get (g_dbus_message_get_body (message),
3291 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3292 * no such interface registered
3294 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3297 GDBusMessage *reply;
3298 reply = g_dbus_message_new_method_error (message,
3299 "org.freedesktop.DBus.Error.InvalidArgs",
3300 _("No such interface `%s'"),
3302 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3303 g_object_unref (reply);
3308 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3311 ei->introspection_data,
3319 /* ---------------------------------------------------------------------------------------------------- */
3323 GDBusConnection *connection;
3324 GDBusMessage *message;
3326 const GDBusInterfaceVTable *vtable;
3327 const GDBusInterfaceInfo *interface_info;
3328 } PropertyGetAllData;
3331 property_get_all_data_free (PropertyData *data)
3333 g_object_unref (data->connection);
3334 g_object_unref (data->message);
3338 /* called in thread where object was registered - no locks held */
3340 invoke_get_all_properties_in_idle_cb (gpointer _data)
3342 PropertyGetAllData *data = _data;
3343 GVariantBuilder *builder;
3347 GDBusMessage *reply;
3352 /* TODO: Right now we never fail this call - we just omit values if
3353 * a get_property() call is failing.
3355 * We could fail the whole call if just a single get_property() call
3356 * returns an error. We need clarification in the D-Bus spec about this.
3358 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3359 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3361 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3364 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3367 value = data->vtable->get_property (data->connection,
3368 g_dbus_message_get_sender (data->message),
3369 g_dbus_message_get_path (data->message),
3370 data->interface_info->name,
3371 property_info->name,
3378 g_variant_ref_sink (value);
3379 g_variant_builder_add (builder,
3381 property_info->name,
3383 g_variant_unref (value);
3385 result = g_variant_builder_end (builder);
3387 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3388 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3389 packed = g_variant_builder_end (builder);
3391 reply = g_dbus_message_new_method_reply (data->message);
3392 g_dbus_message_set_body (reply, packed);
3393 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3394 g_object_unref (reply);
3399 /* called with lock held */
3401 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3402 GDBusMessage *message,
3403 const GDBusInterfaceInfo *introspection_data,
3404 const GDBusInterfaceVTable *vtable,
3405 GMainContext *main_context,
3409 const char *interface_name;
3410 GSource *idle_source;
3411 PropertyGetAllData *property_get_all_data;
3415 g_variant_get (g_dbus_message_get_body (message),
3419 if (vtable == NULL || vtable->get_property == NULL)
3422 /* ok, got the property info - call user in an idle handler */
3423 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3424 property_get_all_data->connection = g_object_ref (connection);
3425 property_get_all_data->message = g_object_ref (message);
3426 property_get_all_data->user_data = user_data;
3427 property_get_all_data->vtable = vtable;
3428 property_get_all_data->interface_info = introspection_data;
3430 idle_source = g_idle_source_new ();
3431 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3432 g_source_set_callback (idle_source,
3433 invoke_get_all_properties_in_idle_cb,
3434 property_get_all_data,
3435 (GDestroyNotify) property_get_all_data_free);
3436 g_source_attach (idle_source, main_context);
3437 g_source_unref (idle_source);
3445 /* called with lock held */
3447 handle_get_all_properties (GDBusConnection *connection,
3449 GDBusMessage *message)
3451 ExportedInterface *ei;
3453 const char *interface_name;
3457 g_variant_get (g_dbus_message_get_body (message),
3461 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3462 * no such interface registered
3464 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3467 GDBusMessage *reply;
3468 reply = g_dbus_message_new_method_error (message,
3469 "org.freedesktop.DBus.Error.InvalidArgs",
3470 _("No such interface"),
3472 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3473 g_object_unref (reply);
3478 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3480 ei->introspection_data,
3488 /* ---------------------------------------------------------------------------------------------------- */
3490 static const gchar introspect_header[] =
3491 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3492 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3493 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3496 static const gchar introspect_tail[] =
3499 static const gchar introspect_standard_interfaces[] =
3500 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3501 " <method name=\"Get\">\n"
3502 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3503 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3504 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3506 " <method name=\"GetAll\">\n"
3507 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3508 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3510 " <method name=\"Set\">\n"
3511 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3512 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3513 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3515 " <signal name=\"PropertiesChanged\">\n"
3516 " <arg type=\"s\" name=\"interface_name\"/>\n"
3517 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3520 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3521 " <method name=\"Introspect\">\n"
3522 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3525 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3526 " <method name=\"Ping\"/>\n"
3527 " <method name=\"GetMachineId\">\n"
3528 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3533 introspect_append_header (GString *s)
3535 g_string_append (s, introspect_header);
3539 introspect_append_standard_interfaces (GString *s)
3541 g_string_append (s, introspect_standard_interfaces);
3545 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3547 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3553 begin = object_path + path_len;
3554 end = strchr (begin, '/');
3557 s = g_strndup (begin, end - begin);
3559 s = g_strdup (begin);
3561 if (g_hash_table_lookup (set, s) == NULL)
3562 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3568 /* TODO: we want a nicer public interface for this */
3570 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3575 GHashTableIter hash_iter;
3576 const gchar *object_path;
3582 CONNECTION_ENSURE_LOCK (connection);
3584 path_len = strlen (path);
3588 set = g_hash_table_new (g_str_hash, g_str_equal);
3590 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3591 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3592 maybe_add_path (path, path_len, object_path, set);
3594 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3595 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3596 maybe_add_path (path, path_len, object_path, set);
3598 p = g_ptr_array_new ();
3599 keys = g_hash_table_get_keys (set);
3600 for (l = keys; l != NULL; l = l->next)
3601 g_ptr_array_add (p, l->data);
3602 g_hash_table_unref (set);
3605 g_ptr_array_add (p, NULL);
3606 ret = (gchar **) g_ptr_array_free (p, FALSE);
3611 g_dbus_connection_list_registered (GDBusConnection *connection,
3615 CONNECTION_LOCK (connection);
3616 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3617 CONNECTION_UNLOCK (connection);
3621 /* called in message handler thread with lock held */
3623 handle_introspect (GDBusConnection *connection,
3625 GDBusMessage *message)
3629 GDBusMessage *reply;
3630 GHashTableIter hash_iter;
3631 ExportedInterface *ei;
3634 /* first the header with the standard interfaces */
3635 s = g_string_sized_new (sizeof (introspect_header) +
3636 sizeof (introspect_standard_interfaces) +
3637 sizeof (introspect_tail));
3638 introspect_append_header (s);
3639 introspect_append_standard_interfaces (s);
3641 /* then include the registered interfaces */
3642 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3643 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3644 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3646 /* finally include nodes registered below us */
3647 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3648 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3649 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3650 g_strfreev (registered);
3651 g_string_append (s, introspect_tail);
3653 reply = g_dbus_message_new_method_reply (message);
3654 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3655 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3656 g_object_unref (reply);
3657 g_string_free (s, TRUE);
3662 /* called in thread where object was registered - no locks held */
3664 call_in_idle_cb (gpointer user_data)
3666 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3667 GDBusInterfaceVTable *vtable;
3669 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3670 g_assert (vtable != NULL && vtable->method_call != NULL);
3672 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3673 g_dbus_method_invocation_get_sender (invocation),
3674 g_dbus_method_invocation_get_object_path (invocation),
3675 g_dbus_method_invocation_get_interface_name (invocation),
3676 g_dbus_method_invocation_get_method_name (invocation),
3677 g_dbus_method_invocation_get_parameters (invocation),
3678 g_object_ref (invocation),
3679 g_dbus_method_invocation_get_user_data (invocation));
3684 /* called in message handler thread with lock held */
3686 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3687 GDBusMessage *message,
3688 const GDBusInterfaceInfo *introspection_data,
3689 const GDBusInterfaceVTable *vtable,
3690 GMainContext *main_context,
3693 GDBusMethodInvocation *invocation;
3694 const GDBusMethodInfo *method_info;
3695 GDBusMessage *reply;
3696 GVariant *parameters;
3697 GSource *idle_source;
3699 gchar *in_signature;
3703 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3704 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3706 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3707 * error to the caller
3709 if (method_info == NULL)
3711 reply = g_dbus_message_new_method_error (message,
3712 "org.freedesktop.DBus.Error.UnknownMethod",
3713 _("No such method `%s'"),
3714 g_dbus_message_get_member (message));
3715 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3716 g_object_unref (reply);
3721 /* Check that the incoming args are of the right type - if they are not, return
3722 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3724 * TODO: might also be worth caching the combined signature.
3726 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3727 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3729 reply = g_dbus_message_new_method_error (message,
3730 "org.freedesktop.DBus.Error.InvalidArgs",
3731 _("Signature of message, `%s', does not match expected signature `%s'"),
3732 g_dbus_message_get_signature (message),
3734 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3735 g_object_unref (reply);
3736 g_free (in_signature);
3740 g_free (in_signature);
3742 parameters = g_dbus_message_get_body (message);
3743 if (parameters == NULL)
3745 parameters = g_variant_new ("()");
3746 g_variant_ref_sink (parameters);
3750 g_variant_ref (parameters);
3753 /* schedule the call in idle */
3754 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3755 g_dbus_message_get_path (message),
3756 g_dbus_message_get_interface (message),
3757 g_dbus_message_get_member (message),
3763 g_variant_unref (parameters);
3764 g_object_set_data (G_OBJECT (invocation),
3765 "g-dbus-interface-vtable",
3768 idle_source = g_idle_source_new ();
3769 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3770 g_source_set_callback (idle_source,
3774 g_source_attach (idle_source, main_context);
3775 g_source_unref (idle_source);
3783 /* ---------------------------------------------------------------------------------------------------- */
3785 /* called in message handler thread with lock held */
3787 obj_message_func (GDBusConnection *connection,
3789 GDBusMessage *message)
3791 const gchar *interface_name;
3792 const gchar *member;
3793 const gchar *signature;
3798 interface_name = g_dbus_message_get_interface (message);
3799 member = g_dbus_message_get_member (message);
3800 signature = g_dbus_message_get_signature (message);
3802 /* see if we have an interface for handling this call */
3803 if (interface_name != NULL)
3805 ExportedInterface *ei;
3806 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3809 /* we do - invoke the handler in idle in the right thread */
3811 /* handle no vtable or handler being present */
3812 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3815 handled = validate_and_maybe_schedule_method_call (connection,
3817 ei->introspection_data,
3825 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3826 g_strcmp0 (member, "Introspect") == 0 &&
3827 g_strcmp0 (signature, "") == 0)
3829 handled = handle_introspect (connection, eo, message);
3832 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3833 g_strcmp0 (member, "Get") == 0 &&
3834 g_strcmp0 (signature, "ss") == 0)
3836 handled = handle_getset_property (connection, eo, message, TRUE);
3839 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3840 g_strcmp0 (member, "Set") == 0 &&
3841 g_strcmp0 (signature, "ssv") == 0)
3843 handled = handle_getset_property (connection, eo, message, FALSE);
3846 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3847 g_strcmp0 (member, "GetAll") == 0 &&
3848 g_strcmp0 (signature, "s") == 0)
3850 handled = handle_get_all_properties (connection, eo, message);
3859 * g_dbus_connection_register_object:
3860 * @connection: A #GDBusConnection.
3861 * @object_path: The object path to register at.
3862 * @interface_name: The D-Bus interface to register.
3863 * @introspection_data: Introspection data for the interface.
3864 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3865 * @user_data: Data to pass to functions in @vtable.
3866 * @user_data_free_func: Function to call when the object path is unregistered.
3867 * @error: Return location for error or %NULL.
3869 * Registers callbacks for exported objects at @object_path with the
3870 * D-Bus interface @interface_name.
3872 * Calls to functions in @vtable (and @user_data_free_func) will
3873 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3874 * loop</link> of the thread you are calling this method from.
3876 * Note that all #GVariant values passed to functions in @vtable will match
3877 * the signature given in @introspection_data - if a remote caller passes
3878 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3879 * is returned to the remote caller.
3881 * Additionally, if the remote caller attempts to invoke methods or
3882 * access properties not mentioned in @introspection_data the
3883 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3884 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3885 * are returned to the caller.
3887 * It is considered a programming error if the
3888 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3889 * #GVariant of incorrect type.
3891 * If an existing callback is already registered at @object_path and
3892 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3894 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3896 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3897 * that can be used with g_dbus_connection_unregister_object() .
3902 g_dbus_connection_register_object (GDBusConnection *connection,
3903 const gchar *object_path,
3904 const gchar *interface_name,
3905 const GDBusInterfaceInfo *introspection_data,
3906 const GDBusInterfaceVTable *vtable,
3908 GDestroyNotify user_data_free_func,
3912 ExportedInterface *ei;
3915 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3916 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3917 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3918 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3919 g_return_val_if_fail (introspection_data != NULL, 0);
3920 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3924 CONNECTION_LOCK (connection);
3926 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3929 eo = g_new0 (ExportedObject, 1);
3930 eo->object_path = g_strdup (object_path);
3931 eo->connection = connection;
3932 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3935 (GDestroyNotify) exported_interface_free);
3936 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3939 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3945 _("An object is already exported for the interface %s at %s"),
3951 ei = g_new0 (ExportedInterface, 1);
3952 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3954 ei->user_data = user_data;
3955 ei->user_data_free_func = user_data_free_func;
3956 ei->vtable = vtable;
3957 ei->introspection_data = introspection_data;
3958 ei->interface_name = g_strdup (interface_name);
3959 ei->context = g_main_context_get_thread_default ();
3960 if (ei->context != NULL)
3961 g_main_context_ref (ei->context);
3963 g_hash_table_insert (eo->map_if_name_to_ei,
3964 (gpointer) ei->interface_name,
3966 g_hash_table_insert (connection->priv->map_id_to_ei,
3967 GUINT_TO_POINTER (ei->id),
3973 CONNECTION_UNLOCK (connection);
3979 * g_dbus_connection_unregister_object:
3980 * @connection: A #GDBusConnection.
3981 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
3983 * Unregisters an object.
3985 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
3990 g_dbus_connection_unregister_object (GDBusConnection *connection,
3991 guint registration_id)
3993 ExportedInterface *ei;
3997 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4001 CONNECTION_LOCK (connection);
4003 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4004 GUINT_TO_POINTER (registration_id));
4010 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4011 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4012 /* unregister object path if we have no more exported interfaces */
4013 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4014 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4020 CONNECTION_UNLOCK (connection);
4025 /* ---------------------------------------------------------------------------------------------------- */
4028 * g_dbus_connection_emit_signal:
4029 * @connection: A #GDBusConnection.
4030 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4031 * @object_path: Path of remote object.
4032 * @interface_name: D-Bus interface to emit a signal on.
4033 * @signal_name: The name of the signal to emit.
4034 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4035 * @error: Return location for error or %NULL.
4039 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4041 * Returns: %TRUE unless @error is set.
4046 g_dbus_connection_emit_signal (GDBusConnection *connection,
4047 const gchar *destination_bus_name,
4048 const gchar *object_path,
4049 const gchar *interface_name,
4050 const gchar *signal_name,
4051 GVariant *parameters,
4054 GDBusMessage *message;
4060 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4061 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4062 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4063 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4064 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4065 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4067 message = g_dbus_message_new_signal (object_path,
4071 if (destination_bus_name != NULL)
4072 g_dbus_message_set_header (message,
4073 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4074 g_variant_new_string (destination_bus_name));
4076 if (parameters != NULL)
4077 g_dbus_message_set_body (message, parameters);
4079 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4080 g_object_unref (message);
4086 add_call_flags (GDBusMessage *message,
4087 GDBusCallFlags flags)
4089 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4090 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4094 * g_dbus_connection_call:
4095 * @connection: A #GDBusConnection.
4096 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4097 * @object_path: Path of remote object.
4098 * @interface_name: D-Bus interface to invoke method on.
4099 * @method_name: The name of the method to invoke.
4100 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4101 * @flags: Flags from the #GDBusCallFlags enumeration.
4102 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4103 * @cancellable: A #GCancellable or %NULL.
4104 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4105 * care about the result of the method invocation.
4106 * @user_data: The data to pass to @callback.
4108 * Asynchronously invokes the @method_name method on the
4109 * @interface_name D-Bus interface on the remote object at
4110 * @object_path owned by @bus_name.
4112 * If @connection is closed then the operation will fail with
4113 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4114 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4115 * not compatible with the D-Bus protocol, the operation fails with
4116 * %G_IO_ERROR_INVALID_ARGUMENT.
4118 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4119 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4120 * of the thread you are calling this method from. You can then call
4121 * g_dbus_connection_call_finish() to get the result of the operation.
4122 * See g_dbus_connection_call_sync() for the synchronous version of this
4128 g_dbus_connection_call (GDBusConnection *connection,
4129 const gchar *bus_name,
4130 const gchar *object_path,
4131 const gchar *interface_name,
4132 const gchar *method_name,
4133 GVariant *parameters,
4134 GDBusCallFlags flags,
4136 GCancellable *cancellable,
4137 GAsyncReadyCallback callback,
4140 GDBusMessage *message;
4142 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4143 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4144 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4145 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4146 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4147 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4148 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4150 message = g_dbus_message_new_method_call (bus_name,
4154 add_call_flags (message, flags);
4155 if (parameters != NULL)
4156 g_dbus_message_set_body (message, parameters);
4158 g_dbus_connection_send_message_with_reply (connection,
4161 NULL, /* volatile guint32 *out_serial */
4166 if (message != NULL)
4167 g_object_unref (message);
4171 decode_method_reply (GDBusMessage *reply,
4177 switch (g_dbus_message_get_message_type (reply))
4179 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4180 result = g_dbus_message_get_body (reply);
4183 result = g_variant_new ("()");
4184 g_variant_ref_sink (result);
4188 g_variant_ref (result);
4192 case G_DBUS_MESSAGE_TYPE_ERROR:
4193 g_dbus_message_to_gerror (reply, error);
4197 g_assert_not_reached ();
4205 * g_dbus_connection_call_finish:
4206 * @connection: A #GDBusConnection.
4207 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4208 * @error: Return location for error or %NULL.
4210 * Finishes an operation started with g_dbus_connection_call().
4212 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4213 * return values. Free with g_variant_unref().
4218 g_dbus_connection_call_finish (GDBusConnection *connection,
4222 GDBusMessage *reply;
4225 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4226 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4227 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4231 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4235 result = decode_method_reply (reply, error);
4237 g_object_unref (reply);
4243 /* ---------------------------------------------------------------------------------------------------- */
4246 * g_dbus_connection_call_sync:
4247 * @connection: A #GDBusConnection.
4248 * @bus_name: A unique or well-known bus name.
4249 * @object_path: Path of remote object.
4250 * @interface_name: D-Bus interface to invoke method on.
4251 * @method_name: The name of the method to invoke.
4252 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4253 * @flags: Flags from the #GDBusCallFlags enumeration.
4254 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4255 * @cancellable: A #GCancellable or %NULL.
4256 * @error: Return location for error or %NULL.
4258 * Synchronously invokes the @method_name method on the
4259 * @interface_name D-Bus interface on the remote object at
4260 * @object_path owned by @bus_name.
4262 * If @connection is closed then the operation will fail with
4263 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4264 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4265 * contains a value not compatible with the D-Bus protocol, the operation
4266 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4268 * The calling thread is blocked until a reply is received. See
4269 * g_dbus_connection_call() for the asynchronous version of
4272 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4273 * return values. Free with g_variant_unref().
4278 g_dbus_connection_call_sync (GDBusConnection *connection,
4279 const gchar *bus_name,
4280 const gchar *object_path,
4281 const gchar *interface_name,
4282 const gchar *method_name,
4283 GVariant *parameters,
4284 GDBusCallFlags flags,
4286 GCancellable *cancellable,
4289 GDBusMessage *message;
4290 GDBusMessage *reply;
4297 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4298 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4299 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4300 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4301 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4302 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4303 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4305 message = g_dbus_message_new_method_call (bus_name,
4309 add_call_flags (message, flags);
4310 if (parameters != NULL)
4311 g_dbus_message_set_body (message, parameters);
4313 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4316 NULL, /* volatile guint32 *out_serial */
4323 result = decode_method_reply (reply, error);
4326 if (message != NULL)
4327 g_object_unref (message);
4329 g_object_unref (reply);
4334 /* ---------------------------------------------------------------------------------------------------- */
4336 struct ExportedSubtree
4340 GDBusConnection *connection;
4341 const GDBusSubtreeVTable *vtable;
4342 GDBusSubtreeFlags flags;
4344 GMainContext *context;
4346 GDestroyNotify user_data_free_func;
4350 exported_subtree_free (ExportedSubtree *es)
4352 if (es->user_data_free_func != NULL)
4353 /* TODO: push to thread-default mainloop */
4354 es->user_data_free_func (es->user_data);
4356 if (es->context != NULL)
4357 g_main_context_unref (es->context);
4359 g_free (es->object_path);
4363 /* called without lock held */
4365 handle_subtree_introspect (GDBusConnection *connection,
4366 ExportedSubtree *es,
4367 GDBusMessage *message)
4371 GDBusMessage *reply;
4374 const gchar *sender;
4375 const gchar *requested_object_path;
4376 const gchar *requested_node;
4377 GPtrArray *interfaces;
4379 gchar **subnode_paths;
4383 requested_object_path = g_dbus_message_get_path (message);
4384 sender = g_dbus_message_get_sender (message);
4385 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4387 s = g_string_new (NULL);
4388 introspect_append_header (s);
4390 /* Strictly we don't need the children in dynamic mode, but we avoid the
4391 * conditionals to preserve code clarity
4393 children = es->vtable->enumerate (es->connection,
4400 requested_node = strrchr (requested_object_path, '/') + 1;
4402 /* Assert existence of object if we are not dynamic */
4403 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4404 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4409 requested_node = "/";
4412 interfaces = es->vtable->introspect (es->connection,
4417 if (interfaces != NULL)
4419 if (interfaces->len > 0)
4421 /* we're in business */
4422 introspect_append_standard_interfaces (s);
4424 for (n = 0; n < interfaces->len; n++)
4426 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4427 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4430 g_ptr_array_unref (interfaces);
4433 /* then include <node> entries from the Subtree for the root */
4436 for (n = 0; children != NULL && children[n] != NULL; n++)
4437 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4440 /* finally include nodes registered below us */
4441 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4442 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4443 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4444 g_strfreev (subnode_paths);
4446 g_string_append (s, "</node>\n");
4448 reply = g_dbus_message_new_method_reply (message);
4449 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4450 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4451 g_object_unref (reply);
4456 g_string_free (s, TRUE);
4457 g_strfreev (children);
4461 /* called without lock held */
4463 handle_subtree_method_invocation (GDBusConnection *connection,
4464 ExportedSubtree *es,
4465 GDBusMessage *message)
4468 const gchar *sender;
4469 const gchar *interface_name;
4470 const gchar *member;
4471 const gchar *signature;
4472 const gchar *requested_object_path;
4473 const gchar *requested_node;
4476 const GDBusInterfaceInfo *introspection_data;
4477 const GDBusInterfaceVTable *interface_vtable;
4478 gpointer interface_user_data;
4480 GPtrArray *interfaces;
4481 gboolean is_property_get;
4482 gboolean is_property_set;
4483 gboolean is_property_get_all;
4488 requested_object_path = g_dbus_message_get_path (message);
4489 sender = g_dbus_message_get_sender (message);
4490 interface_name = g_dbus_message_get_interface (message);
4491 member = g_dbus_message_get_member (message);
4492 signature = g_dbus_message_get_signature (message);
4493 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4495 is_property_get = FALSE;
4496 is_property_set = FALSE;
4497 is_property_get_all = FALSE;
4498 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4500 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4501 is_property_get = TRUE;
4502 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4503 is_property_set = TRUE;
4504 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4505 is_property_get_all = TRUE;
4508 children = es->vtable->enumerate (es->connection,
4515 requested_node = strrchr (requested_object_path, '/') + 1;
4517 /* If not dynamic, skip if requested node is not part of children */
4518 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4519 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4524 requested_node = "/";
4527 /* get introspection data for the node */
4528 interfaces = es->vtable->introspect (es->connection,
4530 requested_object_path,
4533 g_assert (interfaces != NULL);
4534 introspection_data = NULL;
4535 for (n = 0; n < interfaces->len; n++)
4537 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4538 if (g_strcmp0 (id_n->name, interface_name) == 0)
4539 introspection_data = id_n;
4542 /* dispatch the call if the user wants to handle it */
4543 if (introspection_data != NULL)
4545 /* figure out where to dispatch the method call */
4546 interface_user_data = NULL;
4547 interface_vtable = es->vtable->dispatch (es->connection,
4552 &interface_user_data,
4554 if (interface_vtable == NULL)
4557 CONNECTION_LOCK (connection);
4558 handled = validate_and_maybe_schedule_method_call (es->connection,
4563 interface_user_data);
4564 CONNECTION_UNLOCK (connection);
4566 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4567 else if (is_property_get || is_property_set || is_property_get_all)
4569 if (is_property_get)
4570 g_variant_get (g_dbus_message_get_body (message), "(ss)", &interface_name, NULL);
4571 else if (is_property_set)
4572 g_variant_get (g_dbus_message_get_body (message), "(ssv)", &interface_name, NULL, NULL);
4573 else if (is_property_get_all)
4574 g_variant_get (g_dbus_message_get_body (message), "(s)", &interface_name, NULL, NULL);
4576 g_assert_not_reached ();
4578 /* see if the object supports this interface at all */
4579 for (n = 0; n < interfaces->len; n++)
4581 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4582 if (g_strcmp0 (id_n->name, interface_name) == 0)
4583 introspection_data = id_n;
4586 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4587 * claims it won't support the interface
4589 if (introspection_data == NULL)
4591 GDBusMessage *reply;
4592 reply = g_dbus_message_new_method_error (message,
4593 "org.freedesktop.DBus.Error.InvalidArgs",
4594 _("No such interface `%s'"),
4596 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4597 g_object_unref (reply);
4602 /* figure out where to dispatch the property get/set/getall calls */
4603 interface_user_data = NULL;
4604 interface_vtable = es->vtable->dispatch (es->connection,
4609 &interface_user_data,
4611 if (interface_vtable == NULL)
4614 if (is_property_get || is_property_set)
4616 CONNECTION_LOCK (connection);
4617 handled = validate_and_maybe_schedule_property_getset (es->connection,
4623 interface_user_data);
4624 CONNECTION_UNLOCK (connection);
4626 else if (is_property_get_all)
4628 CONNECTION_LOCK (connection);
4629 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4634 interface_user_data);
4635 CONNECTION_UNLOCK (connection);
4640 if (interfaces != NULL)
4641 g_ptr_array_unref (interfaces);
4642 g_strfreev (children);
4648 GDBusMessage *message;
4649 ExportedSubtree *es;
4650 } SubtreeDeferredData;
4653 subtree_deferred_data_free (SubtreeDeferredData *data)
4655 g_object_unref (data->message);
4659 /* called without lock held in the thread where the caller registered the subtree */
4661 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4663 SubtreeDeferredData *data = _data;
4668 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4669 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4670 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4671 handled = handle_subtree_introspect (data->es->connection,
4675 handled = handle_subtree_method_invocation (data->es->connection,
4681 CONNECTION_LOCK (data->es->connection);
4682 handled = handle_generic_unlocked (data->es->connection, data->message);
4683 CONNECTION_UNLOCK (data->es->connection);
4686 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4689 GDBusMessage *reply;
4690 reply = g_dbus_message_new_method_error (data->message,
4691 "org.freedesktop.DBus.Error.UnknownMethod",
4692 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4693 g_dbus_message_get_member (data->message),
4694 g_dbus_message_get_interface (data->message),
4695 g_dbus_message_get_signature (data->message));
4696 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4697 g_object_unref (reply);
4703 /* called in message handler thread with lock held */
4705 subtree_message_func (GDBusConnection *connection,
4706 ExportedSubtree *es,
4707 GDBusMessage *message)
4709 GSource *idle_source;
4710 SubtreeDeferredData *data;
4712 data = g_new0 (SubtreeDeferredData, 1);
4713 data->message = g_object_ref (message);
4716 /* defer this call to an idle handler in the right thread */
4717 idle_source = g_idle_source_new ();
4718 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4719 g_source_set_callback (idle_source,
4720 process_subtree_vtable_message_in_idle_cb,
4722 (GDestroyNotify) subtree_deferred_data_free);
4723 g_source_attach (idle_source, es->context);
4724 g_source_unref (idle_source);
4726 /* since we own the entire subtree, handlers for objects not in the subtree have been
4727 * tried already by libdbus-1 - so we just need to ensure that we're always going
4728 * to reply to the message
4734 * g_dbus_connection_register_subtree:
4735 * @connection: A #GDBusConnection.
4736 * @object_path: The object path to register the subtree at.
4737 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4738 * @flags: Flags used to fine tune the behavior of the subtree.
4739 * @user_data: Data to pass to functions in @vtable.
4740 * @user_data_free_func: Function to call when the subtree is unregistered.
4741 * @error: Return location for error or %NULL.
4743 * Registers a whole subtree of <quote>dynamic</quote> objects.
4745 * The @enumerate and @introspection functions in @vtable are used to
4746 * convey, to remote callers, what nodes exist in the subtree rooted
4749 * When handling remote calls into any node in the subtree, first the
4750 * @enumerate function is used to check if the node exists. If the node exists
4751 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4752 * the @introspection function is used to check if the node supports the
4753 * requested method. If so, the @dispatch function is used to determine
4754 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4755 * #gpointer will be used to call into the interface vtable for processing
4758 * All calls into user-provided code will be invoked in the <link
4759 * linkend="g-main-context-push-thread-default">thread-default main
4760 * loop</link> of the thread you are calling this method from.
4762 * If an existing subtree is already registered at @object_path or
4763 * then @error is set to #G_IO_ERROR_EXISTS.
4765 * Note that it is valid to register regular objects (using
4766 * g_dbus_connection_register_object()) in a subtree registered with
4767 * g_dbus_connection_register_subtree() - if so, the subtree handler
4768 * is tried as the last resort. One way to think about a subtree
4769 * handler is to consider it a <quote>fallback handler</quote>
4770 * for object paths not registered via g_dbus_connection_register_object()
4771 * or other bindings.
4773 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4775 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4776 * that can be used with g_dbus_connection_unregister_subtree() .
4781 g_dbus_connection_register_subtree (GDBusConnection *connection,
4782 const gchar *object_path,
4783 const GDBusSubtreeVTable *vtable,
4784 GDBusSubtreeFlags flags,
4786 GDestroyNotify user_data_free_func,
4790 ExportedSubtree *es;
4792 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4793 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4794 g_return_val_if_fail (vtable != NULL, 0);
4795 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4799 CONNECTION_LOCK (connection);
4801 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4807 _("A subtree is already exported for %s"),
4812 es = g_new0 (ExportedSubtree, 1);
4813 es->object_path = g_strdup (object_path);
4814 es->connection = connection;
4816 es->vtable = vtable;
4818 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4819 es->user_data = user_data;
4820 es->user_data_free_func = user_data_free_func;
4821 es->context = g_main_context_get_thread_default ();
4822 if (es->context != NULL)
4823 g_main_context_ref (es->context);
4825 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4826 g_hash_table_insert (connection->priv->map_id_to_es,
4827 GUINT_TO_POINTER (es->id),
4833 CONNECTION_UNLOCK (connection);
4838 /* ---------------------------------------------------------------------------------------------------- */
4841 * g_dbus_connection_unregister_subtree:
4842 * @connection: A #GDBusConnection.
4843 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4845 * Unregisters a subtree.
4847 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4852 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4853 guint registration_id)
4855 ExportedSubtree *es;
4858 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4862 CONNECTION_LOCK (connection);
4864 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4865 GUINT_TO_POINTER (registration_id));
4869 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4870 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4875 CONNECTION_UNLOCK (connection);
4880 /* ---------------------------------------------------------------------------------------------------- */
4882 /* must be called with lock held */
4884 handle_generic_ping_unlocked (GDBusConnection *connection,
4885 const gchar *object_path,
4886 GDBusMessage *message)
4888 GDBusMessage *reply;
4889 reply = g_dbus_message_new_method_reply (message);
4890 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4891 g_object_unref (reply);
4894 /* must be called with lock held */
4896 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4897 const gchar *object_path,
4898 GDBusMessage *message)
4900 GDBusMessage *reply;
4903 if (connection->priv->machine_id == NULL)
4907 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4908 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4909 &connection->priv->machine_id,
4913 reply = g_dbus_message_new_method_error (message,
4914 "org.freedesktop.DBus.Error.Failed",
4915 _("Unable to load /var/lib/dbus/machine-id: %s"),
4917 g_error_free (error);
4921 g_strstrip (connection->priv->machine_id);
4922 /* TODO: validate value */
4928 reply = g_dbus_message_new_method_reply (message);
4929 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
4931 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4932 g_object_unref (reply);
4935 /* must be called with lock held */
4937 handle_generic_introspect_unlocked (GDBusConnection *connection,
4938 const gchar *object_path,
4939 GDBusMessage *message)
4944 GDBusMessage *reply;
4946 /* first the header */
4947 s = g_string_new (NULL);
4948 introspect_append_header (s);
4950 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
4951 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4952 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4953 g_strfreev (registered);
4954 g_string_append (s, "</node>\n");
4956 reply = g_dbus_message_new_method_reply (message);
4957 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4958 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4959 g_object_unref (reply);
4960 g_string_free (s, TRUE);
4963 /* must be called with lock held */
4965 handle_generic_unlocked (GDBusConnection *connection,
4966 GDBusMessage *message)
4969 const gchar *interface_name;
4970 const gchar *member;
4971 const gchar *signature;
4974 CONNECTION_ENSURE_LOCK (connection);
4978 interface_name = g_dbus_message_get_interface (message);
4979 member = g_dbus_message_get_member (message);
4980 signature = g_dbus_message_get_signature (message);
4981 path = g_dbus_message_get_path (message);
4983 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4984 g_strcmp0 (member, "Introspect") == 0 &&
4985 g_strcmp0 (signature, "") == 0)
4987 handle_generic_introspect_unlocked (connection, path, message);
4990 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4991 g_strcmp0 (member, "Ping") == 0 &&
4992 g_strcmp0 (signature, "") == 0)
4994 handle_generic_ping_unlocked (connection, path, message);
4997 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
4998 g_strcmp0 (member, "GetMachineId") == 0 &&
4999 g_strcmp0 (signature, "") == 0)
5001 handle_generic_get_machine_id_unlocked (connection, path, message);
5008 /* ---------------------------------------------------------------------------------------------------- */
5010 /* called in message handler thread with lock held */
5012 distribute_method_call (GDBusConnection *connection,
5013 GDBusMessage *message)
5016 ExportedSubtree *es;
5017 const gchar *object_path;
5018 const gchar *interface_name;
5019 const gchar *member;
5020 const gchar *signature;
5022 gchar *subtree_path;
5025 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5027 interface_name = g_dbus_message_get_interface (message);
5028 member = g_dbus_message_get_member (message);
5029 signature = g_dbus_message_get_signature (message);
5030 path = g_dbus_message_get_path (message);
5031 subtree_path = g_strdup (path);
5032 needle = strrchr (subtree_path, '/');
5033 if (needle != NULL && needle != subtree_path)
5039 g_free (subtree_path);
5040 subtree_path = NULL;
5044 g_debug ("interface = `%s'", interface_name);
5045 g_debug ("member = `%s'", member);
5046 g_debug ("signature = `%s'", signature);
5047 g_debug ("path = `%s'", path);
5048 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5051 object_path = g_dbus_message_get_path (message);
5052 g_assert (object_path != NULL);
5054 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5057 if (obj_message_func (connection, eo, message))
5061 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5064 if (subtree_message_func (connection, es, message))
5068 if (subtree_path != NULL)
5070 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5073 if (subtree_message_func (connection, es, message))
5078 if (handle_generic_unlocked (connection, message))
5081 /* if we end up here, the message has not been not handled */
5084 g_free (subtree_path);
5087 /* ---------------------------------------------------------------------------------------------------- */
5089 static GDBusConnection **
5090 message_bus_get_singleton (GBusType bus_type,
5093 GDBusConnection **ret;
5094 const gchar *starter_bus;
5100 case G_BUS_TYPE_SESSION:
5101 ret = &the_session_bus;
5104 case G_BUS_TYPE_SYSTEM:
5105 ret = &the_system_bus;
5108 case G_BUS_TYPE_STARTER:
5109 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5110 if (g_strcmp0 (starter_bus, "session") == 0)
5112 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5115 else if (g_strcmp0 (starter_bus, "system") == 0)
5117 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5122 if (starter_bus != NULL)
5126 G_IO_ERROR_INVALID_ARGUMENT,
5127 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5128 " - unknown value `%s'"),
5133 g_set_error_literal (error,
5135 G_IO_ERROR_INVALID_ARGUMENT,
5136 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5137 "variable is not set"));
5143 g_assert_not_reached ();
5151 static GDBusConnection *
5152 get_uninitialized_connection (GBusType bus_type,
5153 GCancellable *cancellable,
5156 GDBusConnection **singleton;
5157 GDBusConnection *ret;
5161 G_LOCK (message_bus_lock);
5162 singleton = message_bus_get_singleton (bus_type, error);
5163 if (singleton == NULL)
5166 if (*singleton == NULL)
5169 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5170 if (address == NULL)
5172 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5174 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5175 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5176 "exit-on-close", TRUE,
5181 ret = g_object_ref (*singleton);
5184 g_assert (ret != NULL);
5187 G_UNLOCK (message_bus_lock);
5193 * @bus_type: A #GBusType.
5194 * @cancellable: A #GCancellable or %NULL.
5195 * @error: Return location for error or %NULL.
5197 * Synchronously connects to the message bus specified by @bus_type.
5198 * Note that the returned object may shared with other callers,
5199 * e.g. if two separate parts of a process calls this function with
5200 * the same @bus_type, they will share the same object.
5202 * This is a synchronous failable function. See g_bus_get() and
5203 * g_bus_get_finish() for the asynchronous version.
5205 * The returned object is a singleton, that is, shared with other
5206 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5207 * event that you need a private message bus connection, use
5208 * g_dbus_address_get_for_bus() and
5209 * g_dbus_connection_new_for_address().
5211 * Note that the returned #GDBusConnection object will (usually) have
5212 * the #GDBusConnection:exit-on-close property set to %TRUE.
5214 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5219 g_bus_get_sync (GBusType bus_type,
5220 GCancellable *cancellable,
5223 GDBusConnection *connection;
5225 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5227 connection = get_uninitialized_connection (bus_type, cancellable, error);
5228 if (connection == NULL)
5231 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5233 g_object_unref (connection);
5242 bus_get_async_initable_cb (GObject *source_object,
5246 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5250 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5254 g_assert (error != NULL);
5255 g_simple_async_result_set_from_error (simple, error);
5256 g_error_free (error);
5257 g_object_unref (source_object);
5261 g_simple_async_result_set_op_res_gpointer (simple,
5265 g_simple_async_result_complete_in_idle (simple);
5266 g_object_unref (simple);
5271 * @bus_type: A #GBusType.
5272 * @cancellable: A #GCancellable or %NULL.
5273 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5274 * @user_data: The data to pass to @callback.
5276 * Asynchronously connects to the message bus specified by @bus_type.
5278 * When the operation is finished, @callback will be invoked. You can
5279 * then call g_bus_get_finish() to get the result of the operation.
5281 * This is a asynchronous failable function. See g_bus_get_sync() for
5282 * the synchronous version.
5287 g_bus_get (GBusType bus_type,
5288 GCancellable *cancellable,
5289 GAsyncReadyCallback callback,
5292 GDBusConnection *connection;
5293 GSimpleAsyncResult *simple;
5296 simple = g_simple_async_result_new (NULL,
5302 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5303 if (connection == NULL)
5305 g_assert (error != NULL);
5306 g_simple_async_result_set_from_error (simple, error);
5307 g_error_free (error);
5308 g_simple_async_result_complete_in_idle (simple);
5309 g_object_unref (simple);
5313 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5316 bus_get_async_initable_cb,
5323 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5324 * @error: Return location for error or %NULL.
5326 * Finishes an operation started with g_bus_get().
5328 * The returned object is a singleton, that is, shared with other
5329 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5330 * event that you need a private message bus connection, use
5331 * g_dbus_address_get_for_bus() and
5332 * g_dbus_connection_new_for_address().
5334 * Note that the returned #GDBusConnection object will (usually) have
5335 * the #GDBusConnection:exit-on-close property set to %TRUE.
5337 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5342 g_bus_get_finish (GAsyncResult *res,
5345 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5347 GDBusConnection *ret;
5349 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5351 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5355 if (g_simple_async_result_propagate_error (simple, error))
5358 object = g_simple_async_result_get_op_res_gpointer (simple);
5359 g_assert (object != NULL);
5360 ret = g_object_ref (G_DBUS_CONNECTION (object));
5366 /* ---------------------------------------------------------------------------------------------------- */
5368 #define __G_DBUS_CONNECTION_C__
5369 #include "gioaliasdef.c"