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 * - Validate all data (e.g. UTF-8) and check all the required D-Bus headers
27 * are present and forbidden ones aren't
28 * - When writing: g_dbus_message_to_blob()
29 * - When reading: g_dbus_message_new_from_blob()
31 * - would be nice to expose GDBusAuthMechanism and an extension point
33 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
34 * the mechanism VFuncs need to be able to set an error.
36 * - Need to document other mechanisms/sources for determining the D-Bus
37 * address of a well-known bus.
39 * - e.g. on Win32 we need code like from here
41 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
43 * that was never copied over here because it originally was copy-paste
44 * from the GPLv2 / AFL 2.1 libdbus sources.
46 * - on OS X we need to look in launchd for the address
48 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
50 * - on X11 we need to look in a X11 property on the X server
51 * - (we can also just use dbus-launch(1) from the D-Bus
54 * - (ideally) this requires D-Bus spec work because none of
55 * this has never really been specced out properly (excect
58 * - Related to the above, we also need to be able to launch a message bus
59 * instance.... Since we don't want to write our own bus daemon we should
60 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
62 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
63 * to specify where the nonce is stored. This will allow people to use
64 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
65 * to easily acheive secure RPC via nonce-tcp.
67 * - need to expose an extension point for resolving D-Bus address and
68 * turning them into GIOStream objects. This will allow us to implement
69 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
71 * - see g_dbus_address_connect() in gdbusaddress.c
73 * - would be cute to use kernel-specific APIs to resolve fds for
74 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
76 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
78 * maybe we can show more information about what fd 21 really is.
79 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
80 * Initial experiments on Linux 2.6 suggests that the symlink looks
85 * e.g. not of much use.
87 * - GDBus High-Level docs
88 * - Proxy: properties, signals...
89 * - Connection: IOStream based, ::close, connection setup steps
90 * mainloop integration, threading
91 * - Differences from libdbus (extend "Migrating from")
92 * - the message handling thread
93 * - Using GVariant instead of GValue
94 * - Explain why the high-level API is a good thing and what
95 * kind of pitfalls it avoids
96 * - Export objects before claiming names
97 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
104 #include <sys/types.h>
109 #include "gdbusauth.h"
110 #include "gdbusutils.h"
111 #include "gdbusaddress.h"
112 #include "gdbusmessage.h"
113 #include "gdbusconnection.h"
114 #include "gdbuserror.h"
115 #include "gioenumtypes.h"
116 #include "gdbusintrospection.h"
117 #include "gdbusmethodinvocation.h"
118 #include "gdbusprivate.h"
119 #include "gdbusauthobserver.h"
120 #include "gio-marshal.h"
121 #include "ginitable.h"
122 #include "gasyncinitable.h"
123 #include "giostream.h"
124 #include "gasyncresult.h"
125 #include "gsimpleasyncresult.h"
128 #include "gunixconnection.h"
129 #include "gunixfdmessage.h"
132 #include "glibintl.h"
133 #include "gioalias.h"
136 * SECTION:gdbusconnection
137 * @short_description: D-Bus Connections
138 * @include: gio/gio.h
140 * The #GDBusConnection type is used for D-Bus connections to remote
141 * peers such as a message buses. It is a low-level API that offers a
142 * lot of flexibility. For instance, it lets you establish a connection
143 * over any transport that can by represented as an #GIOStream.
145 * This class is rarely used directly in D-Bus clients. If you are writing
146 * an D-Bus client, it is often easier to use the g_bus_own_name(),
147 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
149 * <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>
151 * <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>
153 * <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>
155 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
158 /* ---------------------------------------------------------------------------------------------------- */
160 G_LOCK_DEFINE_STATIC (message_bus_lock);
162 static GDBusConnection *the_session_bus = NULL;
163 static GDBusConnection *the_system_bus = NULL;
165 /* ---------------------------------------------------------------------------------------------------- */
168 _g_strv_has_string (const gchar* const *haystack,
173 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
175 if (g_strcmp0 (haystack[n], needle) == 0)
181 /* ---------------------------------------------------------------------------------------------------- */
184 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
186 // TODO: for some reason this doesn't work on Windows
187 #define CONNECTION_ENSURE_LOCK(obj) do { \
188 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
190 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
191 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
196 #define CONNECTION_LOCK(obj) do { \
197 g_mutex_lock ((obj)->priv->lock); \
200 #define CONNECTION_UNLOCK(obj) do { \
201 g_mutex_unlock ((obj)->priv->lock); \
204 struct _GDBusConnectionPrivate
206 /* ------------------------------------------------------------------------ */
207 /* -- General object state ------------------------------------------------ */
208 /* ------------------------------------------------------------------------ */
210 /* object-wide lock */
213 /* A lock used in the init() method of the GInitable interface - see comments
214 * in initable_init() for why a separate lock is needed
218 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
219 * someone calls org.freedesktop.DBus.GetMachineId()
223 /* The underlying stream used for communication */
226 /* The object used for authentication (if any) */
229 /* Set to TRUE if the connection has been closed */
232 /* Last serial used */
235 /* The object used to send/receive message */
238 /* If connected to a message bus, this contains the unique name assigned to
239 * us by the bus (e.g. ":1.42")
241 gchar *bus_unique_name;
243 /* The GUID returned by the other side if we authenticed as a client or
244 * the GUID to use if authenticating as a server
248 /* set to TRUE exactly when initable_init() has finished running */
249 gboolean is_initialized;
251 /* If the connection could not be established during initable_init(), this GError will set */
252 GError *initialization_error;
254 /* The result of g_main_context_get_thread_default() when the object
255 * was created (the GObject _init() function) - this is used for delivery
256 * of the :closed GObject signal.
258 GMainContext *main_context_at_construction;
260 /* construct properties */
262 GDBusConnectionFlags flags;
264 /* Map used for managing method replies */
265 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
267 /* Maps used for managing signal subscription */
268 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
269 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
270 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
272 /* Maps used for managing exported objects and subtrees */
273 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
274 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
275 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
276 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
278 /* Structure used for message filters */
281 /* Whether to exit on close */
282 gboolean exit_on_close;
284 /* Capabilities negotiated during authentication */
285 GDBusCapabilityFlags capabilities;
287 GDBusAuthObserver *authentication_observer;
288 GCredentials *crendentials;
291 typedef struct ExportedObject ExportedObject;
292 static void exported_object_free (ExportedObject *eo);
294 typedef struct ExportedSubtree ExportedSubtree;
295 static void exported_subtree_free (ExportedSubtree *es);
313 PROP_CAPABILITY_FLAGS,
314 PROP_AUTHENTICATION_OBSERVER,
317 static void distribute_signals (GDBusConnection *connection,
318 GDBusMessage *message);
320 static void distribute_method_call (GDBusConnection *connection,
321 GDBusMessage *message);
323 static gboolean handle_generic_unlocked (GDBusConnection *connection,
324 GDBusMessage *message);
327 static void purge_all_signal_subscriptions (GDBusConnection *connection);
328 static void purge_all_filters (GDBusConnection *connection);
330 #define _G_ENSURE_LOCK(name) do { \
331 if (G_UNLIKELY (G_TRYLOCK(name))) \
333 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
334 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
338 static guint signals[LAST_SIGNAL] = { 0 };
340 static void initable_iface_init (GInitableIface *initable_iface);
341 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
343 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
344 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
345 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
349 g_dbus_connection_dispose (GObject *object)
351 GDBusConnection *connection = G_DBUS_CONNECTION (object);
353 G_LOCK (message_bus_lock);
354 //g_debug ("disposing %p", connection);
355 if (connection == the_session_bus)
357 the_session_bus = NULL;
359 else if (connection == the_system_bus)
361 the_system_bus = NULL;
363 if (connection->priv->worker != NULL)
365 _g_dbus_worker_stop (connection->priv->worker);
366 connection->priv->worker = NULL;
368 G_UNLOCK (message_bus_lock);
370 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
371 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
375 g_dbus_connection_finalize (GObject *object)
377 GDBusConnection *connection = G_DBUS_CONNECTION (object);
379 if (connection->priv->authentication_observer != NULL)
380 g_object_unref (connection->priv->authentication_observer);
382 if (connection->priv->auth != NULL)
383 g_object_unref (connection->priv->auth);
385 //g_debug ("finalizing %p", connection);
386 if (connection->priv->stream != NULL)
388 /* We don't really care if closing the stream succeeds or not */
389 g_io_stream_close_async (connection->priv->stream,
391 NULL, /* GCancellable */
392 NULL, /* GAsyncReadyCallback */
393 NULL); /* userdata */
394 g_object_unref (connection->priv->stream);
395 connection->priv->stream = NULL;
398 g_free (connection->priv->address);
400 g_free (connection->priv->guid);
401 g_free (connection->priv->bus_unique_name);
403 if (connection->priv->initialization_error != NULL)
404 g_error_free (connection->priv->initialization_error);
406 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
408 purge_all_signal_subscriptions (connection);
409 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
410 g_hash_table_unref (connection->priv->map_id_to_signal_data);
411 g_hash_table_unref (connection->priv->map_sender_unique_name_to_signal_data_array);
413 g_hash_table_unref (connection->priv->map_id_to_ei);
414 g_hash_table_unref (connection->priv->map_object_path_to_eo);
415 g_hash_table_unref (connection->priv->map_id_to_es);
416 g_hash_table_unref (connection->priv->map_object_path_to_es);
418 purge_all_filters (connection);
419 g_ptr_array_unref (connection->priv->filters);
421 if (connection->priv->main_context_at_construction != NULL)
422 g_main_context_unref (connection->priv->main_context_at_construction);
424 g_free (connection->priv->machine_id);
426 g_mutex_free (connection->priv->init_lock);
427 g_mutex_free (connection->priv->lock);
429 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
433 g_dbus_connection_get_property (GObject *object,
438 GDBusConnection *connection = G_DBUS_CONNECTION (object);
443 g_value_set_object (value, g_dbus_connection_get_stream (connection));
447 g_value_set_string (value, g_dbus_connection_get_guid (connection));
450 case PROP_UNIQUE_NAME:
451 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
455 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
458 case PROP_EXIT_ON_CLOSE:
459 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
462 case PROP_CAPABILITY_FLAGS:
463 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
467 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
473 g_dbus_connection_set_property (GObject *object,
478 GDBusConnection *connection = G_DBUS_CONNECTION (object);
483 connection->priv->stream = g_value_dup_object (value);
487 connection->priv->guid = g_value_dup_string (value);
491 connection->priv->address = g_value_dup_string (value);
495 connection->priv->flags = g_value_get_flags (value);
498 case PROP_EXIT_ON_CLOSE:
499 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
502 case PROP_AUTHENTICATION_OBSERVER:
503 connection->priv->authentication_observer = g_value_dup_object (value);
507 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
513 g_dbus_connection_real_closed (GDBusConnection *connection,
514 gboolean remote_peer_vanished,
517 if (remote_peer_vanished && connection->priv->exit_on_close)
519 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
525 g_dbus_connection_class_init (GDBusConnectionClass *klass)
527 GObjectClass *gobject_class;
529 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
531 gobject_class = G_OBJECT_CLASS (klass);
533 gobject_class->finalize = g_dbus_connection_finalize;
534 gobject_class->dispose = g_dbus_connection_dispose;
535 gobject_class->set_property = g_dbus_connection_set_property;
536 gobject_class->get_property = g_dbus_connection_get_property;
538 klass->closed = g_dbus_connection_real_closed;
541 * GDBusConnection:stream:
543 * The underlying #GIOStream used for I/O.
547 g_object_class_install_property (gobject_class,
549 g_param_spec_object ("stream",
551 P_("The underlying streams used for I/O"),
555 G_PARAM_CONSTRUCT_ONLY |
556 G_PARAM_STATIC_NAME |
557 G_PARAM_STATIC_BLURB |
558 G_PARAM_STATIC_NICK));
561 * GDBusConnection:address:
563 * A D-Bus address specifying potential endpoints that can be used
564 * when establishing the connection.
568 g_object_class_install_property (gobject_class,
570 g_param_spec_string ("address",
572 P_("D-Bus address specifying potential socket endpoints"),
575 G_PARAM_CONSTRUCT_ONLY |
576 G_PARAM_STATIC_NAME |
577 G_PARAM_STATIC_BLURB |
578 G_PARAM_STATIC_NICK));
581 * GDBusConnection:flags:
583 * Flags from the #GDBusConnectionFlags enumeration.
587 g_object_class_install_property (gobject_class,
589 g_param_spec_flags ("flags",
592 G_TYPE_DBUS_CONNECTION_FLAGS,
593 G_DBUS_CONNECTION_FLAGS_NONE,
595 G_PARAM_CONSTRUCT_ONLY |
596 G_PARAM_STATIC_NAME |
597 G_PARAM_STATIC_BLURB |
598 G_PARAM_STATIC_NICK));
601 * GDBusConnection:guid:
603 * The GUID of the peer performing the role of server when
606 * If you are constructing a #GDBusConnection and pass
607 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
608 * #GDBusConnection:flags property then you MUST also set this
609 * property to a valid guid.
611 * If you are constructing a #GDBusConnection and pass
612 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
613 * #GDBusConnection:flags property you will be able to read the GUID
614 * of the other peer here after the connection has been successfully
619 g_object_class_install_property (gobject_class,
621 g_param_spec_string ("guid",
623 P_("GUID of the server peer"),
627 G_PARAM_CONSTRUCT_ONLY |
628 G_PARAM_STATIC_NAME |
629 G_PARAM_STATIC_BLURB |
630 G_PARAM_STATIC_NICK));
633 * GDBusConnection:unique-name:
635 * The unique name as assigned by the message bus or %NULL if the
636 * connection is not open or not a message bus connection.
640 g_object_class_install_property (gobject_class,
642 g_param_spec_string ("unique-name",
644 P_("Unique name of bus connection"),
647 G_PARAM_STATIC_NAME |
648 G_PARAM_STATIC_BLURB |
649 G_PARAM_STATIC_NICK));
652 * GDBusConnection:closed:
654 * A boolean specifying whether the connection has been closed.
658 g_object_class_install_property (gobject_class,
660 g_param_spec_boolean ("closed",
662 P_("Whether the connection is closed"),
665 G_PARAM_STATIC_NAME |
666 G_PARAM_STATIC_BLURB |
667 G_PARAM_STATIC_NICK));
670 * GDBusConnection:exit-on-close:
672 * A boolean specifying whether the process will be terminated (by
673 * calling <literal>raise(SIGTERM)</literal>) if the connection
674 * is closed by the remote peer.
678 g_object_class_install_property (gobject_class,
680 g_param_spec_boolean ("exit-on-close",
682 P_("Whether the process is terminated when the connection is closed"),
686 G_PARAM_STATIC_NAME |
687 G_PARAM_STATIC_BLURB |
688 G_PARAM_STATIC_NICK));
691 * GDBusConnection:capabilities:
693 * Flags from the #GDBusCapabilityFlags enumeration
694 * representing connection features negotiated with the other peer.
698 g_object_class_install_property (gobject_class,
699 PROP_CAPABILITY_FLAGS,
700 g_param_spec_flags ("capabilities",
703 G_TYPE_DBUS_CAPABILITY_FLAGS,
704 G_DBUS_CAPABILITY_FLAGS_NONE,
706 G_PARAM_STATIC_NAME |
707 G_PARAM_STATIC_BLURB |
708 G_PARAM_STATIC_NICK));
711 * GDBusConnection:authentication-observer:
713 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
717 g_object_class_install_property (gobject_class,
718 PROP_AUTHENTICATION_OBSERVER,
719 g_param_spec_object ("authentication-observer",
720 P_("Authentication Observer"),
721 P_("Object used to assist in the authentication process"),
722 G_TYPE_DBUS_AUTH_OBSERVER,
724 G_PARAM_CONSTRUCT_ONLY |
725 G_PARAM_STATIC_NAME |
726 G_PARAM_STATIC_BLURB |
727 G_PARAM_STATIC_NICK));
730 * GDBusConnection::closed:
731 * @connection: The #GDBusConnection emitting the signal.
732 * @remote_peer_vanished: %TRUE if @connection is closed because the
733 * remote peer closed its end of the connection.
734 * @error: A #GError with more details about the event or %NULL.
736 * Emitted when the connection is closed.
738 * The cause of this event can be
741 * If g_dbus_connection_close() is called. In this case
742 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
745 * If the remote peer closes the connection. In this case
746 * @remote_peer_vanished is set to %TRUE and @error is set.
749 * If the remote peer sends invalid or malformed data. In this
750 * case @remote_peer_vanished is set to %FALSE and @error
755 * Upon receiving this signal, you should give up your reference to
756 * @connection. You are guaranteed that this signal is emitted only
761 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
762 G_TYPE_DBUS_CONNECTION,
764 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
767 _gio_marshal_VOID__BOOLEAN_BOXED,
775 g_dbus_connection_init (GDBusConnection *connection)
777 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
779 connection->priv->lock = g_mutex_new ();
780 connection->priv->init_lock = g_mutex_new ();
782 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
784 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
786 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
788 connection->priv->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
793 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
796 (GDestroyNotify) exported_object_free);
798 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
801 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
804 (GDestroyNotify) exported_subtree_free);
806 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
809 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
810 if (connection->priv->main_context_at_construction != NULL)
811 g_main_context_ref (connection->priv->main_context_at_construction);
813 connection->priv->filters = g_ptr_array_new ();
817 * g_dbus_connection_get_stream:
818 * @connection: a #GDBusConnection
820 * Gets the underlying stream used for IO.
822 * Returns: the stream used for IO
827 g_dbus_connection_get_stream (GDBusConnection *connection)
829 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
830 return connection->priv->stream;
834 * g_dbus_connection_start_message_processing:
835 * @connection: A #GDBusConnection.
837 * If @connection was created with
838 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
839 * starts processing messages. Does nothing on if @connection wasn't
840 * created with this flag or if the method has already been called.
845 g_dbus_connection_start_message_processing (GDBusConnection *connection)
847 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
848 _g_dbus_worker_unfreeze (connection->priv->worker);
852 * g_dbus_connection_is_closed:
853 * @connection: A #GDBusConnection.
855 * Gets whether @connection is closed.
857 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
862 g_dbus_connection_is_closed (GDBusConnection *connection)
864 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
865 return connection->priv->closed;
869 * g_dbus_connection_get_capabilities:
870 * @connection: A #GDBusConnection.
872 * Gets the capabilities negotiated with the remote peer
874 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
879 g_dbus_connection_get_capabilities (GDBusConnection *connection)
881 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
882 return connection->priv->capabilities;
886 /* ---------------------------------------------------------------------------------------------------- */
890 GDBusConnection *connection;
892 gboolean remote_peer_vanished;
896 emit_closed_data_free (EmitClosedData *data)
898 g_object_unref (data->connection);
899 if (data->error != NULL)
900 g_error_free (data->error);
905 emit_closed_in_idle (gpointer user_data)
907 EmitClosedData *data = user_data;
910 g_object_notify (G_OBJECT (data->connection), "closed");
911 g_signal_emit (data->connection,
912 signals[CLOSED_SIGNAL],
914 data->remote_peer_vanished,
920 /* Can be called from any thread, must hold lock */
922 set_closed_unlocked (GDBusConnection *connection,
923 gboolean remote_peer_vanished,
926 GSource *idle_source;
927 EmitClosedData *data;
929 CONNECTION_ENSURE_LOCK (connection);
931 g_assert (!connection->priv->closed);
933 connection->priv->closed = TRUE;
935 data = g_new0 (EmitClosedData, 1);
936 data->connection = g_object_ref (connection);
937 data->remote_peer_vanished = remote_peer_vanished;
938 data->error = error != NULL ? g_error_copy (error) : NULL;
940 idle_source = g_idle_source_new ();
941 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
942 g_source_set_callback (idle_source,
945 (GDestroyNotify) emit_closed_data_free);
946 g_source_attach (idle_source, connection->priv->main_context_at_construction);
947 g_source_unref (idle_source);
950 /* ---------------------------------------------------------------------------------------------------- */
953 * g_dbus_connection_close:
954 * @connection: A #GDBusConnection.
956 * Closes @connection. Note that this never causes the process to
957 * exit (this might only happen if the other end of a shared message
958 * bus connection disconnects).
960 * If @connection is already closed, this method does nothing.
965 g_dbus_connection_close (GDBusConnection *connection)
967 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
969 CONNECTION_LOCK (connection);
970 if (!connection->priv->closed)
972 GError *error = NULL;
974 /* TODO: do this async */
975 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
976 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
978 g_warning ("Error closing stream: %s", error->message);
979 g_error_free (error);
982 set_closed_unlocked (connection, FALSE, NULL);
984 CONNECTION_UNLOCK (connection);
987 /* ---------------------------------------------------------------------------------------------------- */
990 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
991 GDBusMessage *message,
992 volatile guint32 *out_serial,
997 guint32 serial_to_use;
1000 CONNECTION_ENSURE_LOCK (connection);
1002 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1003 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1005 /* TODO: check all necessary headers are present */
1010 if (out_serial != NULL)
1013 if (connection->priv->closed)
1015 g_set_error_literal (error,
1018 _("The connection is closed"));
1022 blob = g_dbus_message_to_blob (message,
1024 connection->priv->capabilities,
1029 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
1034 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1037 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1040 g_assert_not_reached ();
1045 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1046 blob_size, serial_to_use, connection);
1047 g_printerr ("----\n");
1048 hexdump (blob, blob_size);
1049 g_printerr ("----\n");
1052 /* TODO: use connection->priv->auth to encode the blob */
1054 if (out_serial != NULL)
1055 *out_serial = serial_to_use;
1057 g_dbus_message_set_serial (message, serial_to_use);
1059 _g_dbus_worker_send_message (connection->priv->worker,
1063 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1074 * g_dbus_connection_send_message:
1075 * @connection: A #GDBusConnection.
1076 * @message: A #GDBusMessage
1077 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1078 * @error: Return location for error or %NULL.
1080 * Asynchronously sends @message to the peer represented by @connection.
1082 * If @out_serial is not %NULL, then the serial number assigned to
1083 * @message by @connection will be written to this location prior to
1084 * submitting the message to the underlying transport.
1086 * If @connection is closed then the operation will fail with
1087 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1088 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1089 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1091 * See <xref linkend="gdbus-server"/> and <xref
1092 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1093 * low-level API to send and receive UNIX file descriptors.
1095 * Returns: %TRUE if the message was well-formed and queued for
1096 * transmission, %FALSE if @error is set.
1101 g_dbus_connection_send_message (GDBusConnection *connection,
1102 GDBusMessage *message,
1103 volatile guint32 *out_serial,
1108 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1109 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1110 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1112 CONNECTION_LOCK (connection);
1113 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1114 CONNECTION_UNLOCK (connection);
1118 /* ---------------------------------------------------------------------------------------------------- */
1122 volatile gint ref_count;
1123 GDBusConnection *connection;
1125 GSimpleAsyncResult *simple;
1127 GMainContext *main_context;
1129 GCancellable *cancellable;
1131 gulong cancellable_handler_id;
1133 GSource *timeout_source;
1138 static SendMessageData *
1139 send_message_data_ref (SendMessageData *data)
1141 g_atomic_int_inc (&data->ref_count);
1146 send_message_data_unref (SendMessageData *data)
1148 if (g_atomic_int_dec_and_test (&data->ref_count))
1150 g_assert (data->timeout_source == NULL);
1151 g_assert (data->simple == NULL);
1152 g_assert (data->cancellable_handler_id == 0);
1153 g_object_unref (data->connection);
1154 if (data->cancellable != NULL)
1155 g_object_unref (data->cancellable);
1156 if (data->main_context != NULL)
1157 g_main_context_unref (data->main_context);
1162 /* ---------------------------------------------------------------------------------------------------- */
1164 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1166 send_message_with_reply_deliver (SendMessageData *data)
1168 CONNECTION_ENSURE_LOCK (data->connection);
1170 g_assert (!data->delivered);
1172 data->delivered = TRUE;
1174 g_simple_async_result_complete_in_idle (data->simple);
1175 g_object_unref (data->simple);
1176 data->simple = NULL;
1178 if (data->timeout_source != NULL)
1180 g_source_destroy (data->timeout_source);
1181 data->timeout_source = NULL;
1183 if (data->cancellable_handler_id > 0)
1185 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1186 data->cancellable_handler_id = 0;
1189 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1190 GUINT_TO_POINTER (data->serial)));
1192 send_message_data_unref (data);
1195 /* ---------------------------------------------------------------------------------------------------- */
1197 /* must hold lock */
1199 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1200 GDBusMessage *reply)
1202 if (data->delivered)
1205 g_simple_async_result_set_op_res_gpointer (data->simple,
1206 g_object_ref (reply),
1209 send_message_with_reply_deliver (data);
1215 /* ---------------------------------------------------------------------------------------------------- */
1218 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1220 SendMessageData *data = user_data;
1222 CONNECTION_LOCK (data->connection);
1223 if (data->delivered)
1226 g_simple_async_result_set_error (data->simple,
1228 G_IO_ERROR_CANCELLED,
1229 _("Operation was cancelled"));
1231 send_message_with_reply_deliver (data);
1234 CONNECTION_UNLOCK (data->connection);
1238 /* Can be called from any thread with or without lock held */
1240 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1243 SendMessageData *data = user_data;
1244 GSource *idle_source;
1246 /* postpone cancellation to idle handler since we may be called directly
1247 * via g_cancellable_connect() (e.g. holding lock)
1249 idle_source = g_idle_source_new ();
1250 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1251 g_source_set_callback (idle_source,
1252 send_message_with_reply_cancelled_idle_cb,
1253 send_message_data_ref (data),
1254 (GDestroyNotify) send_message_data_unref);
1255 g_source_attach (idle_source, data->main_context);
1256 g_source_unref (idle_source);
1259 /* ---------------------------------------------------------------------------------------------------- */
1262 send_message_with_reply_timeout_cb (gpointer user_data)
1264 SendMessageData *data = user_data;
1266 CONNECTION_LOCK (data->connection);
1267 if (data->delivered)
1270 g_simple_async_result_set_error (data->simple,
1272 G_IO_ERROR_TIMED_OUT,
1273 _("Timeout was reached"));
1275 send_message_with_reply_deliver (data);
1278 CONNECTION_UNLOCK (data->connection);
1283 /* ---------------------------------------------------------------------------------------------------- */
1286 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1287 GDBusMessage *message,
1289 volatile guint32 *out_serial,
1290 GCancellable *cancellable,
1291 GAsyncReadyCallback callback,
1294 GSimpleAsyncResult *simple;
1295 SendMessageData *data;
1297 volatile guint32 serial;
1301 if (out_serial == NULL)
1302 out_serial = &serial;
1304 if (timeout_msec == -1)
1305 timeout_msec = 25 * 1000;
1307 simple = g_simple_async_result_new (G_OBJECT (connection),
1310 g_dbus_connection_send_message_with_reply);
1312 if (g_cancellable_is_cancelled (cancellable))
1314 g_simple_async_result_set_error (simple,
1316 G_IO_ERROR_CANCELLED,
1317 _("Operation was cancelled"));
1318 g_simple_async_result_complete_in_idle (simple);
1319 g_object_unref (simple);
1323 if (connection->priv->closed)
1325 g_simple_async_result_set_error (simple,
1328 _("The connection is closed"));
1329 g_simple_async_result_complete_in_idle (simple);
1330 g_object_unref (simple);
1335 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1337 g_simple_async_result_set_from_error (simple, error);
1338 g_simple_async_result_complete_in_idle (simple);
1339 g_object_unref (simple);
1343 data = g_new0 (SendMessageData, 1);
1344 data->ref_count = 1;
1345 data->connection = g_object_ref (connection);
1346 data->simple = simple;
1347 data->serial = *out_serial;
1348 data->main_context = g_main_context_get_thread_default ();
1349 if (data->main_context != NULL)
1350 g_main_context_ref (data->main_context);
1352 if (cancellable != NULL)
1354 data->cancellable = g_object_ref (cancellable);
1355 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1356 G_CALLBACK (send_message_with_reply_cancelled_cb),
1357 send_message_data_ref (data),
1358 (GDestroyNotify) send_message_data_unref);
1359 g_object_set_data_full (G_OBJECT (simple),
1361 g_object_ref (cancellable),
1362 (GDestroyNotify) g_object_unref);
1365 data->timeout_source = g_timeout_source_new (timeout_msec);
1366 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1367 g_source_set_callback (data->timeout_source,
1368 send_message_with_reply_timeout_cb,
1369 send_message_data_ref (data),
1370 (GDestroyNotify) send_message_data_unref);
1371 g_source_attach (data->timeout_source, data->main_context);
1372 g_source_unref (data->timeout_source);
1374 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1375 GUINT_TO_POINTER (*out_serial),
1383 * g_dbus_connection_send_message_with_reply:
1384 * @connection: A #GDBusConnection.
1385 * @message: A #GDBusMessage.
1386 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1387 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1388 * @cancellable: A #GCancellable or %NULL.
1389 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1390 * care about the result.
1391 * @user_data: The data to pass to @callback.
1393 * Asynchronously sends @message to the peer represented by @connection.
1395 * If @out_serial is not %NULL, then the serial number assigned to
1396 * @message by @connection will be written to this location prior to
1397 * submitting the message to the underlying transport.
1399 * If @connection is closed then the operation will fail with
1400 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1401 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1402 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1404 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1405 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1406 * of the thread you are calling this method from. You can then call
1407 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1408 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1410 * See <xref linkend="gdbus-server"/> and <xref
1411 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1412 * low-level API to send and receive UNIX file descriptors.
1417 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1418 GDBusMessage *message,
1420 volatile guint32 *out_serial,
1421 GCancellable *cancellable,
1422 GAsyncReadyCallback callback,
1425 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1426 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1427 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1429 CONNECTION_LOCK (connection);
1430 g_dbus_connection_send_message_with_reply_unlocked (connection,
1437 CONNECTION_UNLOCK (connection);
1441 * g_dbus_connection_send_message_with_reply_finish:
1442 * @connection: a #GDBusConnection
1443 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1444 * @error: Return location for error or %NULL.
1446 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1448 * Note that @error is only set if a local in-process error
1449 * occured. That is to say that the returned #GDBusMessage object may
1450 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1451 * g_dbus_message_to_gerror() to transcode this to a #GError.
1453 * See <xref linkend="gdbus-server"/> and <xref
1454 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1455 * low-level API to send and receive UNIX file descriptors.
1457 * Returns: A #GDBusMessage or %NULL if @error is set.
1462 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1466 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1467 GDBusMessage *reply;
1468 GCancellable *cancellable;
1470 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1471 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1475 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1477 if (g_simple_async_result_propagate_error (simple, error))
1480 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1481 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1482 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1484 g_object_unref (reply);
1486 g_set_error_literal (error,
1488 G_IO_ERROR_CANCELLED,
1489 _("Operation was cancelled"));
1495 /* ---------------------------------------------------------------------------------------------------- */
1500 GMainContext *context;
1502 } SendMessageSyncData;
1505 send_message_with_reply_sync_cb (GDBusConnection *connection,
1509 SendMessageSyncData *data = user_data;
1510 data->res = g_object_ref (res);
1511 g_main_loop_quit (data->loop);
1515 * g_dbus_connection_send_message_with_reply_sync:
1516 * @connection: A #GDBusConnection.
1517 * @message: A #GDBusMessage.
1518 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1519 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1520 * @cancellable: A #GCancellable or %NULL.
1521 * @error: Return location for error or %NULL.
1523 * Synchronously sends @message to the peer represented by @connection
1524 * and blocks the calling thread until a reply is received or the
1525 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1526 * for the asynchronous version of this method.
1528 * If @out_serial is not %NULL, then the serial number assigned to
1529 * @message by @connection will be written to this location prior to
1530 * submitting the message to the underlying transport.
1532 * If @connection is closed then the operation will fail with
1533 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1534 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1535 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1537 * Note that @error is only set if a local in-process error
1538 * occured. That is to say that the returned #GDBusMessage object may
1539 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1540 * g_dbus_message_to_gerror() to transcode this to a #GError.
1542 * See <xref linkend="gdbus-server"/> and <xref
1543 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1544 * low-level API to send and receive UNIX file descriptors.
1546 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1551 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1552 GDBusMessage *message,
1554 volatile guint32 *out_serial,
1555 GCancellable *cancellable,
1558 SendMessageSyncData *data;
1559 GDBusMessage *reply;
1561 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1562 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1563 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1564 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1566 data = g_new0 (SendMessageSyncData, 1);
1567 data->context = g_main_context_new ();
1568 data->loop = g_main_loop_new (data->context, FALSE);
1570 g_main_context_push_thread_default (data->context);
1572 g_dbus_connection_send_message_with_reply (connection,
1577 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1579 g_main_loop_run (data->loop);
1580 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1584 g_main_context_pop_thread_default (data->context);
1586 g_main_context_unref (data->context);
1587 g_main_loop_unref (data->loop);
1588 g_object_unref (data->res);
1594 /* ---------------------------------------------------------------------------------------------------- */
1598 GDBusMessageFilterFunction func;
1605 GDBusMessageFilterFunction filter_function;
1607 GDestroyNotify user_data_free_func;
1610 /* Called in worker's thread - we must not block */
1612 on_worker_message_received (GDBusWorker *worker,
1613 GDBusMessage *message,
1616 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1617 FilterCallback *filters;
1618 gboolean consumed_by_filter;
1622 //g_debug ("in on_worker_message_received");
1624 g_object_ref (connection);
1626 /* First collect the set of callback functions */
1627 CONNECTION_LOCK (connection);
1628 num_filters = connection->priv->filters->len;
1629 filters = g_new0 (FilterCallback, num_filters);
1630 for (n = 0; n < num_filters; n++)
1632 FilterData *data = connection->priv->filters->pdata[n];
1633 filters[n].func = data->filter_function;
1634 filters[n].user_data = data->user_data;
1636 CONNECTION_UNLOCK (connection);
1638 /* the call the filters in order (without holding the lock) */
1639 consumed_by_filter = FALSE;
1640 for (n = 0; n < num_filters; n++)
1642 consumed_by_filter = filters[n].func (connection,
1645 filters[n].user_data);
1646 if (consumed_by_filter)
1650 /* Standard dispatch unless the filter ate the message */
1651 if (!consumed_by_filter)
1653 GDBusMessageType message_type;
1655 message_type = g_dbus_message_get_message_type (message);
1656 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1658 guint32 reply_serial;
1659 SendMessageData *send_message_data;
1661 reply_serial = g_dbus_message_get_reply_serial (message);
1662 CONNECTION_LOCK (connection);
1663 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1664 GUINT_TO_POINTER (reply_serial));
1665 if (send_message_data != NULL)
1667 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1668 send_message_data_deliver_reply_unlocked (send_message_data, message);
1672 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1674 CONNECTION_UNLOCK (connection);
1676 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1678 CONNECTION_LOCK (connection);
1679 distribute_signals (connection, message);
1680 CONNECTION_UNLOCK (connection);
1682 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1684 CONNECTION_LOCK (connection);
1685 distribute_method_call (connection, message);
1686 CONNECTION_UNLOCK (connection);
1690 g_object_unref (connection);
1694 /* Called in worker's thread */
1696 on_worker_message_about_to_be_sent (GDBusWorker *worker,
1697 GDBusMessage *message,
1700 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1701 FilterCallback *filters;
1702 gboolean consumed_by_filter;
1706 //g_debug ("in on_worker_message_about_to_be_sent");
1708 g_object_ref (connection);
1710 /* First collect the set of callback functions */
1711 CONNECTION_LOCK (connection);
1712 num_filters = connection->priv->filters->len;
1713 filters = g_new0 (FilterCallback, num_filters);
1714 for (n = 0; n < num_filters; n++)
1716 FilterData *data = connection->priv->filters->pdata[n];
1717 filters[n].func = data->filter_function;
1718 filters[n].user_data = data->user_data;
1720 CONNECTION_UNLOCK (connection);
1722 /* the call the filters in order (without holding the lock) */
1723 consumed_by_filter = FALSE;
1724 for (n = 0; n < num_filters; n++)
1726 consumed_by_filter = filters[n].func (connection,
1729 filters[n].user_data);
1730 if (consumed_by_filter)
1734 g_object_unref (connection);
1737 return consumed_by_filter;
1740 /* Called in worker's thread - we must not block */
1742 on_worker_closed (GDBusWorker *worker,
1743 gboolean remote_peer_vanished,
1747 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1749 //g_debug ("in on_worker_closed: %s", error->message);
1751 CONNECTION_LOCK (connection);
1752 if (!connection->priv->closed)
1753 set_closed_unlocked (connection, remote_peer_vanished, error);
1754 CONNECTION_UNLOCK (connection);
1757 /* ---------------------------------------------------------------------------------------------------- */
1759 /* Determines the biggest set of capabilities we can support on this connection */
1760 static GDBusCapabilityFlags
1761 get_offered_capabilities_max (GDBusConnection *connection)
1763 GDBusCapabilityFlags ret;
1764 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1766 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1767 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1773 initable_init (GInitable *initable,
1774 GCancellable *cancellable,
1777 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1780 /* This method needs to be idempotent to work with the singleton
1781 * pattern. See the docs for g_initable_init(). We implement this by
1784 * Unfortunately we can't use the main lock since the on_worker_*()
1785 * callbacks above needs the lock during initialization (for message
1786 * bus connections we do a synchronous Hello() call on the bus).
1788 g_mutex_lock (connection->priv->init_lock);
1792 if (connection->priv->is_initialized)
1794 if (connection->priv->stream != NULL)
1797 g_assert (connection->priv->initialization_error != NULL);
1800 g_assert (connection->priv->initialization_error == NULL);
1802 /* The user can pass multiple (but mutally exclusive) construct
1805 * - stream (of type GIOStream)
1806 * - address (of type gchar*)
1808 * At the end of the day we end up with a non-NULL GIOStream
1809 * object in connection->priv->stream.
1811 if (connection->priv->address != NULL)
1813 g_assert (connection->priv->stream == NULL);
1815 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1816 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1818 g_set_error_literal (error,
1820 G_IO_ERROR_INVALID_ARGUMENT,
1821 _("Unsupported flags encountered when constructing a client-side connection"));
1825 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1826 NULL, /* TODO: out_guid */
1828 &connection->priv->initialization_error);
1829 if (connection->priv->stream == NULL)
1832 else if (connection->priv->stream != NULL)
1838 g_assert_not_reached ();
1841 /* Authenticate the connection */
1842 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1844 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1845 g_assert (connection->priv->guid != NULL);
1846 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1847 if (!_g_dbus_auth_run_server (connection->priv->auth,
1848 connection->priv->authentication_observer,
1849 connection->priv->guid,
1850 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1851 get_offered_capabilities_max (connection),
1852 &connection->priv->capabilities,
1853 &connection->priv->crendentials,
1855 &connection->priv->initialization_error))
1858 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1860 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1861 g_assert (connection->priv->guid == NULL);
1862 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1863 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1864 get_offered_capabilities_max (connection),
1865 &connection->priv->capabilities,
1867 &connection->priv->initialization_error);
1868 if (connection->priv->guid == NULL)
1872 if (connection->priv->authentication_observer != NULL)
1874 g_object_unref (connection->priv->authentication_observer);
1875 connection->priv->authentication_observer = NULL;
1878 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1880 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1885 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1889 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1891 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1895 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1896 connection->priv->capabilities,
1897 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
1898 on_worker_message_received,
1899 on_worker_message_about_to_be_sent,
1903 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
1904 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1906 GVariant *hello_result;
1908 /* we could lift this restriction by adding code in gdbusprivate.c */
1909 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
1911 g_set_error_literal (&connection->priv->initialization_error,
1914 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
1918 hello_result = g_dbus_connection_call_sync (connection,
1919 "org.freedesktop.DBus", /* name */
1920 "/org/freedesktop/DBus", /* path */
1921 "org.freedesktop.DBus", /* interface */
1923 NULL, /* parameters */
1924 G_VARIANT_TYPE ("(s)"),
1925 G_DBUS_CALL_FLAGS_NONE,
1927 NULL, /* TODO: cancellable */
1928 &connection->priv->initialization_error);
1929 if (hello_result == NULL)
1932 g_variant_get (hello_result, "(s)", &connection->priv->bus_unique_name);
1933 g_variant_unref (hello_result);
1934 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1937 connection->priv->is_initialized = TRUE;
1943 g_assert (connection->priv->initialization_error != NULL);
1944 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1947 g_mutex_unlock (connection->priv->init_lock);
1953 initable_iface_init (GInitableIface *initable_iface)
1955 initable_iface->init = initable_init;
1958 /* ---------------------------------------------------------------------------------------------------- */
1961 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1966 /* ---------------------------------------------------------------------------------------------------- */
1969 * g_dbus_connection_new:
1970 * @stream: A #GIOStream.
1971 * @guid: The GUID to use if a authenticating as a server or %NULL.
1972 * @flags: Flags describing how to make the connection.
1973 * @observer: A #GDBusAuthObserver or %NULL.
1974 * @cancellable: A #GCancellable or %NULL.
1975 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1976 * @user_data: The data to pass to @callback.
1978 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1979 * with the end represented by @stream.
1981 * If @observer is not %NULL it may be used to control the
1982 * authentication process.
1984 * When the operation is finished, @callback will be invoked. You can
1985 * then call g_dbus_connection_new_finish() to get the result of the
1988 * This is a asynchronous failable constructor. See
1989 * g_dbus_connection_new_sync() for the synchronous
1995 g_dbus_connection_new (GIOStream *stream,
1997 GDBusConnectionFlags flags,
1998 GDBusAuthObserver *observer,
1999 GCancellable *cancellable,
2000 GAsyncReadyCallback callback,
2003 g_return_if_fail (G_IS_IO_STREAM (stream));
2004 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2012 "authentication-observer", observer,
2017 * g_dbus_connection_new_finish:
2018 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2019 * @error: Return location for error or %NULL.
2021 * Finishes an operation started with g_dbus_connection_new().
2023 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2028 g_dbus_connection_new_finish (GAsyncResult *res,
2032 GObject *source_object;
2034 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2035 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2037 source_object = g_async_result_get_source_object (res);
2038 g_assert (source_object != NULL);
2039 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2042 g_object_unref (source_object);
2044 return G_DBUS_CONNECTION (object);
2050 * g_dbus_connection_new_sync:
2051 * @stream: A #GIOStream.
2052 * @guid: The GUID to use if a authenticating as a server or %NULL.
2053 * @flags: Flags describing how to make the connection.
2054 * @observer: A #GDBusAuthObserver or %NULL.
2055 * @cancellable: A #GCancellable or %NULL.
2056 * @error: Return location for error or %NULL.
2058 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2059 * with the end represented by @stream.
2061 * If @observer is not %NULL it may be used to control the
2062 * authentication process.
2064 * This is a synchronous failable constructor. See
2065 * g_dbus_connection_new() for the asynchronous version.
2067 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2072 g_dbus_connection_new_sync (GIOStream *stream,
2074 GDBusConnectionFlags flags,
2075 GDBusAuthObserver *observer,
2076 GCancellable *cancellable,
2079 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2080 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2081 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2087 "authentication-observer", observer,
2091 /* ---------------------------------------------------------------------------------------------------- */
2094 * g_dbus_connection_new_for_address:
2095 * @address: A D-Bus address.
2096 * @flags: Flags describing how to make the connection.
2097 * @observer: A #GDBusAuthObserver or %NULL.
2098 * @cancellable: A #GCancellable or %NULL.
2099 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2100 * @user_data: The data to pass to @callback.
2102 * Asynchronously connects and sets up a D-Bus client connection for
2103 * exchanging D-Bus messages with an endpoint specified by @address
2104 * which must be in the D-Bus address format.
2106 * This constructor can only be used to initiate client-side
2107 * connections - use g_dbus_connection_new() if you need to act as the
2108 * server. In particular, @flags cannot contain the
2109 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2110 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2112 * When the operation is finished, @callback will be invoked. You can
2113 * then call g_dbus_connection_new_finish() to get the result of the
2116 * If @observer is not %NULL it may be used to control the
2117 * authentication process.
2119 * This is a asynchronous failable constructor. See
2120 * g_dbus_connection_new_for_address_sync() for the synchronous
2126 g_dbus_connection_new_for_address (const gchar *address,
2127 GDBusConnectionFlags flags,
2128 GDBusAuthObserver *observer,
2129 GCancellable *cancellable,
2130 GAsyncReadyCallback callback,
2133 g_return_if_fail (address != NULL);
2134 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2141 "authentication-observer", observer,
2146 * g_dbus_connection_new_for_address_finish:
2147 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2148 * @error: Return location for error or %NULL.
2150 * Finishes an operation started with g_dbus_connection_new_for_address().
2152 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2157 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2161 GObject *source_object;
2163 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2164 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2166 source_object = g_async_result_get_source_object (res);
2167 g_assert (source_object != NULL);
2168 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2171 g_object_unref (source_object);
2173 return G_DBUS_CONNECTION (object);
2179 * g_dbus_connection_new_for_address_sync:
2180 * @address: A D-Bus address.
2181 * @flags: Flags describing how to make the connection.
2182 * @observer: A #GDBusAuthObserver or %NULL.
2183 * @cancellable: A #GCancellable or %NULL.
2184 * @error: Return location for error or %NULL.
2186 * Synchronously connects and sets up a D-Bus client connection for
2187 * exchanging D-Bus messages with an endpoint specified by @address
2188 * which must be in the D-Bus address format.
2190 * This constructor can only be used to initiate client-side
2191 * connections - use g_dbus_connection_new_sync() if you need to act
2192 * as the server. In particular, @flags cannot contain the
2193 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2194 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2196 * This is a synchronous failable constructor. See
2197 * g_dbus_connection_new_for_address() for the asynchronous version.
2199 * If @observer is not %NULL it may be used to control the
2200 * authentication process.
2202 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2207 g_dbus_connection_new_for_address_sync (const gchar *address,
2208 GDBusConnectionFlags flags,
2209 GDBusAuthObserver *observer,
2210 GCancellable *cancellable,
2213 g_return_val_if_fail (address != NULL, NULL);
2214 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2215 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2220 "authentication-observer", observer,
2224 /* ---------------------------------------------------------------------------------------------------- */
2227 * g_dbus_connection_set_exit_on_close:
2228 * @connection: A #GDBusConnection.
2229 * @exit_on_close: Whether the process should be terminated
2230 * when @connection is closed by the remote peer.
2232 * Sets whether the process should be terminated when @connection is
2233 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2239 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2240 gboolean exit_on_close)
2242 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2243 connection->priv->exit_on_close = exit_on_close;
2247 * g_dbus_connection_get_exit_on_close:
2248 * @connection: A #GDBusConnection.
2250 * Gets whether the process is terminated when @connection is
2251 * closed by the remote peer. See
2252 * #GDBusConnection:exit-on-close for more details.
2254 * Returns: Whether the process is terminated when @connection is
2255 * closed by the remote peer.
2260 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2262 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2263 return connection->priv->exit_on_close;
2267 * g_dbus_connection_get_guid:
2268 * @connection: A #GDBusConnection.
2270 * The GUID of the peer performing the role of server when
2271 * authenticating. See #GDBusConnection:guid for more details.
2273 * Returns: The GUID. Do not free this string, it is owned by
2279 g_dbus_connection_get_guid (GDBusConnection *connection)
2281 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2282 return connection->priv->guid;
2286 * g_dbus_connection_get_unique_name:
2287 * @connection: A #GDBusConnection.
2289 * Gets the unique name of @connection as assigned by the message
2290 * bus. This can also be used to figure out if @connection is a
2291 * message bus connection.
2293 * Returns: The unique name or %NULL if @connection is not a message
2294 * bus connection. Do not free this string, it is owned by
2300 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2302 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2303 return connection->priv->bus_unique_name;
2307 * g_dbus_connection_get_peer_credentials:
2308 * @connection: A #GDBusConnection.
2310 * Gets the credentials of the authenticated peer. This will always
2311 * return %NULL unless @connection acted as a server
2312 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2313 * when set up and the client passed credentials as part of the
2314 * authentication process.
2316 * In a message bus setup, the message bus is always the server and
2317 * each application is a client. So this method will always return
2318 * %NULL for message bus clients.
2320 * Returns: A #GCredentials or %NULL if not available. Do not free
2321 * this object, it is owned by @connection.
2326 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2328 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2329 return connection->priv->crendentials;
2332 /* ---------------------------------------------------------------------------------------------------- */
2334 static guint _global_filter_id = 1;
2337 * g_dbus_connection_add_filter:
2338 * @connection: A #GDBusConnection.
2339 * @filter_function: A filter function.
2340 * @user_data: User data to pass to @filter_function.
2341 * @user_data_free_func: Function to free @user_data with when filter
2342 * is removed or %NULL.
2344 * Adds a message filter. Filters are handlers that are run on all
2345 * incoming and outgoing messages, prior to standard dispatch. Filters
2346 * are run in the order that they were added. The same handler can be
2347 * added as a filter more than once, in which case it will be run more
2348 * than once. Filters added during a filter callback won't be run on
2349 * the message being processed.
2351 * Note that filters are run in a dedicated message handling thread so
2352 * they can't block and, generally, can't do anything but signal a
2353 * worker thread. Also note that filters are rarely needed - use API
2354 * such as g_dbus_connection_send_message_with_reply(),
2355 * g_dbus_connection_signal_subscribe() or
2356 * g_dbus_connection_call() instead.
2358 * If a filter consumes an incoming message (by returning %TRUE), the
2359 * message is not dispatched anywhere else - not even the standard
2360 * dispatch machinery (that API such as
2361 * g_dbus_connection_signal_subscribe() and
2362 * g_dbus_connection_send_message_with_reply() relies on) will see the
2363 * message. Similary, if a filter consumes an outgoing message, the
2364 * message will not be sent to the other peer.
2366 * Returns: A filter identifier that can be used with
2367 * g_dbus_connection_remove_filter().
2372 g_dbus_connection_add_filter (GDBusConnection *connection,
2373 GDBusMessageFilterFunction filter_function,
2375 GDestroyNotify user_data_free_func)
2379 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2380 g_return_val_if_fail (filter_function != NULL, 0);
2382 CONNECTION_LOCK (connection);
2383 data = g_new0 (FilterData, 1);
2384 data->id = _global_filter_id++; /* TODO: overflow etc. */
2385 data->filter_function = filter_function;
2386 data->user_data = user_data;
2387 data->user_data_free_func = user_data_free_func;
2388 g_ptr_array_add (connection->priv->filters, data);
2389 CONNECTION_UNLOCK (connection);
2394 /* only called from finalize(), removes all filters */
2396 purge_all_filters (GDBusConnection *connection)
2399 for (n = 0; n < connection->priv->filters->len; n++)
2401 FilterData *data = connection->priv->filters->pdata[n];
2402 if (data->user_data_free_func != NULL)
2403 data->user_data_free_func (data->user_data);
2409 * g_dbus_connection_remove_filter:
2410 * @connection: a #GDBusConnection
2411 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2418 g_dbus_connection_remove_filter (GDBusConnection *connection,
2422 FilterData *to_destroy;
2424 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2426 CONNECTION_LOCK (connection);
2428 for (n = 0; n < connection->priv->filters->len; n++)
2430 FilterData *data = connection->priv->filters->pdata[n];
2431 if (data->id == filter_id)
2433 g_ptr_array_remove_index (connection->priv->filters, n);
2438 CONNECTION_UNLOCK (connection);
2440 /* do free without holding lock */
2441 if (to_destroy != NULL)
2443 if (to_destroy->user_data_free_func != NULL)
2444 to_destroy->user_data_free_func (to_destroy->user_data);
2445 g_free (to_destroy);
2449 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2453 /* ---------------------------------------------------------------------------------------------------- */
2459 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2460 gchar *interface_name;
2464 GArray *subscribers;
2469 GDBusSignalCallback callback;
2471 GDestroyNotify user_data_free_func;
2473 GMainContext *context;
2477 signal_data_free (SignalData *signal_data)
2479 g_free (signal_data->rule);
2480 g_free (signal_data->sender);
2481 g_free (signal_data->sender_unique_name);
2482 g_free (signal_data->interface_name);
2483 g_free (signal_data->member);
2484 g_free (signal_data->object_path);
2485 g_free (signal_data->arg0);
2486 g_array_free (signal_data->subscribers, TRUE);
2487 g_free (signal_data);
2491 args_to_rule (const gchar *sender,
2492 const gchar *interface_name,
2493 const gchar *member,
2494 const gchar *object_path,
2499 rule = g_string_new ("type='signal'");
2501 g_string_append_printf (rule, ",sender='%s'", sender);
2502 if (interface_name != NULL)
2503 g_string_append_printf (rule, ",interface='%s'", interface_name);
2505 g_string_append_printf (rule, ",member='%s'", member);
2506 if (object_path != NULL)
2507 g_string_append_printf (rule, ",path='%s'", object_path);
2509 g_string_append_printf (rule, ",arg0='%s'", arg0);
2511 return g_string_free (rule, FALSE);
2514 static guint _global_subscriber_id = 1;
2515 static guint _global_registration_id = 1;
2516 static guint _global_subtree_registration_id = 1;
2518 /* ---------------------------------------------------------------------------------------------------- */
2520 /* must hold lock when calling */
2522 add_match_rule (GDBusConnection *connection,
2523 const gchar *match_rule)
2526 GDBusMessage *message;
2528 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2529 "/org/freedesktop/DBus", /* path */
2530 "org.freedesktop.DBus", /* interface */
2532 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2534 if (!g_dbus_connection_send_message_unlocked (connection,
2539 g_critical ("Error while sending AddMatch() message: %s", error->message);
2540 g_error_free (error);
2542 g_object_unref (message);
2545 /* ---------------------------------------------------------------------------------------------------- */
2547 /* must hold lock when calling */
2549 remove_match_rule (GDBusConnection *connection,
2550 const gchar *match_rule)
2553 GDBusMessage *message;
2555 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2556 "/org/freedesktop/DBus", /* path */
2557 "org.freedesktop.DBus", /* interface */
2559 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2562 if (!g_dbus_connection_send_message_unlocked (connection,
2567 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2568 g_error_free (error);
2570 g_object_unref (message);
2573 /* ---------------------------------------------------------------------------------------------------- */
2576 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2578 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
2579 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2580 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2581 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2582 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2585 /* ---------------------------------------------------------------------------------------------------- */
2588 * g_dbus_connection_signal_subscribe:
2589 * @connection: A #GDBusConnection.
2590 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
2591 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2592 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2593 * @object_path: Object path to match on or %NULL to match on all object paths.
2594 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2595 * @callback: Callback to invoke when there is a signal matching the requested data.
2596 * @user_data: User data to pass to @callback.
2597 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2599 * Subscribes to signals on @connection and invokes @callback with a
2600 * whenever the signal is received. Note that @callback
2601 * will be invoked in the <link
2602 * linkend="g-main-context-push-thread-default">thread-default main
2603 * loop</link> of the thread you are calling this method from.
2605 * If @connection is not a message bus connection, @sender must be
2608 * If @sender is a well-known name note that @callback is invoked with
2609 * the unique name for the owner of @sender, not the well-known name
2610 * as one would expect. This is because the message bus rewrites the
2611 * name. As such, to avoid certain race conditions, users should be
2612 * tracking the name owner of the well-known name and use that when
2613 * processing the received signal.
2615 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2620 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2621 const gchar *sender,
2622 const gchar *interface_name,
2623 const gchar *member,
2624 const gchar *object_path,
2626 GDBusSignalCallback callback,
2628 GDestroyNotify user_data_free_func)
2631 SignalData *signal_data;
2632 SignalSubscriber subscriber;
2633 GPtrArray *signal_data_array;
2634 const gchar *sender_unique_name;
2636 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2637 * an OOM condition. We might want to change that but that would involve making
2638 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2639 * handle that. And there's really no sensible way of handling this short of retrying
2640 * to add the match rule... and then there's the little thing that, hey, maybe there's
2641 * a reason the bus in an OOM condition.
2643 * Doable, but not really sure it's worth it...
2646 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2647 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2648 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2649 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2650 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2651 g_return_val_if_fail (callback != NULL, 0);
2653 CONNECTION_LOCK (connection);
2655 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2657 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
2658 sender_unique_name = sender;
2660 sender_unique_name = "";
2662 subscriber.callback = callback;
2663 subscriber.user_data = user_data;
2664 subscriber.user_data_free_func = user_data_free_func;
2665 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2666 subscriber.context = g_main_context_get_thread_default ();
2667 if (subscriber.context != NULL)
2668 g_main_context_ref (subscriber.context);
2670 /* see if we've already have this rule */
2671 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2672 if (signal_data != NULL)
2674 g_array_append_val (signal_data->subscribers, subscriber);
2679 signal_data = g_new0 (SignalData, 1);
2680 signal_data->rule = rule;
2681 signal_data->sender = g_strdup (sender);
2682 signal_data->sender_unique_name = g_strdup (sender_unique_name);
2683 signal_data->interface_name = g_strdup (interface_name);
2684 signal_data->member = g_strdup (member);
2685 signal_data->object_path = g_strdup (object_path);
2686 signal_data->arg0 = g_strdup (arg0);
2687 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2688 g_array_append_val (signal_data->subscribers, subscriber);
2690 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2694 /* Add the match rule to the bus...
2696 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2697 * always send such messages to us.
2699 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2701 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2702 add_match_rule (connection, signal_data->rule);
2705 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array,
2706 signal_data->sender_unique_name);
2707 if (signal_data_array == NULL)
2709 signal_data_array = g_ptr_array_new ();
2710 g_hash_table_insert (connection->priv->map_sender_unique_name_to_signal_data_array,
2711 g_strdup (signal_data->sender_unique_name),
2714 g_ptr_array_add (signal_data_array, signal_data);
2717 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2718 GUINT_TO_POINTER (subscriber.id),
2721 CONNECTION_UNLOCK (connection);
2723 return subscriber.id;
2726 /* ---------------------------------------------------------------------------------------------------- */
2728 /* must hold lock when calling this */
2730 unsubscribe_id_internal (GDBusConnection *connection,
2731 guint subscription_id,
2732 GArray *out_removed_subscribers)
2734 SignalData *signal_data;
2735 GPtrArray *signal_data_array;
2738 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2739 GUINT_TO_POINTER (subscription_id));
2740 if (signal_data == NULL)
2742 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2746 for (n = 0; n < signal_data->subscribers->len; n++)
2748 SignalSubscriber *subscriber;
2750 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2751 if (subscriber->id != subscription_id)
2754 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2755 GUINT_TO_POINTER (subscription_id)));
2756 g_array_append_val (out_removed_subscribers, *subscriber);
2757 g_array_remove_index (signal_data->subscribers, n);
2759 if (signal_data->subscribers->len == 0)
2761 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2763 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array,
2764 signal_data->sender_unique_name);
2765 g_warn_if_fail (signal_data_array != NULL);
2766 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2768 if (signal_data_array->len == 0)
2770 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_unique_name_to_signal_data_array,
2771 signal_data->sender_unique_name));
2774 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2775 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2777 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2778 if (!connection->priv->closed)
2779 remove_match_rule (connection, signal_data->rule);
2781 signal_data_free (signal_data);
2787 g_assert_not_reached ();
2794 * g_dbus_connection_signal_unsubscribe:
2795 * @connection: A #GDBusConnection.
2796 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2798 * Unsubscribes from signals.
2803 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2804 guint subscription_id)
2806 GArray *subscribers;
2809 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2811 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2813 CONNECTION_LOCK (connection);
2814 unsubscribe_id_internal (connection,
2817 CONNECTION_UNLOCK (connection);
2820 g_assert (subscribers->len == 0 || subscribers->len == 1);
2822 /* call GDestroyNotify without lock held */
2823 for (n = 0; n < subscribers->len; n++)
2825 SignalSubscriber *subscriber;
2826 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2827 if (subscriber->user_data_free_func != NULL)
2828 subscriber->user_data_free_func (subscriber->user_data);
2829 if (subscriber->context != NULL)
2830 g_main_context_unref (subscriber->context);
2833 g_array_free (subscribers, TRUE);
2836 /* ---------------------------------------------------------------------------------------------------- */
2840 guint subscription_id;
2841 GDBusSignalCallback callback;
2843 GDBusMessage *message;
2844 GDBusConnection *connection;
2845 const gchar *sender;
2847 const gchar *interface;
2848 const gchar *member;
2851 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2855 emit_signal_instance_in_idle_cb (gpointer data)
2857 SignalInstance *signal_instance = data;
2858 GVariant *parameters;
2859 gboolean has_subscription;
2861 parameters = g_dbus_message_get_body (signal_instance->message);
2862 if (parameters == NULL)
2864 parameters = g_variant_new ("()");
2865 g_variant_ref_sink (parameters);
2869 g_variant_ref_sink (parameters);
2873 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
2874 signal_instance->subscription_id,
2875 signal_instance->sender,
2876 signal_instance->path,
2877 signal_instance->interface,
2878 signal_instance->member,
2879 g_variant_print (parameters, TRUE));
2882 /* Careful here, don't do the callback if we no longer has the subscription */
2883 CONNECTION_LOCK (signal_instance->connection);
2884 has_subscription = FALSE;
2885 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2886 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2887 has_subscription = TRUE;
2888 CONNECTION_UNLOCK (signal_instance->connection);
2890 if (has_subscription)
2891 signal_instance->callback (signal_instance->connection,
2892 signal_instance->sender,
2893 signal_instance->path,
2894 signal_instance->interface,
2895 signal_instance->member,
2897 signal_instance->user_data);
2899 if (parameters != NULL)
2900 g_variant_unref (parameters);
2906 signal_instance_free (SignalInstance *signal_instance)
2908 g_object_unref (signal_instance->message);
2909 g_object_unref (signal_instance->connection);
2910 g_free (signal_instance);
2913 /* called in message handler thread WITH lock held */
2915 schedule_callbacks (GDBusConnection *connection,
2916 GPtrArray *signal_data_array,
2917 GDBusMessage *message,
2918 const gchar *sender)
2921 const gchar *interface;
2922 const gchar *member;
2931 interface = g_dbus_message_get_interface (message);
2932 member = g_dbus_message_get_member (message);
2933 path = g_dbus_message_get_path (message);
2934 arg0 = g_dbus_message_get_arg0 (message);
2937 g_print ("In schedule_callbacks:\n"
2939 " interface = `%s'\n"
2950 /* TODO: if this is slow, then we can change signal_data_array into
2951 * map_object_path_to_signal_data_array or something.
2953 for (n = 0; n < signal_data_array->len; n++)
2955 SignalData *signal_data = signal_data_array->pdata[n];
2957 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2960 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2963 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2966 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2969 for (m = 0; m < signal_data->subscribers->len; m++)
2971 SignalSubscriber *subscriber;
2972 GSource *idle_source;
2973 SignalInstance *signal_instance;
2975 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2977 signal_instance = g_new0 (SignalInstance, 1);
2978 signal_instance->subscription_id = subscriber->id;
2979 signal_instance->callback = subscriber->callback;
2980 signal_instance->user_data = subscriber->user_data;
2981 signal_instance->message = g_object_ref (message);
2982 signal_instance->connection = g_object_ref (connection);
2983 signal_instance->sender = sender;
2984 signal_instance->path = path;
2985 signal_instance->interface = interface;
2986 signal_instance->member = member;
2988 idle_source = g_idle_source_new ();
2989 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2990 g_source_set_callback (idle_source,
2991 emit_signal_instance_in_idle_cb,
2993 (GDestroyNotify) signal_instance_free);
2994 g_source_attach (idle_source, subscriber->context);
2995 g_source_unref (idle_source);
3000 /* called in message handler thread with lock held */
3002 distribute_signals (GDBusConnection *connection,
3003 GDBusMessage *message)
3005 GPtrArray *signal_data_array;
3006 const gchar *sender;
3008 sender = g_dbus_message_get_sender (message);
3010 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3012 _g_dbus_debug_print_lock ();
3013 g_print ("========================================================================\n"
3014 "GDBus-debug:Signal:\n"
3015 " >>>> SIGNAL %s.%s\n"
3017 " sent by name %s\n",
3018 g_dbus_message_get_interface (message),
3019 g_dbus_message_get_member (message),
3020 g_dbus_message_get_path (message),
3021 sender != NULL ? sender : "(none)");
3022 _g_dbus_debug_print_unlock ();
3025 /* collect subscribers that match on sender */
3028 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array, sender);
3029 if (signal_data_array != NULL)
3030 schedule_callbacks (connection, signal_data_array, message, sender);
3033 /* collect subscribers not matching on sender */
3034 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array, "");
3035 if (signal_data_array != NULL)
3036 schedule_callbacks (connection, signal_data_array, message, sender);
3039 /* ---------------------------------------------------------------------------------------------------- */
3041 /* only called from finalize(), removes all subscriptions */
3043 purge_all_signal_subscriptions (GDBusConnection *connection)
3045 GHashTableIter iter;
3048 GArray *subscribers;
3051 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3052 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
3053 while (g_hash_table_iter_next (&iter, &key, NULL))
3055 guint subscription_id = GPOINTER_TO_UINT (key);
3056 g_array_append_val (ids, subscription_id);
3059 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3060 for (n = 0; n < ids->len; n++)
3062 guint subscription_id = g_array_index (ids, guint, n);
3063 unsubscribe_id_internal (connection,
3067 g_array_free (ids, TRUE);
3069 /* call GDestroyNotify without lock held */
3070 for (n = 0; n < subscribers->len; n++)
3072 SignalSubscriber *subscriber;
3073 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3074 if (subscriber->user_data_free_func != NULL)
3075 subscriber->user_data_free_func (subscriber->user_data);
3076 if (subscriber->context != NULL)
3077 g_main_context_unref (subscriber->context);
3080 g_array_free (subscribers, TRUE);
3083 /* ---------------------------------------------------------------------------------------------------- */
3085 struct ExportedObject
3088 GDBusConnection *connection;
3090 /* maps gchar* -> ExportedInterface* */
3091 GHashTable *map_if_name_to_ei;
3094 /* only called with lock held */
3096 exported_object_free (ExportedObject *eo)
3098 g_free (eo->object_path);
3099 g_hash_table_unref (eo->map_if_name_to_ei);
3108 gchar *interface_name;
3109 const GDBusInterfaceVTable *vtable;
3110 const GDBusInterfaceInfo *interface_info;
3112 GMainContext *context;
3114 GDestroyNotify user_data_free_func;
3115 } ExportedInterface;
3117 /* called with lock held */
3119 exported_interface_free (ExportedInterface *ei)
3121 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3123 if (ei->user_data_free_func != NULL)
3124 /* TODO: push to thread-default mainloop */
3125 ei->user_data_free_func (ei->user_data);
3127 if (ei->context != NULL)
3128 g_main_context_unref (ei->context);
3130 g_free (ei->interface_name);
3134 /* ---------------------------------------------------------------------------------------------------- */
3136 /* Convenience function to check if @registration_id (if not zero) or
3137 * @subtree_registration_id (if not zero) has been unregistered. If
3138 * so, returns %TRUE.
3140 * Caller must *not* hold lock.
3143 has_object_been_unregistered (GDBusConnection *connection,
3144 guint registration_id,
3145 guint subtree_registration_id)
3149 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3153 CONNECTION_LOCK (connection);
3154 if (registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_ei,
3155 GUINT_TO_POINTER (registration_id)) == NULL)
3159 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_es,
3160 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3164 CONNECTION_UNLOCK (connection);
3169 /* ---------------------------------------------------------------------------------------------------- */
3173 GDBusConnection *connection;
3174 GDBusMessage *message;
3176 const gchar *property_name;
3177 const GDBusInterfaceVTable *vtable;
3178 const GDBusInterfaceInfo *interface_info;
3179 const GDBusPropertyInfo *property_info;
3180 guint registration_id;
3181 guint subtree_registration_id;
3185 property_data_free (PropertyData *data)
3187 g_object_unref (data->connection);
3188 g_object_unref (data->message);
3192 /* called in thread where object was registered - no locks held */
3194 invoke_get_property_in_idle_cb (gpointer _data)
3196 PropertyData *data = _data;
3199 GDBusMessage *reply;
3201 if (has_object_been_unregistered (data->connection,
3202 data->registration_id,
3203 data->subtree_registration_id))
3205 reply = g_dbus_message_new_method_error (data->message,
3206 "org.freedesktop.DBus.Error.UnknownMethod",
3207 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3208 g_dbus_message_get_path (data->message));
3209 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3210 g_object_unref (reply);
3215 value = data->vtable->get_property (data->connection,
3216 g_dbus_message_get_sender (data->message),
3217 g_dbus_message_get_path (data->message),
3218 data->interface_info->name,
3219 data->property_name,
3226 g_assert_no_error (error);
3228 g_variant_ref_sink (value);
3229 reply = g_dbus_message_new_method_reply (data->message);
3230 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3231 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3232 g_variant_unref (value);
3233 g_object_unref (reply);
3237 gchar *dbus_error_name;
3238 g_assert (error != NULL);
3239 dbus_error_name = g_dbus_error_encode_gerror (error);
3240 reply = g_dbus_message_new_method_error_literal (data->message,
3243 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3244 g_free (dbus_error_name);
3245 g_error_free (error);
3246 g_object_unref (reply);
3253 /* called in thread where object was registered - no locks held */
3255 invoke_set_property_in_idle_cb (gpointer _data)
3257 PropertyData *data = _data;
3259 GDBusMessage *reply;
3265 g_variant_get (g_dbus_message_get_body (data->message),
3271 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3272 * of the given value is wrong
3274 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3276 reply = g_dbus_message_new_method_error (data->message,
3277 "org.freedesktop.DBus.Error.InvalidArgs",
3278 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3279 data->property_info->name,
3280 data->property_info->signature,
3281 g_variant_get_type_string (value));
3285 if (!data->vtable->set_property (data->connection,
3286 g_dbus_message_get_sender (data->message),
3287 g_dbus_message_get_path (data->message),
3288 data->interface_info->name,
3289 data->property_name,
3294 gchar *dbus_error_name;
3295 g_assert (error != NULL);
3296 dbus_error_name = g_dbus_error_encode_gerror (error);
3297 reply = g_dbus_message_new_method_error_literal (data->message,
3300 g_free (dbus_error_name);
3301 g_error_free (error);
3305 reply = g_dbus_message_new_method_reply (data->message);
3309 g_assert (reply != NULL);
3310 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3311 g_object_unref (reply);
3316 /* called with lock held */
3318 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3319 GDBusMessage *message,
3320 guint registration_id,
3321 guint subtree_registration_id,
3323 const GDBusInterfaceInfo *interface_info,
3324 const GDBusInterfaceVTable *vtable,
3325 GMainContext *main_context,
3329 const char *interface_name;
3330 const char *property_name;
3331 const GDBusPropertyInfo *property_info;
3332 GSource *idle_source;
3333 PropertyData *property_data;
3334 GDBusMessage *reply;
3339 g_variant_get (g_dbus_message_get_body (message),
3344 g_variant_get (g_dbus_message_get_body (message),
3353 if (vtable == NULL || vtable->get_property == NULL)
3358 if (vtable == NULL || vtable->set_property == NULL)
3362 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3364 property_info = NULL;
3366 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3367 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3368 if (property_info == NULL)
3370 reply = g_dbus_message_new_method_error (message,
3371 "org.freedesktop.DBus.Error.InvalidArgs",
3372 _("No such property `%s'"),
3374 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3375 g_object_unref (reply);
3380 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3382 reply = g_dbus_message_new_method_error (message,
3383 "org.freedesktop.DBus.Error.InvalidArgs",
3384 _("Property `%s' is not readable"),
3386 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3387 g_object_unref (reply);
3391 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3393 reply = g_dbus_message_new_method_error (message,
3394 "org.freedesktop.DBus.Error.InvalidArgs",
3395 _("Property `%s' is not writable"),
3397 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3398 g_object_unref (reply);
3403 /* ok, got the property info - call user code in an idle handler */
3404 property_data = g_new0 (PropertyData, 1);
3405 property_data->connection = g_object_ref (connection);
3406 property_data->message = g_object_ref (message);
3407 property_data->user_data = user_data;
3408 property_data->property_name = property_name;
3409 property_data->vtable = vtable;
3410 property_data->interface_info = interface_info;
3411 property_data->property_info = property_info;
3412 property_data->registration_id = registration_id;
3413 property_data->subtree_registration_id = subtree_registration_id;
3415 idle_source = g_idle_source_new ();
3416 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3417 g_source_set_callback (idle_source,
3418 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3420 (GDestroyNotify) property_data_free);
3421 g_source_attach (idle_source, main_context);
3422 g_source_unref (idle_source);
3430 /* called with lock held */
3432 handle_getset_property (GDBusConnection *connection,
3434 GDBusMessage *message,
3437 ExportedInterface *ei;
3439 const char *interface_name;
3440 const char *property_name;
3445 g_variant_get (g_dbus_message_get_body (message),
3450 g_variant_get (g_dbus_message_get_body (message),
3456 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3457 * no such interface registered
3459 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3462 GDBusMessage *reply;
3463 reply = g_dbus_message_new_method_error (message,
3464 "org.freedesktop.DBus.Error.InvalidArgs",
3465 _("No such interface `%s'"),
3467 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3468 g_object_unref (reply);
3473 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3486 /* ---------------------------------------------------------------------------------------------------- */
3490 GDBusConnection *connection;
3491 GDBusMessage *message;
3493 const GDBusInterfaceVTable *vtable;
3494 const GDBusInterfaceInfo *interface_info;
3495 guint registration_id;
3496 guint subtree_registration_id;
3497 } PropertyGetAllData;
3500 property_get_all_data_free (PropertyData *data)
3502 g_object_unref (data->connection);
3503 g_object_unref (data->message);
3507 /* called in thread where object was registered - no locks held */
3509 invoke_get_all_properties_in_idle_cb (gpointer _data)
3511 PropertyGetAllData *data = _data;
3512 GVariantBuilder builder;
3514 GDBusMessage *reply;
3517 if (has_object_been_unregistered (data->connection,
3518 data->registration_id,
3519 data->subtree_registration_id))
3521 reply = g_dbus_message_new_method_error (data->message,
3522 "org.freedesktop.DBus.Error.UnknownMethod",
3523 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3524 g_dbus_message_get_path (data->message));
3525 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3526 g_object_unref (reply);
3532 /* TODO: Right now we never fail this call - we just omit values if
3533 * a get_property() call is failing.
3535 * We could fail the whole call if just a single get_property() call
3536 * returns an error. We need clarification in the D-Bus spec about this.
3538 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3539 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3540 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3542 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3545 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3548 value = data->vtable->get_property (data->connection,
3549 g_dbus_message_get_sender (data->message),
3550 g_dbus_message_get_path (data->message),
3551 data->interface_info->name,
3552 property_info->name,
3559 g_variant_builder_add (&builder,
3561 property_info->name,
3564 g_variant_builder_close (&builder);
3566 reply = g_dbus_message_new_method_reply (data->message);
3567 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3568 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3569 g_object_unref (reply);
3575 /* called with lock held */
3577 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3578 GDBusMessage *message,
3579 guint registration_id,
3580 guint subtree_registration_id,
3581 const GDBusInterfaceInfo *interface_info,
3582 const GDBusInterfaceVTable *vtable,
3583 GMainContext *main_context,
3587 const char *interface_name;
3588 GSource *idle_source;
3589 PropertyGetAllData *property_get_all_data;
3593 g_variant_get (g_dbus_message_get_body (message),
3597 if (vtable == NULL || vtable->get_property == NULL)
3600 /* ok, got the property info - call user in an idle handler */
3601 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3602 property_get_all_data->connection = g_object_ref (connection);
3603 property_get_all_data->message = g_object_ref (message);
3604 property_get_all_data->user_data = user_data;
3605 property_get_all_data->vtable = vtable;
3606 property_get_all_data->interface_info = interface_info;
3607 property_get_all_data->registration_id = registration_id;
3608 property_get_all_data->subtree_registration_id = subtree_registration_id;
3610 idle_source = g_idle_source_new ();
3611 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3612 g_source_set_callback (idle_source,
3613 invoke_get_all_properties_in_idle_cb,
3614 property_get_all_data,
3615 (GDestroyNotify) property_get_all_data_free);
3616 g_source_attach (idle_source, main_context);
3617 g_source_unref (idle_source);
3625 /* called with lock held */
3627 handle_get_all_properties (GDBusConnection *connection,
3629 GDBusMessage *message)
3631 ExportedInterface *ei;
3633 const char *interface_name;
3637 g_variant_get (g_dbus_message_get_body (message),
3641 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3642 * no such interface registered
3644 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3647 GDBusMessage *reply;
3648 reply = g_dbus_message_new_method_error (message,
3649 "org.freedesktop.DBus.Error.InvalidArgs",
3650 _("No such interface"),
3652 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3653 g_object_unref (reply);
3658 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3670 /* ---------------------------------------------------------------------------------------------------- */
3672 static const gchar introspect_header[] =
3673 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3674 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3675 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3678 static const gchar introspect_tail[] =
3681 static const gchar introspect_standard_interfaces[] =
3682 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3683 " <method name=\"Get\">\n"
3684 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3685 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3686 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3688 " <method name=\"GetAll\">\n"
3689 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3690 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3692 " <method name=\"Set\">\n"
3693 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3694 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3695 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3697 " <signal name=\"PropertiesChanged\">\n"
3698 " <arg type=\"s\" name=\"interface_name\"/>\n"
3699 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3700 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3703 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3704 " <method name=\"Introspect\">\n"
3705 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3708 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3709 " <method name=\"Ping\"/>\n"
3710 " <method name=\"GetMachineId\">\n"
3711 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3716 introspect_append_header (GString *s)
3718 g_string_append (s, introspect_header);
3722 introspect_append_standard_interfaces (GString *s)
3724 g_string_append (s, introspect_standard_interfaces);
3728 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3730 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
3736 begin = object_path + path_len;
3737 end = strchr (begin, '/');
3739 s = g_strndup (begin, end - begin);
3741 s = g_strdup (begin);
3743 if (g_hash_table_lookup (set, s) == NULL)
3744 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3750 /* TODO: we want a nicer public interface for this */
3752 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3757 GHashTableIter hash_iter;
3758 const gchar *object_path;
3764 CONNECTION_ENSURE_LOCK (connection);
3766 path_len = strlen (path);
3770 set = g_hash_table_new (g_str_hash, g_str_equal);
3772 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3773 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3774 maybe_add_path (path, path_len, object_path, set);
3776 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3777 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3778 maybe_add_path (path, path_len, object_path, set);
3780 p = g_ptr_array_new ();
3781 keys = g_hash_table_get_keys (set);
3782 for (l = keys; l != NULL; l = l->next)
3783 g_ptr_array_add (p, l->data);
3784 g_hash_table_unref (set);
3787 g_ptr_array_add (p, NULL);
3788 ret = (gchar **) g_ptr_array_free (p, FALSE);
3793 g_dbus_connection_list_registered (GDBusConnection *connection,
3797 CONNECTION_LOCK (connection);
3798 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3799 CONNECTION_UNLOCK (connection);
3803 /* called in message handler thread with lock held */
3805 handle_introspect (GDBusConnection *connection,
3807 GDBusMessage *message)
3811 GDBusMessage *reply;
3812 GHashTableIter hash_iter;
3813 ExportedInterface *ei;
3816 /* first the header with the standard interfaces */
3817 s = g_string_sized_new (sizeof (introspect_header) +
3818 sizeof (introspect_standard_interfaces) +
3819 sizeof (introspect_tail));
3820 introspect_append_header (s);
3821 introspect_append_standard_interfaces (s);
3823 /* then include the registered interfaces */
3824 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3825 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3826 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
3828 /* finally include nodes registered below us */
3829 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3830 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3831 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3832 g_strfreev (registered);
3833 g_string_append (s, introspect_tail);
3835 reply = g_dbus_message_new_method_reply (message);
3836 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3837 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3838 g_object_unref (reply);
3839 g_string_free (s, TRUE);
3844 /* called in thread where object was registered - no locks held */
3846 call_in_idle_cb (gpointer user_data)
3848 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3849 GDBusInterfaceVTable *vtable;
3850 guint registration_id;
3851 guint subtree_registration_id;
3853 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3854 g_assert (vtable != NULL && vtable->method_call != NULL);
3856 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
3857 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
3859 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
3861 subtree_registration_id))
3863 GDBusMessage *reply;
3864 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
3865 "org.freedesktop.DBus.Error.UnknownMethod",
3866 _("No such interface `%s' on object at path %s"),
3867 g_dbus_method_invocation_get_interface_name (invocation),
3868 g_dbus_method_invocation_get_object_path (invocation));
3869 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, NULL, NULL);
3870 g_object_unref (reply);
3874 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3875 g_dbus_method_invocation_get_sender (invocation),
3876 g_dbus_method_invocation_get_object_path (invocation),
3877 g_dbus_method_invocation_get_interface_name (invocation),
3878 g_dbus_method_invocation_get_method_name (invocation),
3879 g_dbus_method_invocation_get_parameters (invocation),
3880 g_object_ref (invocation),
3881 g_dbus_method_invocation_get_user_data (invocation));
3887 /* called in message handler thread with lock held */
3889 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3890 GDBusMessage *message,
3891 guint registration_id,
3892 guint subtree_registration_id,
3893 const GDBusInterfaceInfo *interface_info,
3894 const GDBusInterfaceVTable *vtable,
3895 GMainContext *main_context,
3898 GDBusMethodInvocation *invocation;
3899 const GDBusMethodInfo *method_info;
3900 GDBusMessage *reply;
3901 GVariant *parameters;
3902 GSource *idle_source;
3904 GVariantType *in_type;
3908 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3909 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
3911 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3912 * error to the caller
3914 if (method_info == NULL)
3916 reply = g_dbus_message_new_method_error (message,
3917 "org.freedesktop.DBus.Error.UnknownMethod",
3918 _("No such method `%s'"),
3919 g_dbus_message_get_member (message));
3920 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3921 g_object_unref (reply);
3926 parameters = g_dbus_message_get_body (message);
3927 if (parameters == NULL)
3929 parameters = g_variant_new ("()");
3930 g_variant_ref_sink (parameters);
3934 g_variant_ref (parameters);
3937 /* Check that the incoming args are of the right type - if they are not, return
3938 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3940 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
3941 if (!g_variant_is_of_type (parameters, in_type))
3945 type_string = g_variant_type_dup_string (in_type);
3947 reply = g_dbus_message_new_method_error (message,
3948 "org.freedesktop.DBus.Error.InvalidArgs",
3949 _("Type of message, `%s', does not match expected type `%s'"),
3950 g_variant_get_type_string (parameters),
3952 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3953 g_variant_type_free (in_type);
3954 g_variant_unref (parameters);
3955 g_object_unref (reply);
3956 g_free (type_string);
3960 g_variant_type_free (in_type);
3962 /* schedule the call in idle */
3963 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3964 g_dbus_message_get_path (message),
3965 g_dbus_message_get_interface (message),
3966 g_dbus_message_get_member (message),
3972 g_variant_unref (parameters);
3974 /* TODO: would be nicer with a real MethodData like we already
3975 * have PropertyData and PropertyGetAllData... */
3976 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
3977 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
3978 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
3980 idle_source = g_idle_source_new ();
3981 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3982 g_source_set_callback (idle_source,
3986 g_source_attach (idle_source, main_context);
3987 g_source_unref (idle_source);
3995 /* ---------------------------------------------------------------------------------------------------- */
3997 /* called in message handler thread with lock held */
3999 obj_message_func (GDBusConnection *connection,
4001 GDBusMessage *message)
4003 const gchar *interface_name;
4004 const gchar *member;
4005 const gchar *signature;
4010 interface_name = g_dbus_message_get_interface (message);
4011 member = g_dbus_message_get_member (message);
4012 signature = g_dbus_message_get_signature (message);
4014 /* see if we have an interface for handling this call */
4015 if (interface_name != NULL)
4017 ExportedInterface *ei;
4018 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4021 /* we do - invoke the handler in idle in the right thread */
4023 /* handle no vtable or handler being present */
4024 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4027 handled = validate_and_maybe_schedule_method_call (connection,
4039 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4040 g_strcmp0 (member, "Introspect") == 0 &&
4041 g_strcmp0 (signature, "") == 0)
4043 handled = handle_introspect (connection, eo, message);
4046 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4047 g_strcmp0 (member, "Get") == 0 &&
4048 g_strcmp0 (signature, "ss") == 0)
4050 handled = handle_getset_property (connection, eo, message, TRUE);
4053 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4054 g_strcmp0 (member, "Set") == 0 &&
4055 g_strcmp0 (signature, "ssv") == 0)
4057 handled = handle_getset_property (connection, eo, message, FALSE);
4060 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4061 g_strcmp0 (member, "GetAll") == 0 &&
4062 g_strcmp0 (signature, "s") == 0)
4064 handled = handle_get_all_properties (connection, eo, message);
4073 * g_dbus_connection_register_object:
4074 * @connection: A #GDBusConnection.
4075 * @object_path: The object path to register at.
4076 * @interface_info: Introspection data for the interface.
4077 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4078 * @user_data: Data to pass to functions in @vtable.
4079 * @user_data_free_func: Function to call when the object path is unregistered.
4080 * @error: Return location for error or %NULL.
4082 * Registers callbacks for exported objects at @object_path with the
4083 * D-Bus interface that is described in @interface_info.
4085 * Calls to functions in @vtable (and @user_data_free_func) will
4086 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4087 * loop</link> of the thread you are calling this method from.
4089 * Note that all #GVariant values passed to functions in @vtable will match
4090 * the signature given in @interface_info - if a remote caller passes
4091 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4092 * is returned to the remote caller.
4094 * Additionally, if the remote caller attempts to invoke methods or
4095 * access properties not mentioned in @interface_info the
4096 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4097 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4098 * are returned to the caller.
4100 * It is considered a programming error if the
4101 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4102 * #GVariant of incorrect type.
4104 * If an existing callback is already registered at @object_path and
4105 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4107 * Note that @vtable is not copied, so the struct you pass must exist until
4108 * the path is unregistered. One possibility is to free @vtable at the
4109 * same time as @user_data when @user_data_free_func is called.
4111 * GDBus automatically implements the standard D-Bus interfaces
4112 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4113 * and org.freedesktop.Peer, so you don't have to implement those for
4114 * the objects you export. You <emphasis>can</emphasis> implement
4115 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4116 * and setting of properties asynchronously.
4118 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4120 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4121 * that can be used with g_dbus_connection_unregister_object() .
4126 g_dbus_connection_register_object (GDBusConnection *connection,
4127 const gchar *object_path,
4128 const GDBusInterfaceInfo *interface_info,
4129 const GDBusInterfaceVTable *vtable,
4131 GDestroyNotify user_data_free_func,
4135 ExportedInterface *ei;
4138 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4139 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4140 g_return_val_if_fail (interface_info != NULL, 0);
4141 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4142 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4146 CONNECTION_LOCK (connection);
4148 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
4151 eo = g_new0 (ExportedObject, 1);
4152 eo->object_path = g_strdup (object_path);
4153 eo->connection = connection;
4154 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4157 (GDestroyNotify) exported_interface_free);
4158 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
4161 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4167 _("An object is already exported for the interface %s at %s"),
4168 interface_info->name,
4173 ei = g_new0 (ExportedInterface, 1);
4174 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4176 ei->user_data = user_data;
4177 ei->user_data_free_func = user_data_free_func;
4178 ei->vtable = vtable;
4179 ei->interface_info = g_dbus_interface_info_ref ((GDBusInterfaceInfo *) interface_info);
4180 ei->interface_name = g_strdup (interface_info->name);
4181 ei->context = g_main_context_get_thread_default ();
4182 if (ei->context != NULL)
4183 g_main_context_ref (ei->context);
4185 g_hash_table_insert (eo->map_if_name_to_ei,
4186 (gpointer) ei->interface_name,
4188 g_hash_table_insert (connection->priv->map_id_to_ei,
4189 GUINT_TO_POINTER (ei->id),
4195 CONNECTION_UNLOCK (connection);
4201 * g_dbus_connection_unregister_object:
4202 * @connection: A #GDBusConnection.
4203 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4205 * Unregisters an object.
4207 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4212 g_dbus_connection_unregister_object (GDBusConnection *connection,
4213 guint registration_id)
4215 ExportedInterface *ei;
4219 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4223 CONNECTION_LOCK (connection);
4225 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4226 GUINT_TO_POINTER (registration_id));
4232 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4233 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4234 /* unregister object path if we have no more exported interfaces */
4235 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4236 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4242 CONNECTION_UNLOCK (connection);
4247 /* ---------------------------------------------------------------------------------------------------- */
4250 * g_dbus_connection_emit_signal:
4251 * @connection: A #GDBusConnection.
4252 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4253 * @object_path: Path of remote object.
4254 * @interface_name: D-Bus interface to emit a signal on.
4255 * @signal_name: The name of the signal to emit.
4256 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4257 * @error: Return location for error or %NULL.
4261 * If the parameters GVariant is floating, it is consumed.
4263 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4265 * Returns: %TRUE unless @error is set.
4270 g_dbus_connection_emit_signal (GDBusConnection *connection,
4271 const gchar *destination_bus_name,
4272 const gchar *object_path,
4273 const gchar *interface_name,
4274 const gchar *signal_name,
4275 GVariant *parameters,
4278 GDBusMessage *message;
4284 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4285 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4286 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4287 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4288 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4289 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4291 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4293 _g_dbus_debug_print_lock ();
4294 g_print ("========================================================================\n"
4295 "GDBus-debug:Emission:\n"
4296 " >>>> SIGNAL EMISSION %s.%s()\n"
4298 " destination %s\n",
4299 interface_name, signal_name,
4301 destination_bus_name != NULL ? destination_bus_name : "(none)");
4302 _g_dbus_debug_print_unlock ();
4305 message = g_dbus_message_new_signal (object_path,
4309 if (destination_bus_name != NULL)
4310 g_dbus_message_set_header (message,
4311 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4312 g_variant_new_string (destination_bus_name));
4314 if (parameters != NULL)
4315 g_dbus_message_set_body (message, parameters);
4317 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4318 g_object_unref (message);
4324 add_call_flags (GDBusMessage *message,
4325 GDBusCallFlags flags)
4327 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4328 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4332 decode_method_reply (GDBusMessage *reply,
4333 const gchar *method_name,
4334 const GVariantType *reply_type,
4340 switch (g_dbus_message_get_message_type (reply))
4342 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4343 result = g_dbus_message_get_body (reply);
4346 result = g_variant_new ("()");
4347 g_variant_ref_sink (result);
4351 g_variant_ref (result);
4354 if (!g_variant_is_of_type (result, reply_type))
4356 gchar *type_string = g_variant_type_dup_string (reply_type);
4360 G_IO_ERROR_INVALID_ARGUMENT,
4361 _("Method `%s' returned type `%s', but expected `%s'"),
4362 method_name, g_variant_get_type_string (result), type_string);
4364 g_variant_unref (result);
4365 g_free (type_string);
4370 case G_DBUS_MESSAGE_TYPE_ERROR:
4371 g_dbus_message_to_gerror (reply, error);
4375 g_assert_not_reached ();
4385 GSimpleAsyncResult *simple;
4386 GVariantType *reply_type;
4387 gchar *method_name; /* for error message */
4392 g_dbus_connection_call_done (GObject *source,
4393 GAsyncResult *result,
4396 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4397 CallState *state = user_data;
4399 GDBusMessage *reply;
4403 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4407 if (G_UNLIKELY (_g_dbus_debug_call ()))
4409 _g_dbus_debug_print_lock ();
4410 g_print ("========================================================================\n"
4411 "GDBus-debug:Call:\n"
4412 " >>>> ASYNC COMPLETE %s() (serial %d)\n"
4418 g_print ("SUCCESS\n");
4422 g_print ("FAILED: %s\n",
4425 _g_dbus_debug_print_unlock ();
4431 value = decode_method_reply (reply, state->method_name,
4432 state->reply_type, &error);
4433 g_object_unref (reply);
4440 g_simple_async_result_set_from_error (state->simple, error);
4441 g_error_free (error);
4444 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4445 (GDestroyNotify) g_variant_unref);
4447 g_simple_async_result_complete (state->simple);
4448 g_variant_type_free (state->reply_type);
4449 g_object_unref (state->simple);
4450 g_free (state->method_name);
4452 g_slice_free (CallState, state);
4456 * g_dbus_connection_call:
4457 * @connection: A #GDBusConnection.
4458 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4459 * @object_path: Path of remote object.
4460 * @interface_name: D-Bus interface to invoke method on.
4461 * @method_name: The name of the method to invoke.
4462 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4463 * @reply_type: The expected type of the reply, or %NULL.
4464 * @flags: Flags from the #GDBusCallFlags enumeration.
4465 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4466 * @cancellable: A #GCancellable or %NULL.
4467 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4468 * care about the result of the method invocation.
4469 * @user_data: The data to pass to @callback.
4471 * Asynchronously invokes the @method_name method on the
4472 * @interface_name D-Bus interface on the remote object at
4473 * @object_path owned by @bus_name.
4475 * If @connection is closed then the operation will fail with
4476 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4477 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4478 * not compatible with the D-Bus protocol, the operation fails with
4479 * %G_IO_ERROR_INVALID_ARGUMENT.
4481 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4482 * error will be raised if it does not match. Said another way, if you give a @reply_type
4483 * then any non-%NULL return value will be of this type.
4485 * If the @parameters #GVariant is floating, it is consumed. This allows
4486 * convenient 'inline' use of g_variant_new(), e.g.:
4488 * g_dbus_connection_call (connection,
4489 * "org.freedesktop.StringThings",
4490 * "/org/freedesktop/StringThings",
4491 * "org.freedesktop.StringThings",
4493 * g_variant_new ("(ss)",
4497 * G_DBUS_CALL_FLAGS_NONE,
4500 * (GAsyncReadyCallback) two_strings_done,
4504 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4505 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4506 * of the thread you are calling this method from. You can then call
4507 * g_dbus_connection_call_finish() to get the result of the operation.
4508 * See g_dbus_connection_call_sync() for the synchronous version of this
4514 g_dbus_connection_call (GDBusConnection *connection,
4515 const gchar *bus_name,
4516 const gchar *object_path,
4517 const gchar *interface_name,
4518 const gchar *method_name,
4519 GVariant *parameters,
4520 const GVariantType *reply_type,
4521 GDBusCallFlags flags,
4523 GCancellable *cancellable,
4524 GAsyncReadyCallback callback,
4527 GDBusMessage *message;
4530 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4531 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4532 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4533 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4534 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4535 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4536 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4538 state = g_slice_new (CallState);
4539 state->simple = g_simple_async_result_new (G_OBJECT (connection),
4540 callback, user_data,
4541 g_dbus_connection_call);
4542 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4544 if (reply_type == NULL)
4545 reply_type = G_VARIANT_TYPE_ANY;
4547 state->reply_type = g_variant_type_copy (reply_type);
4549 message = g_dbus_message_new_method_call (bus_name,
4553 add_call_flags (message, flags);
4554 if (parameters != NULL)
4555 g_dbus_message_set_body (message, parameters);
4557 g_dbus_connection_send_message_with_reply (connection,
4562 g_dbus_connection_call_done,
4565 if (G_UNLIKELY (_g_dbus_debug_call ()))
4567 _g_dbus_debug_print_lock ();
4568 g_print ("========================================================================\n"
4569 "GDBus-debug:Call:\n"
4570 " >>>> ASYNC %s.%s()\n"
4572 " owned by name %s (serial %d)\n",
4576 bus_name != NULL ? bus_name : "(none)",
4578 _g_dbus_debug_print_unlock ();
4581 if (message != NULL)
4582 g_object_unref (message);
4586 * g_dbus_connection_call_finish:
4587 * @connection: A #GDBusConnection.
4588 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4589 * @error: Return location for error or %NULL.
4591 * Finishes an operation started with g_dbus_connection_call().
4593 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4594 * return values. Free with g_variant_unref().
4599 g_dbus_connection_call_finish (GDBusConnection *connection,
4603 GSimpleAsyncResult *simple;
4605 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4606 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
4607 g_dbus_connection_call), NULL);
4608 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4610 simple = G_SIMPLE_ASYNC_RESULT (res);
4612 if (g_simple_async_result_propagate_error (simple, error))
4615 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
4618 /* ---------------------------------------------------------------------------------------------------- */
4621 * g_dbus_connection_call_sync:
4622 * @connection: A #GDBusConnection.
4623 * @bus_name: A unique or well-known bus name.
4624 * @object_path: Path of remote object.
4625 * @interface_name: D-Bus interface to invoke method on.
4626 * @method_name: The name of the method to invoke.
4627 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4628 * @reply_type: The expected type of the reply, or %NULL.
4629 * @flags: Flags from the #GDBusCallFlags enumeration.
4630 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4631 * @cancellable: A #GCancellable or %NULL.
4632 * @error: Return location for error or %NULL.
4634 * Synchronously invokes the @method_name method on the
4635 * @interface_name D-Bus interface on the remote object at
4636 * @object_path owned by @bus_name.
4638 * If @connection is closed then the operation will fail with
4639 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4640 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4641 * contains a value not compatible with the D-Bus protocol, the operation
4642 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4644 * If @reply_type is non-%NULL then the reply will be checked for having
4645 * this type and an error will be raised if it does not match. Said
4646 * another way, if you give a @reply_type then any non-%NULL return
4647 * value will be of this type.
4649 * If the @parameters #GVariant is floating, it is consumed.
4650 * This allows convenient 'inline' use of g_variant_new(), e.g.:
4652 * g_dbus_connection_call_sync (connection,
4653 * "org.freedesktop.StringThings",
4654 * "/org/freedesktop/StringThings",
4655 * "org.freedesktop.StringThings",
4657 * g_variant_new ("(ss)",
4661 * G_DBUS_CALL_FLAGS_NONE,
4667 * The calling thread is blocked until a reply is received. See
4668 * g_dbus_connection_call() for the asynchronous version of
4671 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4672 * return values. Free with g_variant_unref().
4677 g_dbus_connection_call_sync (GDBusConnection *connection,
4678 const gchar *bus_name,
4679 const gchar *object_path,
4680 const gchar *interface_name,
4681 const gchar *method_name,
4682 GVariant *parameters,
4683 const GVariantType *reply_type,
4684 GDBusCallFlags flags,
4686 GCancellable *cancellable,
4689 GDBusMessage *message;
4690 GDBusMessage *reply;
4692 GError *local_error;
4698 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4699 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4700 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4701 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4702 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4703 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4704 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4706 if (reply_type == NULL)
4707 reply_type = G_VARIANT_TYPE_ANY;
4709 message = g_dbus_message_new_method_call (bus_name,
4713 add_call_flags (message, flags);
4714 if (parameters != NULL)
4715 g_dbus_message_set_body (message, parameters);
4717 if (G_UNLIKELY (_g_dbus_debug_call ()))
4719 _g_dbus_debug_print_lock ();
4720 g_print ("========================================================================\n"
4721 "GDBus-debug:Call:\n"
4722 " >>>> SYNC %s.%s()\n"
4724 " owned by name %s\n",
4728 bus_name != NULL ? bus_name : "(none)");
4729 _g_dbus_debug_print_unlock ();
4733 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4736 NULL, /* volatile guint32 *out_serial */
4740 if (G_UNLIKELY (_g_dbus_debug_call ()))
4742 _g_dbus_debug_print_lock ();
4743 g_print ("========================================================================\n"
4744 "GDBus-debug:Call:\n"
4745 " <<<< SYNC COMPLETE %s.%s()\n"
4751 g_print ("SUCCESS\n");
4755 g_print ("FAILED: %s\n",
4756 local_error->message);
4758 _g_dbus_debug_print_unlock ();
4764 *error = local_error;
4766 g_error_free (local_error);
4770 result = decode_method_reply (reply, method_name, reply_type, error);
4773 if (message != NULL)
4774 g_object_unref (message);
4776 g_object_unref (reply);
4781 /* ---------------------------------------------------------------------------------------------------- */
4783 struct ExportedSubtree
4787 GDBusConnection *connection;
4788 const GDBusSubtreeVTable *vtable;
4789 GDBusSubtreeFlags flags;
4791 GMainContext *context;
4793 GDestroyNotify user_data_free_func;
4797 exported_subtree_free (ExportedSubtree *es)
4799 if (es->user_data_free_func != NULL)
4800 /* TODO: push to thread-default mainloop */
4801 es->user_data_free_func (es->user_data);
4803 if (es->context != NULL)
4804 g_main_context_unref (es->context);
4806 g_free (es->object_path);
4810 /* called without lock held */
4812 handle_subtree_introspect (GDBusConnection *connection,
4813 ExportedSubtree *es,
4814 GDBusMessage *message)
4818 GDBusMessage *reply;
4821 const gchar *sender;
4822 const gchar *requested_object_path;
4823 const gchar *requested_node;
4824 GPtrArray *interfaces;
4826 gchar **subnode_paths;
4830 requested_object_path = g_dbus_message_get_path (message);
4831 sender = g_dbus_message_get_sender (message);
4832 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4834 s = g_string_new (NULL);
4835 introspect_append_header (s);
4837 /* Strictly we don't need the children in dynamic mode, but we avoid the
4838 * conditionals to preserve code clarity
4840 children = es->vtable->enumerate (es->connection,
4847 requested_node = strrchr (requested_object_path, '/') + 1;
4849 /* Assert existence of object if we are not dynamic */
4850 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4851 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4856 requested_node = "/";
4859 interfaces = es->vtable->introspect (es->connection,
4864 if (interfaces != NULL)
4866 if (interfaces->len > 0)
4868 /* we're in business */
4869 introspect_append_standard_interfaces (s);
4871 for (n = 0; n < interfaces->len; n++)
4873 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4874 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4877 g_ptr_array_unref (interfaces);
4880 /* then include <node> entries from the Subtree for the root */
4883 for (n = 0; children != NULL && children[n] != NULL; n++)
4884 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4887 /* finally include nodes registered below us */
4888 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4889 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4890 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4891 g_strfreev (subnode_paths);
4893 g_string_append (s, "</node>\n");
4895 reply = g_dbus_message_new_method_reply (message);
4896 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4897 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4898 g_object_unref (reply);
4903 g_string_free (s, TRUE);
4904 g_strfreev (children);
4908 /* called without lock held */
4910 handle_subtree_method_invocation (GDBusConnection *connection,
4911 ExportedSubtree *es,
4912 GDBusMessage *message)
4915 const gchar *sender;
4916 const gchar *interface_name;
4917 const gchar *member;
4918 const gchar *signature;
4919 const gchar *requested_object_path;
4920 const gchar *requested_node;
4923 const GDBusInterfaceInfo *interface_info;
4924 const GDBusInterfaceVTable *interface_vtable;
4925 gpointer interface_user_data;
4927 GPtrArray *interfaces;
4928 gboolean is_property_get;
4929 gboolean is_property_set;
4930 gboolean is_property_get_all;
4935 requested_object_path = g_dbus_message_get_path (message);
4936 sender = g_dbus_message_get_sender (message);
4937 interface_name = g_dbus_message_get_interface (message);
4938 member = g_dbus_message_get_member (message);
4939 signature = g_dbus_message_get_signature (message);
4940 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4942 is_property_get = FALSE;
4943 is_property_set = FALSE;
4944 is_property_get_all = FALSE;
4945 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4947 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4948 is_property_get = TRUE;
4949 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4950 is_property_set = TRUE;
4951 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4952 is_property_get_all = TRUE;
4955 children = es->vtable->enumerate (es->connection,
4962 requested_node = strrchr (requested_object_path, '/') + 1;
4964 /* If not dynamic, skip if requested node is not part of children */
4965 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4966 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4971 requested_node = "/";
4974 /* get introspection data for the node */
4975 interfaces = es->vtable->introspect (es->connection,
4977 requested_object_path,
4980 g_assert (interfaces != NULL);
4981 interface_info = NULL;
4982 for (n = 0; n < interfaces->len; n++)
4984 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4985 if (g_strcmp0 (id_n->name, interface_name) == 0)
4986 interface_info = id_n;
4989 /* dispatch the call if the user wants to handle it */
4990 if (interface_info != NULL)
4992 /* figure out where to dispatch the method call */
4993 interface_user_data = NULL;
4994 interface_vtable = es->vtable->dispatch (es->connection,
4999 &interface_user_data,
5001 if (interface_vtable == NULL)
5004 CONNECTION_LOCK (connection);
5005 handled = validate_and_maybe_schedule_method_call (es->connection,
5012 interface_user_data);
5013 CONNECTION_UNLOCK (connection);
5015 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5016 else if (is_property_get || is_property_set || is_property_get_all)
5018 if (is_property_get)
5019 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5020 else if (is_property_set)
5021 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5022 else if (is_property_get_all)
5023 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5025 g_assert_not_reached ();
5027 /* see if the object supports this interface at all */
5028 for (n = 0; n < interfaces->len; n++)
5030 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
5031 if (g_strcmp0 (id_n->name, interface_name) == 0)
5032 interface_info = id_n;
5035 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5036 * claims it won't support the interface
5038 if (interface_info == NULL)
5040 GDBusMessage *reply;
5041 reply = g_dbus_message_new_method_error (message,
5042 "org.freedesktop.DBus.Error.InvalidArgs",
5043 _("No such interface `%s'"),
5045 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
5046 g_object_unref (reply);
5051 /* figure out where to dispatch the property get/set/getall calls */
5052 interface_user_data = NULL;
5053 interface_vtable = es->vtable->dispatch (es->connection,
5058 &interface_user_data,
5060 if (interface_vtable == NULL)
5063 if (is_property_get || is_property_set)
5065 CONNECTION_LOCK (connection);
5066 handled = validate_and_maybe_schedule_property_getset (es->connection,
5074 interface_user_data);
5075 CONNECTION_UNLOCK (connection);
5077 else if (is_property_get_all)
5079 CONNECTION_LOCK (connection);
5080 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5087 interface_user_data);
5088 CONNECTION_UNLOCK (connection);
5093 if (interfaces != NULL)
5094 g_ptr_array_unref (interfaces);
5095 g_strfreev (children);
5101 GDBusMessage *message;
5102 ExportedSubtree *es;
5103 } SubtreeDeferredData;
5106 subtree_deferred_data_free (SubtreeDeferredData *data)
5108 g_object_unref (data->message);
5112 /* called without lock held in the thread where the caller registered the subtree */
5114 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5116 SubtreeDeferredData *data = _data;
5121 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5122 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5123 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5124 handled = handle_subtree_introspect (data->es->connection,
5128 handled = handle_subtree_method_invocation (data->es->connection,
5134 CONNECTION_LOCK (data->es->connection);
5135 handled = handle_generic_unlocked (data->es->connection, data->message);
5136 CONNECTION_UNLOCK (data->es->connection);
5139 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5142 GDBusMessage *reply;
5143 reply = g_dbus_message_new_method_error (data->message,
5144 "org.freedesktop.DBus.Error.UnknownMethod",
5145 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5146 g_dbus_message_get_member (data->message),
5147 g_dbus_message_get_interface (data->message),
5148 g_dbus_message_get_signature (data->message));
5149 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
5150 g_object_unref (reply);
5156 /* called in message handler thread with lock held */
5158 subtree_message_func (GDBusConnection *connection,
5159 ExportedSubtree *es,
5160 GDBusMessage *message)
5162 GSource *idle_source;
5163 SubtreeDeferredData *data;
5165 data = g_new0 (SubtreeDeferredData, 1);
5166 data->message = g_object_ref (message);
5169 /* defer this call to an idle handler in the right thread */
5170 idle_source = g_idle_source_new ();
5171 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5172 g_source_set_callback (idle_source,
5173 process_subtree_vtable_message_in_idle_cb,
5175 (GDestroyNotify) subtree_deferred_data_free);
5176 g_source_attach (idle_source, es->context);
5177 g_source_unref (idle_source);
5179 /* since we own the entire subtree, handlers for objects not in the subtree have been
5180 * tried already by libdbus-1 - so we just need to ensure that we're always going
5181 * to reply to the message
5187 * g_dbus_connection_register_subtree:
5188 * @connection: A #GDBusConnection.
5189 * @object_path: The object path to register the subtree at.
5190 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5191 * @flags: Flags used to fine tune the behavior of the subtree.
5192 * @user_data: Data to pass to functions in @vtable.
5193 * @user_data_free_func: Function to call when the subtree is unregistered.
5194 * @error: Return location for error or %NULL.
5196 * Registers a whole subtree of <quote>dynamic</quote> objects.
5198 * The @enumerate and @introspection functions in @vtable are used to
5199 * convey, to remote callers, what nodes exist in the subtree rooted
5202 * When handling remote calls into any node in the subtree, first the
5203 * @enumerate function is used to check if the node exists. If the node exists
5204 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5205 * the @introspection function is used to check if the node supports the
5206 * requested method. If so, the @dispatch function is used to determine
5207 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5208 * #gpointer will be used to call into the interface vtable for processing
5211 * All calls into user-provided code will be invoked in the <link
5212 * linkend="g-main-context-push-thread-default">thread-default main
5213 * loop</link> of the thread you are calling this method from.
5215 * If an existing subtree is already registered at @object_path or
5216 * then @error is set to #G_IO_ERROR_EXISTS.
5218 * Note that it is valid to register regular objects (using
5219 * g_dbus_connection_register_object()) in a subtree registered with
5220 * g_dbus_connection_register_subtree() - if so, the subtree handler
5221 * is tried as the last resort. One way to think about a subtree
5222 * handler is to consider it a <quote>fallback handler</quote>
5223 * for object paths not registered via g_dbus_connection_register_object()
5224 * or other bindings.
5226 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5228 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5229 * that can be used with g_dbus_connection_unregister_subtree() .
5234 g_dbus_connection_register_subtree (GDBusConnection *connection,
5235 const gchar *object_path,
5236 const GDBusSubtreeVTable *vtable,
5237 GDBusSubtreeFlags flags,
5239 GDestroyNotify user_data_free_func,
5243 ExportedSubtree *es;
5245 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5246 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5247 g_return_val_if_fail (vtable != NULL, 0);
5248 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5252 CONNECTION_LOCK (connection);
5254 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5260 _("A subtree is already exported for %s"),
5265 es = g_new0 (ExportedSubtree, 1);
5266 es->object_path = g_strdup (object_path);
5267 es->connection = connection;
5269 es->vtable = vtable;
5271 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5272 es->user_data = user_data;
5273 es->user_data_free_func = user_data_free_func;
5274 es->context = g_main_context_get_thread_default ();
5275 if (es->context != NULL)
5276 g_main_context_ref (es->context);
5278 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
5279 g_hash_table_insert (connection->priv->map_id_to_es,
5280 GUINT_TO_POINTER (es->id),
5286 CONNECTION_UNLOCK (connection);
5291 /* ---------------------------------------------------------------------------------------------------- */
5294 * g_dbus_connection_unregister_subtree:
5295 * @connection: A #GDBusConnection.
5296 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5298 * Unregisters a subtree.
5300 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5305 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5306 guint registration_id)
5308 ExportedSubtree *es;
5311 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5315 CONNECTION_LOCK (connection);
5317 es = g_hash_table_lookup (connection->priv->map_id_to_es,
5318 GUINT_TO_POINTER (registration_id));
5322 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
5323 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
5328 CONNECTION_UNLOCK (connection);
5333 /* ---------------------------------------------------------------------------------------------------- */
5335 /* must be called with lock held */
5337 handle_generic_ping_unlocked (GDBusConnection *connection,
5338 const gchar *object_path,
5339 GDBusMessage *message)
5341 GDBusMessage *reply;
5342 reply = g_dbus_message_new_method_reply (message);
5343 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5344 g_object_unref (reply);
5347 /* must be called with lock held */
5349 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5350 const gchar *object_path,
5351 GDBusMessage *message)
5353 GDBusMessage *reply;
5356 if (connection->priv->machine_id == NULL)
5360 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
5361 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
5362 &connection->priv->machine_id,
5366 reply = g_dbus_message_new_method_error (message,
5367 "org.freedesktop.DBus.Error.Failed",
5368 _("Unable to load /var/lib/dbus/machine-id: %s"),
5370 g_error_free (error);
5374 g_strstrip (connection->priv->machine_id);
5375 /* TODO: validate value */
5381 reply = g_dbus_message_new_method_reply (message);
5382 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5384 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5385 g_object_unref (reply);
5388 /* must be called with lock held */
5390 handle_generic_introspect_unlocked (GDBusConnection *connection,
5391 const gchar *object_path,
5392 GDBusMessage *message)
5397 GDBusMessage *reply;
5399 /* first the header */
5400 s = g_string_new (NULL);
5401 introspect_append_header (s);
5403 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5404 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5405 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5406 g_strfreev (registered);
5407 g_string_append (s, "</node>\n");
5409 reply = g_dbus_message_new_method_reply (message);
5410 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5411 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5412 g_object_unref (reply);
5413 g_string_free (s, TRUE);
5416 /* must be called with lock held */
5418 handle_generic_unlocked (GDBusConnection *connection,
5419 GDBusMessage *message)
5422 const gchar *interface_name;
5423 const gchar *member;
5424 const gchar *signature;
5427 CONNECTION_ENSURE_LOCK (connection);
5431 interface_name = g_dbus_message_get_interface (message);
5432 member = g_dbus_message_get_member (message);
5433 signature = g_dbus_message_get_signature (message);
5434 path = g_dbus_message_get_path (message);
5436 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5437 g_strcmp0 (member, "Introspect") == 0 &&
5438 g_strcmp0 (signature, "") == 0)
5440 handle_generic_introspect_unlocked (connection, path, message);
5443 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5444 g_strcmp0 (member, "Ping") == 0 &&
5445 g_strcmp0 (signature, "") == 0)
5447 handle_generic_ping_unlocked (connection, path, message);
5450 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5451 g_strcmp0 (member, "GetMachineId") == 0 &&
5452 g_strcmp0 (signature, "") == 0)
5454 handle_generic_get_machine_id_unlocked (connection, path, message);
5461 /* ---------------------------------------------------------------------------------------------------- */
5463 /* called in message handler thread with lock held */
5465 distribute_method_call (GDBusConnection *connection,
5466 GDBusMessage *message)
5468 GDBusMessage *reply;
5470 ExportedSubtree *es;
5471 const gchar *object_path;
5472 const gchar *interface_name;
5473 const gchar *member;
5474 const gchar *signature;
5476 gchar *subtree_path;
5479 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5481 interface_name = g_dbus_message_get_interface (message);
5482 member = g_dbus_message_get_member (message);
5483 signature = g_dbus_message_get_signature (message);
5484 path = g_dbus_message_get_path (message);
5485 subtree_path = g_strdup (path);
5486 needle = strrchr (subtree_path, '/');
5487 if (needle != NULL && needle != subtree_path)
5493 g_free (subtree_path);
5494 subtree_path = NULL;
5498 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
5500 _g_dbus_debug_print_lock ();
5501 g_print ("========================================================================\n"
5502 "GDBus-debug:Incoming:\n"
5503 " >>>> METHOD INVOCATION %s.%s()\n"
5505 " invoked by name %s\n",
5506 interface_name, member,
5508 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)");
5509 _g_dbus_debug_print_unlock ();
5513 g_debug ("interface = `%s'", interface_name);
5514 g_debug ("member = `%s'", member);
5515 g_debug ("signature = `%s'", signature);
5516 g_debug ("path = `%s'", path);
5517 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5520 object_path = g_dbus_message_get_path (message);
5521 g_assert (object_path != NULL);
5523 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5526 if (obj_message_func (connection, eo, message))
5530 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5533 if (subtree_message_func (connection, es, message))
5537 if (subtree_path != NULL)
5539 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5542 if (subtree_message_func (connection, es, message))
5547 if (handle_generic_unlocked (connection, message))
5550 /* if we end up here, the message has not been not handled - so return an error saying this */
5551 reply = g_dbus_message_new_method_error (message,
5552 "org.freedesktop.DBus.Error.UnknownMethod",
5553 _("No such interface `%s' on object at path %s"),
5556 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5557 g_object_unref (reply);
5560 g_free (subtree_path);
5563 /* ---------------------------------------------------------------------------------------------------- */
5565 static GDBusConnection **
5566 message_bus_get_singleton (GBusType bus_type,
5569 GDBusConnection **ret;
5570 const gchar *starter_bus;
5576 case G_BUS_TYPE_SESSION:
5577 ret = &the_session_bus;
5580 case G_BUS_TYPE_SYSTEM:
5581 ret = &the_system_bus;
5584 case G_BUS_TYPE_STARTER:
5585 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5586 if (g_strcmp0 (starter_bus, "session") == 0)
5588 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5591 else if (g_strcmp0 (starter_bus, "system") == 0)
5593 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5598 if (starter_bus != NULL)
5602 G_IO_ERROR_INVALID_ARGUMENT,
5603 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5604 " - unknown value `%s'"),
5609 g_set_error_literal (error,
5611 G_IO_ERROR_INVALID_ARGUMENT,
5612 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5613 "variable is not set"));
5619 g_assert_not_reached ();
5627 static GDBusConnection *
5628 get_uninitialized_connection (GBusType bus_type,
5629 GCancellable *cancellable,
5632 GDBusConnection **singleton;
5633 GDBusConnection *ret;
5637 G_LOCK (message_bus_lock);
5638 singleton = message_bus_get_singleton (bus_type, error);
5639 if (singleton == NULL)
5642 if (*singleton == NULL)
5645 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5646 if (address == NULL)
5648 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5650 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5651 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5652 "exit-on-close", TRUE,
5658 ret = g_object_ref (*singleton);
5661 g_assert (ret != NULL);
5664 G_UNLOCK (message_bus_lock);
5670 * @bus_type: A #GBusType.
5671 * @cancellable: A #GCancellable or %NULL.
5672 * @error: Return location for error or %NULL.
5674 * Synchronously connects to the message bus specified by @bus_type.
5675 * Note that the returned object may shared with other callers,
5676 * e.g. if two separate parts of a process calls this function with
5677 * the same @bus_type, they will share the same object.
5679 * This is a synchronous failable function. See g_bus_get() and
5680 * g_bus_get_finish() for the asynchronous version.
5682 * The returned object is a singleton, that is, shared with other
5683 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5684 * event that you need a private message bus connection, use
5685 * g_dbus_address_get_for_bus_sync() and
5686 * g_dbus_connection_new_for_address().
5688 * Note that the returned #GDBusConnection object will (usually) have
5689 * the #GDBusConnection:exit-on-close property set to %TRUE.
5691 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5696 g_bus_get_sync (GBusType bus_type,
5697 GCancellable *cancellable,
5700 GDBusConnection *connection;
5702 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5704 connection = get_uninitialized_connection (bus_type, cancellable, error);
5705 if (connection == NULL)
5708 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5710 g_object_unref (connection);
5719 bus_get_async_initable_cb (GObject *source_object,
5723 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5727 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5731 g_assert (error != NULL);
5732 g_simple_async_result_set_from_error (simple, error);
5733 g_error_free (error);
5734 g_object_unref (source_object);
5738 g_simple_async_result_set_op_res_gpointer (simple,
5742 g_simple_async_result_complete_in_idle (simple);
5743 g_object_unref (simple);
5748 * @bus_type: A #GBusType.
5749 * @cancellable: A #GCancellable or %NULL.
5750 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5751 * @user_data: The data to pass to @callback.
5753 * Asynchronously connects to the message bus specified by @bus_type.
5755 * When the operation is finished, @callback will be invoked. You can
5756 * then call g_bus_get_finish() to get the result of the operation.
5758 * This is a asynchronous failable function. See g_bus_get_sync() for
5759 * the synchronous version.
5764 g_bus_get (GBusType bus_type,
5765 GCancellable *cancellable,
5766 GAsyncReadyCallback callback,
5769 GDBusConnection *connection;
5770 GSimpleAsyncResult *simple;
5773 simple = g_simple_async_result_new (NULL,
5779 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5780 if (connection == NULL)
5782 g_assert (error != NULL);
5783 g_simple_async_result_set_from_error (simple, error);
5784 g_error_free (error);
5785 g_simple_async_result_complete_in_idle (simple);
5786 g_object_unref (simple);
5790 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5793 bus_get_async_initable_cb,
5800 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5801 * @error: Return location for error or %NULL.
5803 * Finishes an operation started with g_bus_get().
5805 * The returned object is a singleton, that is, shared with other
5806 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5807 * event that you need a private message bus connection, use
5808 * g_dbus_address_get_for_bus() and
5809 * g_dbus_connection_new_for_address().
5811 * Note that the returned #GDBusConnection object will (usually) have
5812 * the #GDBusConnection:exit-on-close property set to %TRUE.
5814 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5819 g_bus_get_finish (GAsyncResult *res,
5822 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5824 GDBusConnection *ret;
5826 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5828 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5832 if (g_simple_async_result_propagate_error (simple, error))
5835 object = g_simple_async_result_get_op_res_gpointer (simple);
5836 g_assert (object != NULL);
5837 ret = g_object_ref (G_DBUS_CONNECTION (object));
5843 /* ---------------------------------------------------------------------------------------------------- */
5845 #define __G_DBUS_CONNECTION_C__
5846 #include "gioaliasdef.c"