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=messages, 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 /* collect subscribers that match on sender */
3013 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array, sender);
3014 if (signal_data_array != NULL)
3015 schedule_callbacks (connection, signal_data_array, message, sender);
3018 /* collect subscribers not matching on sender */
3019 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_unique_name_to_signal_data_array, "");
3020 if (signal_data_array != NULL)
3021 schedule_callbacks (connection, signal_data_array, message, sender);
3024 /* ---------------------------------------------------------------------------------------------------- */
3026 /* only called from finalize(), removes all subscriptions */
3028 purge_all_signal_subscriptions (GDBusConnection *connection)
3030 GHashTableIter iter;
3033 GArray *subscribers;
3036 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3037 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
3038 while (g_hash_table_iter_next (&iter, &key, NULL))
3040 guint subscription_id = GPOINTER_TO_UINT (key);
3041 g_array_append_val (ids, subscription_id);
3044 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3045 for (n = 0; n < ids->len; n++)
3047 guint subscription_id = g_array_index (ids, guint, n);
3048 unsubscribe_id_internal (connection,
3052 g_array_free (ids, TRUE);
3054 /* call GDestroyNotify without lock held */
3055 for (n = 0; n < subscribers->len; n++)
3057 SignalSubscriber *subscriber;
3058 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3059 if (subscriber->user_data_free_func != NULL)
3060 subscriber->user_data_free_func (subscriber->user_data);
3061 if (subscriber->context != NULL)
3062 g_main_context_unref (subscriber->context);
3065 g_array_free (subscribers, TRUE);
3068 /* ---------------------------------------------------------------------------------------------------- */
3070 struct ExportedObject
3073 GDBusConnection *connection;
3075 /* maps gchar* -> ExportedInterface* */
3076 GHashTable *map_if_name_to_ei;
3079 /* only called with lock held */
3081 exported_object_free (ExportedObject *eo)
3083 g_free (eo->object_path);
3084 g_hash_table_unref (eo->map_if_name_to_ei);
3093 gchar *interface_name;
3094 const GDBusInterfaceVTable *vtable;
3095 const GDBusInterfaceInfo *interface_info;
3097 GMainContext *context;
3099 GDestroyNotify user_data_free_func;
3100 } ExportedInterface;
3102 /* called with lock held */
3104 exported_interface_free (ExportedInterface *ei)
3106 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3108 if (ei->user_data_free_func != NULL)
3109 /* TODO: push to thread-default mainloop */
3110 ei->user_data_free_func (ei->user_data);
3112 if (ei->context != NULL)
3113 g_main_context_unref (ei->context);
3115 g_free (ei->interface_name);
3119 /* ---------------------------------------------------------------------------------------------------- */
3121 /* Convenience function to check if @registration_id (if not zero) or
3122 * @subtree_registration_id (if not zero) has been unregistered. If
3123 * so, returns %TRUE.
3125 * Caller must *not* hold lock.
3128 has_object_been_unregistered (GDBusConnection *connection,
3129 guint registration_id,
3130 guint subtree_registration_id)
3134 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3138 CONNECTION_LOCK (connection);
3139 if (registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_ei,
3140 GUINT_TO_POINTER (registration_id)) == NULL)
3144 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->priv->map_id_to_es,
3145 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3149 CONNECTION_UNLOCK (connection);
3154 /* ---------------------------------------------------------------------------------------------------- */
3158 GDBusConnection *connection;
3159 GDBusMessage *message;
3161 const gchar *property_name;
3162 const GDBusInterfaceVTable *vtable;
3163 const GDBusInterfaceInfo *interface_info;
3164 const GDBusPropertyInfo *property_info;
3165 guint registration_id;
3166 guint subtree_registration_id;
3170 property_data_free (PropertyData *data)
3172 g_object_unref (data->connection);
3173 g_object_unref (data->message);
3177 /* called in thread where object was registered - no locks held */
3179 invoke_get_property_in_idle_cb (gpointer _data)
3181 PropertyData *data = _data;
3184 GDBusMessage *reply;
3186 if (has_object_been_unregistered (data->connection,
3187 data->registration_id,
3188 data->subtree_registration_id))
3190 reply = g_dbus_message_new_method_error (data->message,
3191 "org.freedesktop.DBus.Error.UnknownMethod",
3192 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3193 g_dbus_message_get_path (data->message));
3194 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3195 g_object_unref (reply);
3200 value = data->vtable->get_property (data->connection,
3201 g_dbus_message_get_sender (data->message),
3202 g_dbus_message_get_path (data->message),
3203 data->interface_info->name,
3204 data->property_name,
3211 g_assert_no_error (error);
3213 g_variant_ref_sink (value);
3214 reply = g_dbus_message_new_method_reply (data->message);
3215 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3216 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3217 g_variant_unref (value);
3218 g_object_unref (reply);
3222 gchar *dbus_error_name;
3223 g_assert (error != NULL);
3224 dbus_error_name = g_dbus_error_encode_gerror (error);
3225 reply = g_dbus_message_new_method_error_literal (data->message,
3228 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3229 g_free (dbus_error_name);
3230 g_error_free (error);
3231 g_object_unref (reply);
3238 /* called in thread where object was registered - no locks held */
3240 invoke_set_property_in_idle_cb (gpointer _data)
3242 PropertyData *data = _data;
3244 GDBusMessage *reply;
3250 g_variant_get (g_dbus_message_get_body (data->message),
3256 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3257 * of the given value is wrong
3259 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3261 reply = g_dbus_message_new_method_error (data->message,
3262 "org.freedesktop.DBus.Error.InvalidArgs",
3263 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3264 data->property_info->name,
3265 data->property_info->signature,
3266 g_variant_get_type_string (value));
3270 if (!data->vtable->set_property (data->connection,
3271 g_dbus_message_get_sender (data->message),
3272 g_dbus_message_get_path (data->message),
3273 data->interface_info->name,
3274 data->property_name,
3279 gchar *dbus_error_name;
3280 g_assert (error != NULL);
3281 dbus_error_name = g_dbus_error_encode_gerror (error);
3282 reply = g_dbus_message_new_method_error_literal (data->message,
3285 g_free (dbus_error_name);
3286 g_error_free (error);
3290 reply = g_dbus_message_new_method_reply (data->message);
3294 g_assert (reply != NULL);
3295 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3296 g_object_unref (reply);
3301 /* called with lock held */
3303 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3304 GDBusMessage *message,
3305 guint registration_id,
3306 guint subtree_registration_id,
3308 const GDBusInterfaceInfo *interface_info,
3309 const GDBusInterfaceVTable *vtable,
3310 GMainContext *main_context,
3314 const char *interface_name;
3315 const char *property_name;
3316 const GDBusPropertyInfo *property_info;
3317 GSource *idle_source;
3318 PropertyData *property_data;
3319 GDBusMessage *reply;
3324 g_variant_get (g_dbus_message_get_body (message),
3329 g_variant_get (g_dbus_message_get_body (message),
3338 if (vtable == NULL || vtable->get_property == NULL)
3343 if (vtable == NULL || vtable->set_property == NULL)
3347 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3349 property_info = NULL;
3351 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3352 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3353 if (property_info == NULL)
3355 reply = g_dbus_message_new_method_error (message,
3356 "org.freedesktop.DBus.Error.InvalidArgs",
3357 _("No such property `%s'"),
3359 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3360 g_object_unref (reply);
3365 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3367 reply = g_dbus_message_new_method_error (message,
3368 "org.freedesktop.DBus.Error.InvalidArgs",
3369 _("Property `%s' is not readable"),
3371 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3372 g_object_unref (reply);
3376 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3378 reply = g_dbus_message_new_method_error (message,
3379 "org.freedesktop.DBus.Error.InvalidArgs",
3380 _("Property `%s' is not writable"),
3382 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3383 g_object_unref (reply);
3388 /* ok, got the property info - call user code in an idle handler */
3389 property_data = g_new0 (PropertyData, 1);
3390 property_data->connection = g_object_ref (connection);
3391 property_data->message = g_object_ref (message);
3392 property_data->user_data = user_data;
3393 property_data->property_name = property_name;
3394 property_data->vtable = vtable;
3395 property_data->interface_info = interface_info;
3396 property_data->property_info = property_info;
3397 property_data->registration_id = registration_id;
3398 property_data->subtree_registration_id = subtree_registration_id;
3400 idle_source = g_idle_source_new ();
3401 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3402 g_source_set_callback (idle_source,
3403 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3405 (GDestroyNotify) property_data_free);
3406 g_source_attach (idle_source, main_context);
3407 g_source_unref (idle_source);
3415 /* called with lock held */
3417 handle_getset_property (GDBusConnection *connection,
3419 GDBusMessage *message,
3422 ExportedInterface *ei;
3424 const char *interface_name;
3425 const char *property_name;
3430 g_variant_get (g_dbus_message_get_body (message),
3435 g_variant_get (g_dbus_message_get_body (message),
3441 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3442 * no such interface registered
3444 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3447 GDBusMessage *reply;
3448 reply = g_dbus_message_new_method_error (message,
3449 "org.freedesktop.DBus.Error.InvalidArgs",
3450 _("No such interface `%s'"),
3452 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3453 g_object_unref (reply);
3458 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3471 /* ---------------------------------------------------------------------------------------------------- */
3475 GDBusConnection *connection;
3476 GDBusMessage *message;
3478 const GDBusInterfaceVTable *vtable;
3479 const GDBusInterfaceInfo *interface_info;
3480 guint registration_id;
3481 guint subtree_registration_id;
3482 } PropertyGetAllData;
3485 property_get_all_data_free (PropertyData *data)
3487 g_object_unref (data->connection);
3488 g_object_unref (data->message);
3492 /* called in thread where object was registered - no locks held */
3494 invoke_get_all_properties_in_idle_cb (gpointer _data)
3496 PropertyGetAllData *data = _data;
3497 GVariantBuilder builder;
3499 GDBusMessage *reply;
3502 if (has_object_been_unregistered (data->connection,
3503 data->registration_id,
3504 data->subtree_registration_id))
3506 reply = g_dbus_message_new_method_error (data->message,
3507 "org.freedesktop.DBus.Error.UnknownMethod",
3508 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3509 g_dbus_message_get_path (data->message));
3510 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3511 g_object_unref (reply);
3517 /* TODO: Right now we never fail this call - we just omit values if
3518 * a get_property() call is failing.
3520 * We could fail the whole call if just a single get_property() call
3521 * returns an error. We need clarification in the D-Bus spec about this.
3523 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
3524 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
3525 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3527 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3530 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3533 value = data->vtable->get_property (data->connection,
3534 g_dbus_message_get_sender (data->message),
3535 g_dbus_message_get_path (data->message),
3536 data->interface_info->name,
3537 property_info->name,
3544 g_variant_builder_add (&builder,
3546 property_info->name,
3549 g_variant_builder_close (&builder);
3551 reply = g_dbus_message_new_method_reply (data->message);
3552 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
3553 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3554 g_object_unref (reply);
3560 /* called with lock held */
3562 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3563 GDBusMessage *message,
3564 guint registration_id,
3565 guint subtree_registration_id,
3566 const GDBusInterfaceInfo *interface_info,
3567 const GDBusInterfaceVTable *vtable,
3568 GMainContext *main_context,
3572 const char *interface_name;
3573 GSource *idle_source;
3574 PropertyGetAllData *property_get_all_data;
3578 g_variant_get (g_dbus_message_get_body (message),
3582 if (vtable == NULL || vtable->get_property == NULL)
3585 /* ok, got the property info - call user in an idle handler */
3586 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3587 property_get_all_data->connection = g_object_ref (connection);
3588 property_get_all_data->message = g_object_ref (message);
3589 property_get_all_data->user_data = user_data;
3590 property_get_all_data->vtable = vtable;
3591 property_get_all_data->interface_info = interface_info;
3592 property_get_all_data->registration_id = registration_id;
3593 property_get_all_data->subtree_registration_id = subtree_registration_id;
3595 idle_source = g_idle_source_new ();
3596 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3597 g_source_set_callback (idle_source,
3598 invoke_get_all_properties_in_idle_cb,
3599 property_get_all_data,
3600 (GDestroyNotify) property_get_all_data_free);
3601 g_source_attach (idle_source, main_context);
3602 g_source_unref (idle_source);
3610 /* called with lock held */
3612 handle_get_all_properties (GDBusConnection *connection,
3614 GDBusMessage *message)
3616 ExportedInterface *ei;
3618 const char *interface_name;
3622 g_variant_get (g_dbus_message_get_body (message),
3626 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3627 * no such interface registered
3629 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3632 GDBusMessage *reply;
3633 reply = g_dbus_message_new_method_error (message,
3634 "org.freedesktop.DBus.Error.InvalidArgs",
3635 _("No such interface"),
3637 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3638 g_object_unref (reply);
3643 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3655 /* ---------------------------------------------------------------------------------------------------- */
3657 static const gchar introspect_header[] =
3658 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3659 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3660 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3663 static const gchar introspect_tail[] =
3666 static const gchar introspect_standard_interfaces[] =
3667 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3668 " <method name=\"Get\">\n"
3669 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3670 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3671 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3673 " <method name=\"GetAll\">\n"
3674 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3675 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3677 " <method name=\"Set\">\n"
3678 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3679 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3680 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3682 " <signal name=\"PropertiesChanged\">\n"
3683 " <arg type=\"s\" name=\"interface_name\"/>\n"
3684 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3685 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3688 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3689 " <method name=\"Introspect\">\n"
3690 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3693 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3694 " <method name=\"Ping\"/>\n"
3695 " <method name=\"GetMachineId\">\n"
3696 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3701 introspect_append_header (GString *s)
3703 g_string_append (s, introspect_header);
3707 introspect_append_standard_interfaces (GString *s)
3709 g_string_append (s, introspect_standard_interfaces);
3713 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3715 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
3721 begin = object_path + path_len;
3722 end = strchr (begin, '/');
3724 s = g_strndup (begin, end - begin);
3726 s = g_strdup (begin);
3728 if (g_hash_table_lookup (set, s) == NULL)
3729 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3735 /* TODO: we want a nicer public interface for this */
3737 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3742 GHashTableIter hash_iter;
3743 const gchar *object_path;
3749 CONNECTION_ENSURE_LOCK (connection);
3751 path_len = strlen (path);
3755 set = g_hash_table_new (g_str_hash, g_str_equal);
3757 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3758 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3759 maybe_add_path (path, path_len, object_path, set);
3761 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3762 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3763 maybe_add_path (path, path_len, object_path, set);
3765 p = g_ptr_array_new ();
3766 keys = g_hash_table_get_keys (set);
3767 for (l = keys; l != NULL; l = l->next)
3768 g_ptr_array_add (p, l->data);
3769 g_hash_table_unref (set);
3772 g_ptr_array_add (p, NULL);
3773 ret = (gchar **) g_ptr_array_free (p, FALSE);
3778 g_dbus_connection_list_registered (GDBusConnection *connection,
3782 CONNECTION_LOCK (connection);
3783 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3784 CONNECTION_UNLOCK (connection);
3788 /* called in message handler thread with lock held */
3790 handle_introspect (GDBusConnection *connection,
3792 GDBusMessage *message)
3796 GDBusMessage *reply;
3797 GHashTableIter hash_iter;
3798 ExportedInterface *ei;
3801 /* first the header with the standard interfaces */
3802 s = g_string_sized_new (sizeof (introspect_header) +
3803 sizeof (introspect_standard_interfaces) +
3804 sizeof (introspect_tail));
3805 introspect_append_header (s);
3806 introspect_append_standard_interfaces (s);
3808 /* then include the registered interfaces */
3809 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3810 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3811 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
3813 /* finally include nodes registered below us */
3814 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3815 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3816 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3817 g_strfreev (registered);
3818 g_string_append (s, introspect_tail);
3820 reply = g_dbus_message_new_method_reply (message);
3821 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3822 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3823 g_object_unref (reply);
3824 g_string_free (s, TRUE);
3829 /* called in thread where object was registered - no locks held */
3831 call_in_idle_cb (gpointer user_data)
3833 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3834 GDBusInterfaceVTable *vtable;
3835 guint registration_id;
3836 guint subtree_registration_id;
3838 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3839 g_assert (vtable != NULL && vtable->method_call != NULL);
3841 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
3842 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
3844 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
3846 subtree_registration_id))
3848 GDBusMessage *reply;
3849 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
3850 "org.freedesktop.DBus.Error.UnknownMethod",
3851 _("No such interface `%s' on object at path %s"),
3852 g_dbus_method_invocation_get_interface_name (invocation),
3853 g_dbus_method_invocation_get_object_path (invocation));
3854 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, NULL, NULL);
3855 g_object_unref (reply);
3859 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3860 g_dbus_method_invocation_get_sender (invocation),
3861 g_dbus_method_invocation_get_object_path (invocation),
3862 g_dbus_method_invocation_get_interface_name (invocation),
3863 g_dbus_method_invocation_get_method_name (invocation),
3864 g_dbus_method_invocation_get_parameters (invocation),
3865 g_object_ref (invocation),
3866 g_dbus_method_invocation_get_user_data (invocation));
3872 /* called in message handler thread with lock held */
3874 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3875 GDBusMessage *message,
3876 guint registration_id,
3877 guint subtree_registration_id,
3878 const GDBusInterfaceInfo *interface_info,
3879 const GDBusInterfaceVTable *vtable,
3880 GMainContext *main_context,
3883 GDBusMethodInvocation *invocation;
3884 const GDBusMethodInfo *method_info;
3885 GDBusMessage *reply;
3886 GVariant *parameters;
3887 GSource *idle_source;
3889 GVariantType *in_type;
3893 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3894 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
3896 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3897 * error to the caller
3899 if (method_info == NULL)
3901 reply = g_dbus_message_new_method_error (message,
3902 "org.freedesktop.DBus.Error.UnknownMethod",
3903 _("No such method `%s'"),
3904 g_dbus_message_get_member (message));
3905 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3906 g_object_unref (reply);
3911 parameters = g_dbus_message_get_body (message);
3912 if (parameters == NULL)
3914 parameters = g_variant_new ("()");
3915 g_variant_ref_sink (parameters);
3919 g_variant_ref (parameters);
3922 /* Check that the incoming args are of the right type - if they are not, return
3923 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3925 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
3926 if (!g_variant_is_of_type (parameters, in_type))
3930 type_string = g_variant_type_dup_string (in_type);
3932 reply = g_dbus_message_new_method_error (message,
3933 "org.freedesktop.DBus.Error.InvalidArgs",
3934 _("Type of message, `%s', does not match expected type `%s'"),
3935 g_variant_get_type_string (parameters),
3937 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3938 g_variant_type_free (in_type);
3939 g_variant_unref (parameters);
3940 g_object_unref (reply);
3941 g_free (type_string);
3945 g_variant_type_free (in_type);
3947 /* schedule the call in idle */
3948 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3949 g_dbus_message_get_path (message),
3950 g_dbus_message_get_interface (message),
3951 g_dbus_message_get_member (message),
3957 g_variant_unref (parameters);
3959 /* TODO: would be nicer with a real MethodData like we already
3960 * have PropertyData and PropertyGetAllData... */
3961 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
3962 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
3963 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
3965 idle_source = g_idle_source_new ();
3966 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3967 g_source_set_callback (idle_source,
3971 g_source_attach (idle_source, main_context);
3972 g_source_unref (idle_source);
3980 /* ---------------------------------------------------------------------------------------------------- */
3982 /* called in message handler thread with lock held */
3984 obj_message_func (GDBusConnection *connection,
3986 GDBusMessage *message)
3988 const gchar *interface_name;
3989 const gchar *member;
3990 const gchar *signature;
3995 interface_name = g_dbus_message_get_interface (message);
3996 member = g_dbus_message_get_member (message);
3997 signature = g_dbus_message_get_signature (message);
3999 /* see if we have an interface for handling this call */
4000 if (interface_name != NULL)
4002 ExportedInterface *ei;
4003 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4006 /* we do - invoke the handler in idle in the right thread */
4008 /* handle no vtable or handler being present */
4009 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4012 handled = validate_and_maybe_schedule_method_call (connection,
4024 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4025 g_strcmp0 (member, "Introspect") == 0 &&
4026 g_strcmp0 (signature, "") == 0)
4028 handled = handle_introspect (connection, eo, message);
4031 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4032 g_strcmp0 (member, "Get") == 0 &&
4033 g_strcmp0 (signature, "ss") == 0)
4035 handled = handle_getset_property (connection, eo, message, TRUE);
4038 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4039 g_strcmp0 (member, "Set") == 0 &&
4040 g_strcmp0 (signature, "ssv") == 0)
4042 handled = handle_getset_property (connection, eo, message, FALSE);
4045 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4046 g_strcmp0 (member, "GetAll") == 0 &&
4047 g_strcmp0 (signature, "s") == 0)
4049 handled = handle_get_all_properties (connection, eo, message);
4058 * g_dbus_connection_register_object:
4059 * @connection: A #GDBusConnection.
4060 * @object_path: The object path to register at.
4061 * @interface_info: Introspection data for the interface.
4062 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4063 * @user_data: Data to pass to functions in @vtable.
4064 * @user_data_free_func: Function to call when the object path is unregistered.
4065 * @error: Return location for error or %NULL.
4067 * Registers callbacks for exported objects at @object_path with the
4068 * D-Bus interface that is described in @interface_info.
4070 * Calls to functions in @vtable (and @user_data_free_func) will
4071 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4072 * loop</link> of the thread you are calling this method from.
4074 * Note that all #GVariant values passed to functions in @vtable will match
4075 * the signature given in @interface_info - if a remote caller passes
4076 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4077 * is returned to the remote caller.
4079 * Additionally, if the remote caller attempts to invoke methods or
4080 * access properties not mentioned in @interface_info the
4081 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4082 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4083 * are returned to the caller.
4085 * It is considered a programming error if the
4086 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4087 * #GVariant of incorrect type.
4089 * If an existing callback is already registered at @object_path and
4090 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4092 * Note that @vtable is not copied, so the struct you pass must exist until
4093 * the path is unregistered. One possibility is to free @vtable at the
4094 * same time as @user_data when @user_data_free_func is called.
4096 * GDBus automatically implements the standard D-Bus interfaces
4097 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4098 * and org.freedesktop.Peer, so you don't have to implement those for
4099 * the objects you export. You <emphasis>can</emphasis> implement
4100 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4101 * and setting of properties asynchronously.
4103 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4105 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4106 * that can be used with g_dbus_connection_unregister_object() .
4111 g_dbus_connection_register_object (GDBusConnection *connection,
4112 const gchar *object_path,
4113 const GDBusInterfaceInfo *interface_info,
4114 const GDBusInterfaceVTable *vtable,
4116 GDestroyNotify user_data_free_func,
4120 ExportedInterface *ei;
4123 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4124 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4125 g_return_val_if_fail (interface_info != NULL, 0);
4126 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4127 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4131 CONNECTION_LOCK (connection);
4133 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
4136 eo = g_new0 (ExportedObject, 1);
4137 eo->object_path = g_strdup (object_path);
4138 eo->connection = connection;
4139 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4142 (GDestroyNotify) exported_interface_free);
4143 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
4146 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4152 _("An object is already exported for the interface %s at %s"),
4153 interface_info->name,
4158 ei = g_new0 (ExportedInterface, 1);
4159 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4161 ei->user_data = user_data;
4162 ei->user_data_free_func = user_data_free_func;
4163 ei->vtable = vtable;
4164 ei->interface_info = g_dbus_interface_info_ref ((GDBusInterfaceInfo *) interface_info);
4165 ei->interface_name = g_strdup (interface_info->name);
4166 ei->context = g_main_context_get_thread_default ();
4167 if (ei->context != NULL)
4168 g_main_context_ref (ei->context);
4170 g_hash_table_insert (eo->map_if_name_to_ei,
4171 (gpointer) ei->interface_name,
4173 g_hash_table_insert (connection->priv->map_id_to_ei,
4174 GUINT_TO_POINTER (ei->id),
4180 CONNECTION_UNLOCK (connection);
4186 * g_dbus_connection_unregister_object:
4187 * @connection: A #GDBusConnection.
4188 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4190 * Unregisters an object.
4192 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4197 g_dbus_connection_unregister_object (GDBusConnection *connection,
4198 guint registration_id)
4200 ExportedInterface *ei;
4204 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4208 CONNECTION_LOCK (connection);
4210 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4211 GUINT_TO_POINTER (registration_id));
4217 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4218 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4219 /* unregister object path if we have no more exported interfaces */
4220 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4221 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4227 CONNECTION_UNLOCK (connection);
4232 /* ---------------------------------------------------------------------------------------------------- */
4235 * g_dbus_connection_emit_signal:
4236 * @connection: A #GDBusConnection.
4237 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4238 * @object_path: Path of remote object.
4239 * @interface_name: D-Bus interface to emit a signal on.
4240 * @signal_name: The name of the signal to emit.
4241 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4242 * @error: Return location for error or %NULL.
4246 * If the parameters GVariant is floating, it is consumed.
4248 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4250 * Returns: %TRUE unless @error is set.
4255 g_dbus_connection_emit_signal (GDBusConnection *connection,
4256 const gchar *destination_bus_name,
4257 const gchar *object_path,
4258 const gchar *interface_name,
4259 const gchar *signal_name,
4260 GVariant *parameters,
4263 GDBusMessage *message;
4269 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4270 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4271 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4272 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4273 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4274 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4276 message = g_dbus_message_new_signal (object_path,
4280 if (destination_bus_name != NULL)
4281 g_dbus_message_set_header (message,
4282 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4283 g_variant_new_string (destination_bus_name));
4285 if (parameters != NULL)
4286 g_dbus_message_set_body (message, parameters);
4288 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4289 g_object_unref (message);
4295 add_call_flags (GDBusMessage *message,
4296 GDBusCallFlags flags)
4298 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4299 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4303 decode_method_reply (GDBusMessage *reply,
4304 const gchar *method_name,
4305 const GVariantType *reply_type,
4311 switch (g_dbus_message_get_message_type (reply))
4313 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4314 result = g_dbus_message_get_body (reply);
4317 result = g_variant_new ("()");
4318 g_variant_ref_sink (result);
4322 g_variant_ref (result);
4325 if (!g_variant_is_of_type (result, reply_type))
4327 gchar *type_string = g_variant_type_dup_string (reply_type);
4331 G_IO_ERROR_INVALID_ARGUMENT,
4332 _("Method `%s' returned type `%s', but expected `%s'"),
4333 method_name, g_variant_get_type_string (result), type_string);
4335 g_variant_unref (result);
4336 g_free (type_string);
4341 case G_DBUS_MESSAGE_TYPE_ERROR:
4342 g_dbus_message_to_gerror (reply, error);
4346 g_assert_not_reached ();
4356 GSimpleAsyncResult *simple;
4357 GVariantType *reply_type;
4358 gchar *method_name; /* for error message */
4362 g_dbus_connection_call_done (GObject *source,
4363 GAsyncResult *result,
4366 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4367 CallState *state = user_data;
4368 GError *error = NULL;
4369 GDBusMessage *reply;
4372 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4377 value = decode_method_reply (reply, state->method_name,
4378 state->reply_type, &error);
4379 g_object_unref (reply);
4386 g_simple_async_result_set_from_error (state->simple, error);
4387 g_error_free (error);
4390 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4391 (GDestroyNotify) g_variant_unref);
4393 g_simple_async_result_complete (state->simple);
4394 g_variant_type_free (state->reply_type);
4395 g_object_unref (state->simple);
4396 g_free (state->method_name);
4398 g_slice_free (CallState, state);
4402 * g_dbus_connection_call:
4403 * @connection: A #GDBusConnection.
4404 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4405 * @object_path: Path of remote object.
4406 * @interface_name: D-Bus interface to invoke method on.
4407 * @method_name: The name of the method to invoke.
4408 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4409 * @reply_type: The expected type of the reply, or %NULL.
4410 * @flags: Flags from the #GDBusCallFlags enumeration.
4411 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4412 * @cancellable: A #GCancellable or %NULL.
4413 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4414 * care about the result of the method invocation.
4415 * @user_data: The data to pass to @callback.
4417 * Asynchronously invokes the @method_name method on the
4418 * @interface_name D-Bus interface on the remote object at
4419 * @object_path owned by @bus_name.
4421 * If @connection is closed then the operation will fail with
4422 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4423 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4424 * not compatible with the D-Bus protocol, the operation fails with
4425 * %G_IO_ERROR_INVALID_ARGUMENT.
4427 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
4428 * error will be raised if it does not match. Said another way, if you give a @reply_type
4429 * then any non-%NULL return value will be of this type.
4431 * If the @parameters #GVariant is floating, it is consumed. This allows
4432 * convenient 'inline' use of g_variant_new(), e.g.:
4434 * g_dbus_connection_call (connection,
4435 * "org.freedesktop.StringThings",
4436 * "/org/freedesktop/StringThings",
4437 * "org.freedesktop.StringThings",
4439 * g_variant_new ("(ss)",
4443 * G_DBUS_CALL_FLAGS_NONE,
4446 * (GAsyncReadyCallback) two_strings_done,
4450 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4451 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4452 * of the thread you are calling this method from. You can then call
4453 * g_dbus_connection_call_finish() to get the result of the operation.
4454 * See g_dbus_connection_call_sync() for the synchronous version of this
4460 g_dbus_connection_call (GDBusConnection *connection,
4461 const gchar *bus_name,
4462 const gchar *object_path,
4463 const gchar *interface_name,
4464 const gchar *method_name,
4465 GVariant *parameters,
4466 const GVariantType *reply_type,
4467 GDBusCallFlags flags,
4469 GCancellable *cancellable,
4470 GAsyncReadyCallback callback,
4473 GDBusMessage *message;
4476 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4477 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4478 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4479 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4480 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4481 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4482 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4484 state = g_slice_new (CallState);
4485 state->simple = g_simple_async_result_new (G_OBJECT (connection),
4486 callback, user_data,
4487 g_dbus_connection_call);
4488 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
4490 if (reply_type == NULL)
4491 reply_type = G_VARIANT_TYPE_ANY;
4493 state->reply_type = g_variant_type_copy (reply_type);
4495 message = g_dbus_message_new_method_call (bus_name,
4499 add_call_flags (message, flags);
4500 if (parameters != NULL)
4501 g_dbus_message_set_body (message, parameters);
4503 g_dbus_connection_send_message_with_reply (connection,
4506 NULL, /* volatile guint32 *out_serial */
4508 g_dbus_connection_call_done,
4511 if (message != NULL)
4512 g_object_unref (message);
4516 * g_dbus_connection_call_finish:
4517 * @connection: A #GDBusConnection.
4518 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4519 * @error: Return location for error or %NULL.
4521 * Finishes an operation started with g_dbus_connection_call().
4523 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4524 * return values. Free with g_variant_unref().
4529 g_dbus_connection_call_finish (GDBusConnection *connection,
4533 GSimpleAsyncResult *simple;
4535 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4536 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
4537 g_dbus_connection_call), NULL);
4538 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4540 simple = G_SIMPLE_ASYNC_RESULT (res);
4542 if (g_simple_async_result_propagate_error (simple, error))
4545 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
4548 /* ---------------------------------------------------------------------------------------------------- */
4551 * g_dbus_connection_call_sync:
4552 * @connection: A #GDBusConnection.
4553 * @bus_name: A unique or well-known bus name.
4554 * @object_path: Path of remote object.
4555 * @interface_name: D-Bus interface to invoke method on.
4556 * @method_name: The name of the method to invoke.
4557 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4558 * @reply_type: The expected type of the reply, or %NULL.
4559 * @flags: Flags from the #GDBusCallFlags enumeration.
4560 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4561 * @cancellable: A #GCancellable or %NULL.
4562 * @error: Return location for error or %NULL.
4564 * Synchronously invokes the @method_name method on the
4565 * @interface_name D-Bus interface on the remote object at
4566 * @object_path owned by @bus_name.
4568 * If @connection is closed then the operation will fail with
4569 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4570 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4571 * contains a value not compatible with the D-Bus protocol, the operation
4572 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4574 * If @reply_type is non-%NULL then the reply will be checked for having
4575 * this type and an error will be raised if it does not match. Said
4576 * another way, if you give a @reply_type then any non-%NULL return
4577 * value will be of this type.
4579 * If the @parameters #GVariant is floating, it is consumed.
4580 * This allows convenient 'inline' use of g_variant_new(), e.g.:
4582 * g_dbus_connection_call_sync (connection,
4583 * "org.freedesktop.StringThings",
4584 * "/org/freedesktop/StringThings",
4585 * "org.freedesktop.StringThings",
4587 * g_variant_new ("(ss)",
4591 * G_DBUS_CALL_FLAGS_NONE,
4597 * The calling thread is blocked until a reply is received. See
4598 * g_dbus_connection_call() for the asynchronous version of
4601 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4602 * return values. Free with g_variant_unref().
4607 g_dbus_connection_call_sync (GDBusConnection *connection,
4608 const gchar *bus_name,
4609 const gchar *object_path,
4610 const gchar *interface_name,
4611 const gchar *method_name,
4612 GVariant *parameters,
4613 const GVariantType *reply_type,
4614 GDBusCallFlags flags,
4616 GCancellable *cancellable,
4619 GDBusMessage *message;
4620 GDBusMessage *reply;
4627 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4628 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4629 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4630 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4631 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4632 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4633 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4635 if (reply_type == NULL)
4636 reply_type = G_VARIANT_TYPE_ANY;
4638 message = g_dbus_message_new_method_call (bus_name,
4642 add_call_flags (message, flags);
4643 if (parameters != NULL)
4644 g_dbus_message_set_body (message, parameters);
4646 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4649 NULL, /* volatile guint32 *out_serial */
4656 result = decode_method_reply (reply, method_name, reply_type, error);
4659 if (message != NULL)
4660 g_object_unref (message);
4662 g_object_unref (reply);
4667 /* ---------------------------------------------------------------------------------------------------- */
4669 struct ExportedSubtree
4673 GDBusConnection *connection;
4674 const GDBusSubtreeVTable *vtable;
4675 GDBusSubtreeFlags flags;
4677 GMainContext *context;
4679 GDestroyNotify user_data_free_func;
4683 exported_subtree_free (ExportedSubtree *es)
4685 if (es->user_data_free_func != NULL)
4686 /* TODO: push to thread-default mainloop */
4687 es->user_data_free_func (es->user_data);
4689 if (es->context != NULL)
4690 g_main_context_unref (es->context);
4692 g_free (es->object_path);
4696 /* called without lock held */
4698 handle_subtree_introspect (GDBusConnection *connection,
4699 ExportedSubtree *es,
4700 GDBusMessage *message)
4704 GDBusMessage *reply;
4707 const gchar *sender;
4708 const gchar *requested_object_path;
4709 const gchar *requested_node;
4710 GPtrArray *interfaces;
4712 gchar **subnode_paths;
4716 requested_object_path = g_dbus_message_get_path (message);
4717 sender = g_dbus_message_get_sender (message);
4718 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4720 s = g_string_new (NULL);
4721 introspect_append_header (s);
4723 /* Strictly we don't need the children in dynamic mode, but we avoid the
4724 * conditionals to preserve code clarity
4726 children = es->vtable->enumerate (es->connection,
4733 requested_node = strrchr (requested_object_path, '/') + 1;
4735 /* Assert existence of object if we are not dynamic */
4736 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4737 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4742 requested_node = "/";
4745 interfaces = es->vtable->introspect (es->connection,
4750 if (interfaces != NULL)
4752 if (interfaces->len > 0)
4754 /* we're in business */
4755 introspect_append_standard_interfaces (s);
4757 for (n = 0; n < interfaces->len; n++)
4759 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4760 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4763 g_ptr_array_unref (interfaces);
4766 /* then include <node> entries from the Subtree for the root */
4769 for (n = 0; children != NULL && children[n] != NULL; n++)
4770 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4773 /* finally include nodes registered below us */
4774 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4775 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4776 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4777 g_strfreev (subnode_paths);
4779 g_string_append (s, "</node>\n");
4781 reply = g_dbus_message_new_method_reply (message);
4782 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4783 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4784 g_object_unref (reply);
4789 g_string_free (s, TRUE);
4790 g_strfreev (children);
4794 /* called without lock held */
4796 handle_subtree_method_invocation (GDBusConnection *connection,
4797 ExportedSubtree *es,
4798 GDBusMessage *message)
4801 const gchar *sender;
4802 const gchar *interface_name;
4803 const gchar *member;
4804 const gchar *signature;
4805 const gchar *requested_object_path;
4806 const gchar *requested_node;
4809 const GDBusInterfaceInfo *interface_info;
4810 const GDBusInterfaceVTable *interface_vtable;
4811 gpointer interface_user_data;
4813 GPtrArray *interfaces;
4814 gboolean is_property_get;
4815 gboolean is_property_set;
4816 gboolean is_property_get_all;
4821 requested_object_path = g_dbus_message_get_path (message);
4822 sender = g_dbus_message_get_sender (message);
4823 interface_name = g_dbus_message_get_interface (message);
4824 member = g_dbus_message_get_member (message);
4825 signature = g_dbus_message_get_signature (message);
4826 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4828 is_property_get = FALSE;
4829 is_property_set = FALSE;
4830 is_property_get_all = FALSE;
4831 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4833 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4834 is_property_get = TRUE;
4835 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4836 is_property_set = TRUE;
4837 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4838 is_property_get_all = TRUE;
4841 children = es->vtable->enumerate (es->connection,
4848 requested_node = strrchr (requested_object_path, '/') + 1;
4850 /* If not dynamic, skip if requested node is not part of children */
4851 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4852 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4857 requested_node = "/";
4860 /* get introspection data for the node */
4861 interfaces = es->vtable->introspect (es->connection,
4863 requested_object_path,
4866 g_assert (interfaces != NULL);
4867 interface_info = NULL;
4868 for (n = 0; n < interfaces->len; n++)
4870 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4871 if (g_strcmp0 (id_n->name, interface_name) == 0)
4872 interface_info = id_n;
4875 /* dispatch the call if the user wants to handle it */
4876 if (interface_info != NULL)
4878 /* figure out where to dispatch the method call */
4879 interface_user_data = NULL;
4880 interface_vtable = es->vtable->dispatch (es->connection,
4885 &interface_user_data,
4887 if (interface_vtable == NULL)
4890 CONNECTION_LOCK (connection);
4891 handled = validate_and_maybe_schedule_method_call (es->connection,
4898 interface_user_data);
4899 CONNECTION_UNLOCK (connection);
4901 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4902 else if (is_property_get || is_property_set || is_property_get_all)
4904 if (is_property_get)
4905 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
4906 else if (is_property_set)
4907 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
4908 else if (is_property_get_all)
4909 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
4911 g_assert_not_reached ();
4913 /* see if the object supports this interface at all */
4914 for (n = 0; n < interfaces->len; n++)
4916 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4917 if (g_strcmp0 (id_n->name, interface_name) == 0)
4918 interface_info = id_n;
4921 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4922 * claims it won't support the interface
4924 if (interface_info == NULL)
4926 GDBusMessage *reply;
4927 reply = g_dbus_message_new_method_error (message,
4928 "org.freedesktop.DBus.Error.InvalidArgs",
4929 _("No such interface `%s'"),
4931 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4932 g_object_unref (reply);
4937 /* figure out where to dispatch the property get/set/getall calls */
4938 interface_user_data = NULL;
4939 interface_vtable = es->vtable->dispatch (es->connection,
4944 &interface_user_data,
4946 if (interface_vtable == NULL)
4949 if (is_property_get || is_property_set)
4951 CONNECTION_LOCK (connection);
4952 handled = validate_and_maybe_schedule_property_getset (es->connection,
4960 interface_user_data);
4961 CONNECTION_UNLOCK (connection);
4963 else if (is_property_get_all)
4965 CONNECTION_LOCK (connection);
4966 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4973 interface_user_data);
4974 CONNECTION_UNLOCK (connection);
4979 if (interfaces != NULL)
4980 g_ptr_array_unref (interfaces);
4981 g_strfreev (children);
4987 GDBusMessage *message;
4988 ExportedSubtree *es;
4989 } SubtreeDeferredData;
4992 subtree_deferred_data_free (SubtreeDeferredData *data)
4994 g_object_unref (data->message);
4998 /* called without lock held in the thread where the caller registered the subtree */
5000 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5002 SubtreeDeferredData *data = _data;
5007 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5008 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5009 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5010 handled = handle_subtree_introspect (data->es->connection,
5014 handled = handle_subtree_method_invocation (data->es->connection,
5020 CONNECTION_LOCK (data->es->connection);
5021 handled = handle_generic_unlocked (data->es->connection, data->message);
5022 CONNECTION_UNLOCK (data->es->connection);
5025 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5028 GDBusMessage *reply;
5029 reply = g_dbus_message_new_method_error (data->message,
5030 "org.freedesktop.DBus.Error.UnknownMethod",
5031 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5032 g_dbus_message_get_member (data->message),
5033 g_dbus_message_get_interface (data->message),
5034 g_dbus_message_get_signature (data->message));
5035 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
5036 g_object_unref (reply);
5042 /* called in message handler thread with lock held */
5044 subtree_message_func (GDBusConnection *connection,
5045 ExportedSubtree *es,
5046 GDBusMessage *message)
5048 GSource *idle_source;
5049 SubtreeDeferredData *data;
5051 data = g_new0 (SubtreeDeferredData, 1);
5052 data->message = g_object_ref (message);
5055 /* defer this call to an idle handler in the right thread */
5056 idle_source = g_idle_source_new ();
5057 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5058 g_source_set_callback (idle_source,
5059 process_subtree_vtable_message_in_idle_cb,
5061 (GDestroyNotify) subtree_deferred_data_free);
5062 g_source_attach (idle_source, es->context);
5063 g_source_unref (idle_source);
5065 /* since we own the entire subtree, handlers for objects not in the subtree have been
5066 * tried already by libdbus-1 - so we just need to ensure that we're always going
5067 * to reply to the message
5073 * g_dbus_connection_register_subtree:
5074 * @connection: A #GDBusConnection.
5075 * @object_path: The object path to register the subtree at.
5076 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5077 * @flags: Flags used to fine tune the behavior of the subtree.
5078 * @user_data: Data to pass to functions in @vtable.
5079 * @user_data_free_func: Function to call when the subtree is unregistered.
5080 * @error: Return location for error or %NULL.
5082 * Registers a whole subtree of <quote>dynamic</quote> objects.
5084 * The @enumerate and @introspection functions in @vtable are used to
5085 * convey, to remote callers, what nodes exist in the subtree rooted
5088 * When handling remote calls into any node in the subtree, first the
5089 * @enumerate function is used to check if the node exists. If the node exists
5090 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5091 * the @introspection function is used to check if the node supports the
5092 * requested method. If so, the @dispatch function is used to determine
5093 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5094 * #gpointer will be used to call into the interface vtable for processing
5097 * All calls into user-provided code will be invoked in the <link
5098 * linkend="g-main-context-push-thread-default">thread-default main
5099 * loop</link> of the thread you are calling this method from.
5101 * If an existing subtree is already registered at @object_path or
5102 * then @error is set to #G_IO_ERROR_EXISTS.
5104 * Note that it is valid to register regular objects (using
5105 * g_dbus_connection_register_object()) in a subtree registered with
5106 * g_dbus_connection_register_subtree() - if so, the subtree handler
5107 * is tried as the last resort. One way to think about a subtree
5108 * handler is to consider it a <quote>fallback handler</quote>
5109 * for object paths not registered via g_dbus_connection_register_object()
5110 * or other bindings.
5112 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5114 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5115 * that can be used with g_dbus_connection_unregister_subtree() .
5120 g_dbus_connection_register_subtree (GDBusConnection *connection,
5121 const gchar *object_path,
5122 const GDBusSubtreeVTable *vtable,
5123 GDBusSubtreeFlags flags,
5125 GDestroyNotify user_data_free_func,
5129 ExportedSubtree *es;
5131 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5132 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5133 g_return_val_if_fail (vtable != NULL, 0);
5134 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5138 CONNECTION_LOCK (connection);
5140 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5146 _("A subtree is already exported for %s"),
5151 es = g_new0 (ExportedSubtree, 1);
5152 es->object_path = g_strdup (object_path);
5153 es->connection = connection;
5155 es->vtable = vtable;
5157 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5158 es->user_data = user_data;
5159 es->user_data_free_func = user_data_free_func;
5160 es->context = g_main_context_get_thread_default ();
5161 if (es->context != NULL)
5162 g_main_context_ref (es->context);
5164 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
5165 g_hash_table_insert (connection->priv->map_id_to_es,
5166 GUINT_TO_POINTER (es->id),
5172 CONNECTION_UNLOCK (connection);
5177 /* ---------------------------------------------------------------------------------------------------- */
5180 * g_dbus_connection_unregister_subtree:
5181 * @connection: A #GDBusConnection.
5182 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5184 * Unregisters a subtree.
5186 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5191 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5192 guint registration_id)
5194 ExportedSubtree *es;
5197 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5201 CONNECTION_LOCK (connection);
5203 es = g_hash_table_lookup (connection->priv->map_id_to_es,
5204 GUINT_TO_POINTER (registration_id));
5208 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
5209 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
5214 CONNECTION_UNLOCK (connection);
5219 /* ---------------------------------------------------------------------------------------------------- */
5221 /* must be called with lock held */
5223 handle_generic_ping_unlocked (GDBusConnection *connection,
5224 const gchar *object_path,
5225 GDBusMessage *message)
5227 GDBusMessage *reply;
5228 reply = g_dbus_message_new_method_reply (message);
5229 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5230 g_object_unref (reply);
5233 /* must be called with lock held */
5235 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5236 const gchar *object_path,
5237 GDBusMessage *message)
5239 GDBusMessage *reply;
5242 if (connection->priv->machine_id == NULL)
5246 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
5247 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
5248 &connection->priv->machine_id,
5252 reply = g_dbus_message_new_method_error (message,
5253 "org.freedesktop.DBus.Error.Failed",
5254 _("Unable to load /var/lib/dbus/machine-id: %s"),
5256 g_error_free (error);
5260 g_strstrip (connection->priv->machine_id);
5261 /* TODO: validate value */
5267 reply = g_dbus_message_new_method_reply (message);
5268 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5270 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5271 g_object_unref (reply);
5274 /* must be called with lock held */
5276 handle_generic_introspect_unlocked (GDBusConnection *connection,
5277 const gchar *object_path,
5278 GDBusMessage *message)
5283 GDBusMessage *reply;
5285 /* first the header */
5286 s = g_string_new (NULL);
5287 introspect_append_header (s);
5289 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5290 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5291 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5292 g_strfreev (registered);
5293 g_string_append (s, "</node>\n");
5295 reply = g_dbus_message_new_method_reply (message);
5296 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5297 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5298 g_object_unref (reply);
5299 g_string_free (s, TRUE);
5302 /* must be called with lock held */
5304 handle_generic_unlocked (GDBusConnection *connection,
5305 GDBusMessage *message)
5308 const gchar *interface_name;
5309 const gchar *member;
5310 const gchar *signature;
5313 CONNECTION_ENSURE_LOCK (connection);
5317 interface_name = g_dbus_message_get_interface (message);
5318 member = g_dbus_message_get_member (message);
5319 signature = g_dbus_message_get_signature (message);
5320 path = g_dbus_message_get_path (message);
5322 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5323 g_strcmp0 (member, "Introspect") == 0 &&
5324 g_strcmp0 (signature, "") == 0)
5326 handle_generic_introspect_unlocked (connection, path, message);
5329 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5330 g_strcmp0 (member, "Ping") == 0 &&
5331 g_strcmp0 (signature, "") == 0)
5333 handle_generic_ping_unlocked (connection, path, message);
5336 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5337 g_strcmp0 (member, "GetMachineId") == 0 &&
5338 g_strcmp0 (signature, "") == 0)
5340 handle_generic_get_machine_id_unlocked (connection, path, message);
5347 /* ---------------------------------------------------------------------------------------------------- */
5349 /* called in message handler thread with lock held */
5351 distribute_method_call (GDBusConnection *connection,
5352 GDBusMessage *message)
5354 GDBusMessage *reply;
5356 ExportedSubtree *es;
5357 const gchar *object_path;
5358 const gchar *interface_name;
5359 const gchar *member;
5360 const gchar *signature;
5362 gchar *subtree_path;
5365 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5367 interface_name = g_dbus_message_get_interface (message);
5368 member = g_dbus_message_get_member (message);
5369 signature = g_dbus_message_get_signature (message);
5370 path = g_dbus_message_get_path (message);
5371 subtree_path = g_strdup (path);
5372 needle = strrchr (subtree_path, '/');
5373 if (needle != NULL && needle != subtree_path)
5379 g_free (subtree_path);
5380 subtree_path = NULL;
5384 g_debug ("interface = `%s'", interface_name);
5385 g_debug ("member = `%s'", member);
5386 g_debug ("signature = `%s'", signature);
5387 g_debug ("path = `%s'", path);
5388 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5391 object_path = g_dbus_message_get_path (message);
5392 g_assert (object_path != NULL);
5394 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5397 if (obj_message_func (connection, eo, message))
5401 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5404 if (subtree_message_func (connection, es, message))
5408 if (subtree_path != NULL)
5410 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5413 if (subtree_message_func (connection, es, message))
5418 if (handle_generic_unlocked (connection, message))
5421 /* if we end up here, the message has not been not handled - so return an error saying this */
5422 reply = g_dbus_message_new_method_error (message,
5423 "org.freedesktop.DBus.Error.UnknownMethod",
5424 _("No such interface `%s' on object at path %s"),
5427 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5428 g_object_unref (reply);
5431 g_free (subtree_path);
5434 /* ---------------------------------------------------------------------------------------------------- */
5436 static GDBusConnection **
5437 message_bus_get_singleton (GBusType bus_type,
5440 GDBusConnection **ret;
5441 const gchar *starter_bus;
5447 case G_BUS_TYPE_SESSION:
5448 ret = &the_session_bus;
5451 case G_BUS_TYPE_SYSTEM:
5452 ret = &the_system_bus;
5455 case G_BUS_TYPE_STARTER:
5456 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5457 if (g_strcmp0 (starter_bus, "session") == 0)
5459 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5462 else if (g_strcmp0 (starter_bus, "system") == 0)
5464 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5469 if (starter_bus != NULL)
5473 G_IO_ERROR_INVALID_ARGUMENT,
5474 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5475 " - unknown value `%s'"),
5480 g_set_error_literal (error,
5482 G_IO_ERROR_INVALID_ARGUMENT,
5483 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5484 "variable is not set"));
5490 g_assert_not_reached ();
5498 static GDBusConnection *
5499 get_uninitialized_connection (GBusType bus_type,
5500 GCancellable *cancellable,
5503 GDBusConnection **singleton;
5504 GDBusConnection *ret;
5508 G_LOCK (message_bus_lock);
5509 singleton = message_bus_get_singleton (bus_type, error);
5510 if (singleton == NULL)
5513 if (*singleton == NULL)
5516 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5517 if (address == NULL)
5519 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5521 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5522 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5523 "exit-on-close", TRUE,
5529 ret = g_object_ref (*singleton);
5532 g_assert (ret != NULL);
5535 G_UNLOCK (message_bus_lock);
5541 * @bus_type: A #GBusType.
5542 * @cancellable: A #GCancellable or %NULL.
5543 * @error: Return location for error or %NULL.
5545 * Synchronously connects to the message bus specified by @bus_type.
5546 * Note that the returned object may shared with other callers,
5547 * e.g. if two separate parts of a process calls this function with
5548 * the same @bus_type, they will share the same object.
5550 * This is a synchronous failable function. See g_bus_get() and
5551 * g_bus_get_finish() for the asynchronous version.
5553 * The returned object is a singleton, that is, shared with other
5554 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5555 * event that you need a private message bus connection, use
5556 * g_dbus_address_get_for_bus_sync() and
5557 * g_dbus_connection_new_for_address().
5559 * Note that the returned #GDBusConnection object will (usually) have
5560 * the #GDBusConnection:exit-on-close property set to %TRUE.
5562 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5567 g_bus_get_sync (GBusType bus_type,
5568 GCancellable *cancellable,
5571 GDBusConnection *connection;
5573 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5575 connection = get_uninitialized_connection (bus_type, cancellable, error);
5576 if (connection == NULL)
5579 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5581 g_object_unref (connection);
5590 bus_get_async_initable_cb (GObject *source_object,
5594 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5598 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5602 g_assert (error != NULL);
5603 g_simple_async_result_set_from_error (simple, error);
5604 g_error_free (error);
5605 g_object_unref (source_object);
5609 g_simple_async_result_set_op_res_gpointer (simple,
5613 g_simple_async_result_complete_in_idle (simple);
5614 g_object_unref (simple);
5619 * @bus_type: A #GBusType.
5620 * @cancellable: A #GCancellable or %NULL.
5621 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5622 * @user_data: The data to pass to @callback.
5624 * Asynchronously connects to the message bus specified by @bus_type.
5626 * When the operation is finished, @callback will be invoked. You can
5627 * then call g_bus_get_finish() to get the result of the operation.
5629 * This is a asynchronous failable function. See g_bus_get_sync() for
5630 * the synchronous version.
5635 g_bus_get (GBusType bus_type,
5636 GCancellable *cancellable,
5637 GAsyncReadyCallback callback,
5640 GDBusConnection *connection;
5641 GSimpleAsyncResult *simple;
5644 simple = g_simple_async_result_new (NULL,
5650 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5651 if (connection == NULL)
5653 g_assert (error != NULL);
5654 g_simple_async_result_set_from_error (simple, error);
5655 g_error_free (error);
5656 g_simple_async_result_complete_in_idle (simple);
5657 g_object_unref (simple);
5661 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5664 bus_get_async_initable_cb,
5671 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5672 * @error: Return location for error or %NULL.
5674 * Finishes an operation started with g_bus_get().
5676 * The returned object is a singleton, that is, shared with other
5677 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5678 * event that you need a private message bus connection, use
5679 * g_dbus_address_get_for_bus() and
5680 * g_dbus_connection_new_for_address().
5682 * Note that the returned #GDBusConnection object will (usually) have
5683 * the #GDBusConnection:exit-on-close property set to %TRUE.
5685 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5690 g_bus_get_finish (GAsyncResult *res,
5693 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5695 GDBusConnection *ret;
5697 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5699 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5703 if (g_simple_async_result_propagate_error (simple, error))
5706 object = g_simple_async_result_get_op_res_gpointer (simple);
5707 g_assert (object != NULL);
5708 ret = g_object_ref (G_DBUS_CONNECTION (object));
5714 /* ---------------------------------------------------------------------------------------------------- */
5716 #define __G_DBUS_CONNECTION_C__
5717 #include "gioaliasdef.c"