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)
105 #include "gdbusauth.h"
106 #include "gdbusutils.h"
107 #include "gdbusaddress.h"
108 #include "gdbusmessage.h"
109 #include "gdbusconnection.h"
110 #include "gdbuserror.h"
111 #include "gioenumtypes.h"
112 #include "gdbusintrospection.h"
113 #include "gdbusmethodinvocation.h"
114 #include "gdbusprivate.h"
115 #include "gdbusauthobserver.h"
116 #include "gio-marshal.h"
117 #include "ginitable.h"
118 #include "gasyncinitable.h"
119 #include "giostream.h"
120 #include "gasyncresult.h"
121 #include "gsimpleasyncresult.h"
124 #include <gio/gunixconnection.h>
125 #include <gio/gunixfdmessage.h>
127 #include <sys/types.h>
130 #include "glibintl.h"
131 #include "gioalias.h"
134 * SECTION:gdbusconnection
135 * @short_description: D-Bus Connections
136 * @include: gio/gio.h
138 * The #GDBusConnection type is used for D-Bus connections to remote
139 * peers such as a message buses. It is a low-level API that offers a
140 * lot of flexibility. For instance, it lets you establish a connection
141 * over any transport that can by represented as an #GIOStream.
143 * This class is rarely used directly in D-Bus clients. If you are writing
144 * an D-Bus client, it is often easier to use the g_bus_own_name(),
145 * g_bus_watch_name() or g_bus_watch_proxy() APIs.
147 * <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>
149 * <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>
151 * <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>
153 * <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>
156 /* ---------------------------------------------------------------------------------------------------- */
158 G_LOCK_DEFINE_STATIC (message_bus_lock);
160 static GDBusConnection *the_session_bus = NULL;
161 static GDBusConnection *the_system_bus = NULL;
163 /* ---------------------------------------------------------------------------------------------------- */
166 _g_strv_has_string (const gchar* const *haystack,
171 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
173 if (g_strcmp0 (haystack[n], needle) == 0)
179 /* ---------------------------------------------------------------------------------------------------- */
182 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
184 // TODO: for some reason this doesn't work on Windows
185 #define CONNECTION_ENSURE_LOCK(obj) do { \
186 if (G_UNLIKELY (g_mutex_trylock((obj)->priv->lock))) \
188 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
189 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
194 #define CONNECTION_LOCK(obj) do { \
195 g_mutex_lock ((obj)->priv->lock); \
198 #define CONNECTION_UNLOCK(obj) do { \
199 g_mutex_unlock ((obj)->priv->lock); \
202 struct _GDBusConnectionPrivate
204 /* ------------------------------------------------------------------------ */
205 /* -- General object state ------------------------------------------------ */
206 /* ------------------------------------------------------------------------ */
208 /* object-wide lock */
211 /* A lock used in the init() method of the GInitable interface - see comments
212 * in initable_init() for why a separate lock is needed
216 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
217 * someone calls org.freedesktop.DBus.GetMachineId()
221 /* The underlying stream used for communication */
224 /* The object used for authentication (if any) */
227 /* Set to TRUE if the connection has been closed */
230 /* Last serial used */
233 /* The object used to send/receive message */
236 /* If connected to a message bus, this contains the unique name assigned to
237 * us by the bus (e.g. ":1.42")
239 gchar *bus_unique_name;
241 /* The GUID returned by the other side if we authenticed as a client or
242 * the GUID to use if authenticating as a server
246 /* set to TRUE exactly when initable_init() has finished running */
247 gboolean is_initialized;
249 /* If the connection could not be established during initable_init(), this GError will set */
250 GError *initialization_error;
252 /* The result of g_main_context_get_thread_default() when the object
253 * was created (the GObject _init() function) - this is used for delivery
254 * of the :closed GObject signal.
256 GMainContext *main_context_at_construction;
258 /* construct properties */
260 GDBusConnectionFlags flags;
262 /* Map used for managing method replies */
263 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
265 /* Maps used for managing signal subscription */
266 GHashTable *map_rule_to_signal_data; /* gchar* -> SignalData */
267 GHashTable *map_id_to_signal_data; /* guint -> SignalData */
268 GHashTable *map_sender_to_signal_data_array; /* gchar* -> GPtrArray* of SignalData */
270 /* Maps used for managing exported objects and subtrees */
271 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
272 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
273 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
274 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
276 /* Structure used for message filters */
279 /* Whether to exit on close */
280 gboolean exit_on_close;
282 /* Capabilities negotiated during authentication */
283 GDBusCapabilityFlags capabilities;
285 GDBusAuthObserver *authentication_observer;
286 GCredentials *crendentials;
289 typedef struct ExportedObject ExportedObject;
290 static void exported_object_free (ExportedObject *eo);
292 typedef struct ExportedSubtree ExportedSubtree;
293 static void exported_subtree_free (ExportedSubtree *es);
311 PROP_CAPABILITY_FLAGS,
312 PROP_AUTHENTICATION_OBSERVER,
315 static void distribute_signals (GDBusConnection *connection,
316 GDBusMessage *message);
318 static void distribute_method_call (GDBusConnection *connection,
319 GDBusMessage *message);
321 static gboolean handle_generic_unlocked (GDBusConnection *connection,
322 GDBusMessage *message);
325 static void purge_all_signal_subscriptions (GDBusConnection *connection);
326 static void purge_all_filters (GDBusConnection *connection);
328 #define _G_ENSURE_LOCK(name) do { \
329 if (G_UNLIKELY (G_TRYLOCK(name))) \
331 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
332 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
336 static guint signals[LAST_SIGNAL] = { 0 };
338 static void initable_iface_init (GInitableIface *initable_iface);
339 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
341 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
342 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
343 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
347 g_dbus_connection_dispose (GObject *object)
349 GDBusConnection *connection = G_DBUS_CONNECTION (object);
351 G_LOCK (message_bus_lock);
352 //g_debug ("disposing %p", connection);
353 if (connection == the_session_bus)
355 the_session_bus = NULL;
357 else if (connection == the_system_bus)
359 the_system_bus = NULL;
361 if (connection->priv->worker != NULL)
363 _g_dbus_worker_stop (connection->priv->worker);
364 connection->priv->worker = NULL;
366 G_UNLOCK (message_bus_lock);
368 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
369 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
373 g_dbus_connection_finalize (GObject *object)
375 GDBusConnection *connection = G_DBUS_CONNECTION (object);
377 if (connection->priv->authentication_observer != NULL)
378 g_object_unref (connection->priv->authentication_observer);
380 if (connection->priv->auth != NULL)
381 g_object_unref (connection->priv->auth);
383 //g_debug ("finalizing %p", connection);
384 if (connection->priv->stream != NULL)
386 /* We don't really care if closing the stream succeeds or not */
387 g_io_stream_close_async (connection->priv->stream,
389 NULL, /* GCancellable */
390 NULL, /* GAsyncReadyCallback */
391 NULL); /* userdata */
392 g_object_unref (connection->priv->stream);
393 connection->priv->stream = NULL;
396 g_free (connection->priv->address);
398 g_free (connection->priv->guid);
399 g_free (connection->priv->bus_unique_name);
401 if (connection->priv->initialization_error != NULL)
402 g_error_free (connection->priv->initialization_error);
404 g_hash_table_unref (connection->priv->map_method_serial_to_send_message_data);
406 purge_all_signal_subscriptions (connection);
407 g_hash_table_unref (connection->priv->map_rule_to_signal_data);
408 g_hash_table_unref (connection->priv->map_id_to_signal_data);
409 g_hash_table_unref (connection->priv->map_sender_to_signal_data_array);
411 g_hash_table_unref (connection->priv->map_id_to_ei);
412 g_hash_table_unref (connection->priv->map_object_path_to_eo);
413 g_hash_table_unref (connection->priv->map_id_to_es);
414 g_hash_table_unref (connection->priv->map_object_path_to_es);
416 purge_all_filters (connection);
417 g_ptr_array_unref (connection->priv->filters);
419 if (connection->priv->main_context_at_construction != NULL)
420 g_main_context_unref (connection->priv->main_context_at_construction);
422 g_free (connection->priv->machine_id);
424 g_mutex_free (connection->priv->init_lock);
425 g_mutex_free (connection->priv->lock);
427 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
431 g_dbus_connection_get_property (GObject *object,
436 GDBusConnection *connection = G_DBUS_CONNECTION (object);
441 g_value_set_object (value, g_dbus_connection_get_stream (connection));
445 g_value_set_string (value, g_dbus_connection_get_guid (connection));
448 case PROP_UNIQUE_NAME:
449 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
453 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
456 case PROP_EXIT_ON_CLOSE:
457 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
460 case PROP_CAPABILITY_FLAGS:
461 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
465 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
471 g_dbus_connection_set_property (GObject *object,
476 GDBusConnection *connection = G_DBUS_CONNECTION (object);
481 connection->priv->stream = g_value_dup_object (value);
485 connection->priv->guid = g_value_dup_string (value);
489 connection->priv->address = g_value_dup_string (value);
493 connection->priv->flags = g_value_get_flags (value);
496 case PROP_EXIT_ON_CLOSE:
497 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
500 case PROP_AUTHENTICATION_OBSERVER:
501 connection->priv->authentication_observer = g_value_dup_object (value);
505 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
511 g_dbus_connection_real_closed (GDBusConnection *connection,
512 gboolean remote_peer_vanished,
515 if (remote_peer_vanished && connection->priv->exit_on_close)
517 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
523 g_dbus_connection_class_init (GDBusConnectionClass *klass)
525 GObjectClass *gobject_class;
527 g_type_class_add_private (klass, sizeof (GDBusConnectionPrivate));
529 gobject_class = G_OBJECT_CLASS (klass);
531 gobject_class->finalize = g_dbus_connection_finalize;
532 gobject_class->dispose = g_dbus_connection_dispose;
533 gobject_class->set_property = g_dbus_connection_set_property;
534 gobject_class->get_property = g_dbus_connection_get_property;
536 klass->closed = g_dbus_connection_real_closed;
539 * GDBusConnection:stream:
541 * The underlying #GIOStream used for I/O.
545 g_object_class_install_property (gobject_class,
547 g_param_spec_object ("stream",
549 P_("The underlying streams used for I/O"),
553 G_PARAM_CONSTRUCT_ONLY |
554 G_PARAM_STATIC_NAME |
555 G_PARAM_STATIC_BLURB |
556 G_PARAM_STATIC_NICK));
559 * GDBusConnection:address:
561 * A D-Bus address specifying potential endpoints that can be used
562 * when establishing the connection.
566 g_object_class_install_property (gobject_class,
568 g_param_spec_string ("address",
570 P_("D-Bus address specifying potential socket endpoints"),
573 G_PARAM_CONSTRUCT_ONLY |
574 G_PARAM_STATIC_NAME |
575 G_PARAM_STATIC_BLURB |
576 G_PARAM_STATIC_NICK));
579 * GDBusConnection:flags:
581 * Flags from the #GDBusConnectionFlags enumeration.
585 g_object_class_install_property (gobject_class,
587 g_param_spec_flags ("flags",
590 G_TYPE_DBUS_CONNECTION_FLAGS,
591 G_DBUS_CONNECTION_FLAGS_NONE,
593 G_PARAM_CONSTRUCT_ONLY |
594 G_PARAM_STATIC_NAME |
595 G_PARAM_STATIC_BLURB |
596 G_PARAM_STATIC_NICK));
599 * GDBusConnection:guid:
601 * The GUID of the peer performing the role of server when
604 * If you are constructing a #GDBusConnection and pass
605 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
606 * #GDBusConnection:flags property then you MUST also set this
607 * property to a valid guid.
609 * If you are constructing a #GDBusConnection and pass
610 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
611 * #GDBusConnection:flags property you will be able to read the GUID
612 * of the other peer here after the connection has been successfully
617 g_object_class_install_property (gobject_class,
619 g_param_spec_string ("guid",
621 P_("GUID of the server peer"),
625 G_PARAM_CONSTRUCT_ONLY |
626 G_PARAM_STATIC_NAME |
627 G_PARAM_STATIC_BLURB |
628 G_PARAM_STATIC_NICK));
631 * GDBusConnection:unique-name:
633 * The unique name as assigned by the message bus or %NULL if the
634 * connection is not open or not a message bus connection.
638 g_object_class_install_property (gobject_class,
640 g_param_spec_string ("unique-name",
642 P_("Unique name of bus connection"),
645 G_PARAM_STATIC_NAME |
646 G_PARAM_STATIC_BLURB |
647 G_PARAM_STATIC_NICK));
650 * GDBusConnection:closed:
652 * A boolean specifying whether the connection has been closed.
656 g_object_class_install_property (gobject_class,
658 g_param_spec_boolean ("closed",
660 P_("Whether the connection is closed"),
663 G_PARAM_STATIC_NAME |
664 G_PARAM_STATIC_BLURB |
665 G_PARAM_STATIC_NICK));
668 * GDBusConnection:exit-on-close:
670 * A boolean specifying whether the process will be terminated (by
671 * calling <literal>raise(SIGTERM)</literal>) if the connection
672 * is closed by the remote peer.
676 g_object_class_install_property (gobject_class,
678 g_param_spec_boolean ("exit-on-close",
680 P_("Whether the process is terminated when the connection is closed"),
684 G_PARAM_STATIC_NAME |
685 G_PARAM_STATIC_BLURB |
686 G_PARAM_STATIC_NICK));
689 * GDBusConnection:capabilities:
691 * Flags from the #GDBusCapabilityFlags enumeration
692 * representing connection features negotiated with the other peer.
696 g_object_class_install_property (gobject_class,
697 PROP_CAPABILITY_FLAGS,
698 g_param_spec_flags ("capabilities",
701 G_TYPE_DBUS_CAPABILITY_FLAGS,
702 G_DBUS_CAPABILITY_FLAGS_NONE,
704 G_PARAM_STATIC_NAME |
705 G_PARAM_STATIC_BLURB |
706 G_PARAM_STATIC_NICK));
709 * GDBusConnection:authentication-observer:
711 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
715 g_object_class_install_property (gobject_class,
716 PROP_AUTHENTICATION_OBSERVER,
717 g_param_spec_object ("authentication-observer",
718 P_("Authentication Observer"),
719 P_("Object used to assist in the authentication process"),
720 G_TYPE_DBUS_AUTH_OBSERVER,
722 G_PARAM_CONSTRUCT_ONLY |
723 G_PARAM_STATIC_NAME |
724 G_PARAM_STATIC_BLURB |
725 G_PARAM_STATIC_NICK));
728 * GDBusConnection::closed:
729 * @connection: The #GDBusConnection emitting the signal.
730 * @remote_peer_vanished: %TRUE if @connection is closed because the
731 * remote peer closed its end of the connection.
732 * @error: A #GError with more details about the event or %NULL.
734 * Emitted when the connection is closed.
736 * The cause of this event can be
739 * If g_dbus_connection_close() is called. In this case
740 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
743 * If the remote peer closes the connection. In this case
744 * @remote_peer_vanished is set to %TRUE and @error is set.
747 * If the remote peer sends invalid or malformed data. In this
748 * case @remote_peer_vanished is set to %FALSE and @error
753 * Upon receiving this signal, you should give up your reference to
754 * @connection. You are guaranteed that this signal is emitted only
759 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
760 G_TYPE_DBUS_CONNECTION,
762 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
765 _gio_marshal_VOID__BOOLEAN_BOXED,
773 g_dbus_connection_init (GDBusConnection *connection)
775 connection->priv = G_TYPE_INSTANCE_GET_PRIVATE (connection, G_TYPE_DBUS_CONNECTION, GDBusConnectionPrivate);
777 connection->priv->lock = g_mutex_new ();
778 connection->priv->init_lock = g_mutex_new ();
780 connection->priv->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
782 connection->priv->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
784 connection->priv->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
786 connection->priv->map_sender_to_signal_data_array = g_hash_table_new_full (g_str_hash,
791 connection->priv->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
794 (GDestroyNotify) exported_object_free);
796 connection->priv->map_id_to_ei = g_hash_table_new (g_direct_hash,
799 connection->priv->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
802 (GDestroyNotify) exported_subtree_free);
804 connection->priv->map_id_to_es = g_hash_table_new (g_direct_hash,
807 connection->priv->main_context_at_construction = g_main_context_get_thread_default ();
808 if (connection->priv->main_context_at_construction != NULL)
809 g_main_context_ref (connection->priv->main_context_at_construction);
811 connection->priv->filters = g_ptr_array_new ();
815 * g_dbus_connection_get_stream:
816 * @connection: a #GDBusConnection
818 * Gets the underlying stream used for IO.
820 * Returns: the stream used for IO
825 g_dbus_connection_get_stream (GDBusConnection *connection)
827 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
828 return connection->priv->stream;
833 * g_dbus_connection_is_closed:
834 * @connection: A #GDBusConnection.
836 * Gets whether @connection is closed.
838 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
843 g_dbus_connection_is_closed (GDBusConnection *connection)
845 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
846 return connection->priv->closed;
850 * g_dbus_connection_get_capabilities:
851 * @connection: A #GDBusConnection.
853 * Gets the capabilities negotiated with the remote peer
855 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
860 g_dbus_connection_get_capabilities (GDBusConnection *connection)
862 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
863 return connection->priv->capabilities;
867 /* ---------------------------------------------------------------------------------------------------- */
871 GDBusConnection *connection;
873 gboolean remote_peer_vanished;
877 emit_closed_data_free (EmitClosedData *data)
879 g_object_unref (data->connection);
880 if (data->error != NULL)
881 g_error_free (data->error);
886 emit_closed_in_idle (gpointer user_data)
888 EmitClosedData *data = user_data;
891 g_object_notify (G_OBJECT (data->connection), "closed");
892 g_signal_emit (data->connection,
893 signals[CLOSED_SIGNAL],
895 data->remote_peer_vanished,
901 /* Can be called from any thread, must hold lock */
903 set_closed_unlocked (GDBusConnection *connection,
904 gboolean remote_peer_vanished,
907 GSource *idle_source;
908 EmitClosedData *data;
910 CONNECTION_ENSURE_LOCK (connection);
912 g_assert (!connection->priv->closed);
914 connection->priv->closed = TRUE;
916 data = g_new0 (EmitClosedData, 1);
917 data->connection = g_object_ref (connection);
918 data->remote_peer_vanished = remote_peer_vanished;
919 data->error = error != NULL ? g_error_copy (error) : NULL;
921 idle_source = g_idle_source_new ();
922 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
923 g_source_set_callback (idle_source,
926 (GDestroyNotify) emit_closed_data_free);
927 g_source_attach (idle_source, connection->priv->main_context_at_construction);
928 g_source_unref (idle_source);
931 /* ---------------------------------------------------------------------------------------------------- */
934 * g_dbus_connection_close:
935 * @connection: A #GDBusConnection.
937 * Closes @connection. Note that this never causes the process to
938 * exit (this might only happen if the other end of a shared message
939 * bus connection disconnects).
941 * If @connection is already closed, this method does nothing.
946 g_dbus_connection_close (GDBusConnection *connection)
948 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
950 CONNECTION_LOCK (connection);
951 if (!connection->priv->closed)
953 GError *error = NULL;
955 /* TODO: do this async */
956 //g_debug ("closing connection %p's stream %p", connection, connection->priv->stream);
957 if (!g_io_stream_close (connection->priv->stream, NULL, &error))
959 g_warning ("Error closing stream: %s", error->message);
960 g_error_free (error);
963 set_closed_unlocked (connection, FALSE, NULL);
965 CONNECTION_UNLOCK (connection);
968 /* ---------------------------------------------------------------------------------------------------- */
971 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
972 GDBusMessage *message,
973 volatile guint32 *out_serial,
978 guint32 serial_to_use;
981 CONNECTION_ENSURE_LOCK (connection);
983 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
984 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
986 /* TODO: check all necessary headers are present */
991 if (out_serial != NULL)
994 if (connection->priv->closed)
996 g_set_error_literal (error,
999 _("The connection is closed"));
1003 blob = g_dbus_message_to_blob (message,
1005 connection->priv->capabilities,
1010 serial_to_use = ++connection->priv->last_serial; /* TODO: handle overflow */
1015 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1018 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1021 g_assert_not_reached ();
1026 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1027 blob_size, serial_to_use, connection);
1028 g_printerr ("----\n");
1029 hexdump (blob, blob_size);
1030 g_printerr ("----\n");
1033 /* TODO: use connection->priv->auth to encode the blob */
1035 if (out_serial != NULL)
1036 *out_serial = serial_to_use;
1038 g_dbus_message_set_serial (message, serial_to_use);
1040 _g_dbus_worker_send_message (connection->priv->worker,
1044 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1055 * g_dbus_connection_send_message:
1056 * @connection: A #GDBusConnection.
1057 * @message: A #GDBusMessage
1058 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1059 * @error: Return location for error or %NULL.
1061 * Asynchronously sends @message to the peer represented by @connection.
1063 * If @out_serial is not %NULL, then the serial number assigned to
1064 * @message by @connection will be written to this location prior to
1065 * submitting the message to the underlying transport.
1067 * If @connection is closed then the operation will fail with
1068 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1069 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1070 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1072 * See <xref linkend="gdbus-server"/> and <xref
1073 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1074 * low-level API to send and receive UNIX file descriptors.
1076 * Returns: %TRUE if the message was well-formed and queued for
1077 * transmission, %FALSE if @error is set.
1082 g_dbus_connection_send_message (GDBusConnection *connection,
1083 GDBusMessage *message,
1084 volatile guint32 *out_serial,
1089 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1090 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1091 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1093 CONNECTION_LOCK (connection);
1094 ret = g_dbus_connection_send_message_unlocked (connection, message, out_serial, error);
1095 CONNECTION_UNLOCK (connection);
1099 /* ---------------------------------------------------------------------------------------------------- */
1103 volatile gint ref_count;
1104 GDBusConnection *connection;
1106 GSimpleAsyncResult *simple;
1108 GMainContext *main_context;
1110 GCancellable *cancellable;
1112 gulong cancellable_handler_id;
1114 GSource *timeout_source;
1119 static SendMessageData *
1120 send_message_data_ref (SendMessageData *data)
1122 g_atomic_int_inc (&data->ref_count);
1127 send_message_data_unref (SendMessageData *data)
1129 if (g_atomic_int_dec_and_test (&data->ref_count))
1131 g_assert (data->timeout_source == NULL);
1132 g_assert (data->simple == NULL);
1133 g_assert (data->cancellable_handler_id == 0);
1134 g_object_unref (data->connection);
1135 if (data->cancellable != NULL)
1136 g_object_unref (data->cancellable);
1137 if (data->main_context != NULL)
1138 g_main_context_unref (data->main_context);
1143 /* ---------------------------------------------------------------------------------------------------- */
1145 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1147 send_message_with_reply_deliver (SendMessageData *data)
1149 CONNECTION_ENSURE_LOCK (data->connection);
1151 g_assert (!data->delivered);
1153 data->delivered = TRUE;
1155 g_simple_async_result_complete_in_idle (data->simple);
1156 g_object_unref (data->simple);
1157 data->simple = NULL;
1159 if (data->timeout_source != NULL)
1161 g_source_destroy (data->timeout_source);
1162 data->timeout_source = NULL;
1164 if (data->cancellable_handler_id > 0)
1166 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1167 data->cancellable_handler_id = 0;
1170 g_warn_if_fail (g_hash_table_remove (data->connection->priv->map_method_serial_to_send_message_data,
1171 GUINT_TO_POINTER (data->serial)));
1173 send_message_data_unref (data);
1176 /* ---------------------------------------------------------------------------------------------------- */
1178 /* must hold lock */
1180 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1181 GDBusMessage *reply)
1183 if (data->delivered)
1186 g_simple_async_result_set_op_res_gpointer (data->simple,
1187 g_object_ref (reply),
1190 send_message_with_reply_deliver (data);
1196 /* ---------------------------------------------------------------------------------------------------- */
1199 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1201 SendMessageData *data = user_data;
1203 CONNECTION_LOCK (data->connection);
1204 if (data->delivered)
1207 g_simple_async_result_set_error (data->simple,
1209 G_IO_ERROR_CANCELLED,
1210 _("Operation was cancelled"));
1212 send_message_with_reply_deliver (data);
1215 CONNECTION_UNLOCK (data->connection);
1219 /* Can be called from any thread with or without lock held */
1221 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1224 SendMessageData *data = user_data;
1225 GSource *idle_source;
1227 /* postpone cancellation to idle handler since we may be called directly
1228 * via g_cancellable_connect() (e.g. holding lock)
1230 idle_source = g_idle_source_new ();
1231 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1232 g_source_set_callback (idle_source,
1233 send_message_with_reply_cancelled_idle_cb,
1234 send_message_data_ref (data),
1235 (GDestroyNotify) send_message_data_unref);
1236 g_source_attach (idle_source, data->main_context);
1237 g_source_unref (idle_source);
1240 /* ---------------------------------------------------------------------------------------------------- */
1243 send_message_with_reply_timeout_cb (gpointer user_data)
1245 SendMessageData *data = user_data;
1247 CONNECTION_LOCK (data->connection);
1248 if (data->delivered)
1251 g_simple_async_result_set_error (data->simple,
1253 G_IO_ERROR_TIMED_OUT,
1254 _("Timeout was reached"));
1256 send_message_with_reply_deliver (data);
1259 CONNECTION_UNLOCK (data->connection);
1264 /* ---------------------------------------------------------------------------------------------------- */
1267 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1268 GDBusMessage *message,
1270 volatile guint32 *out_serial,
1271 GCancellable *cancellable,
1272 GAsyncReadyCallback callback,
1275 GSimpleAsyncResult *simple;
1276 SendMessageData *data;
1278 volatile guint32 serial;
1282 if (out_serial == NULL)
1283 out_serial = &serial;
1285 if (timeout_msec == -1)
1286 timeout_msec = 25 * 1000;
1288 simple = g_simple_async_result_new (G_OBJECT (connection),
1291 g_dbus_connection_send_message_with_reply);
1293 if (g_cancellable_is_cancelled (cancellable))
1295 g_simple_async_result_set_error (simple,
1297 G_IO_ERROR_CANCELLED,
1298 _("Operation was cancelled"));
1299 g_simple_async_result_complete_in_idle (simple);
1300 g_object_unref (simple);
1304 if (connection->priv->closed)
1306 g_simple_async_result_set_error (simple,
1309 _("The connection is closed"));
1310 g_simple_async_result_complete_in_idle (simple);
1311 g_object_unref (simple);
1316 if (!g_dbus_connection_send_message_unlocked (connection, message, out_serial, &error))
1318 g_simple_async_result_set_from_error (simple, error);
1319 g_simple_async_result_complete_in_idle (simple);
1320 g_object_unref (simple);
1324 data = g_new0 (SendMessageData, 1);
1325 data->ref_count = 1;
1326 data->connection = g_object_ref (connection);
1327 data->simple = simple;
1328 data->serial = *out_serial;
1329 data->main_context = g_main_context_get_thread_default ();
1330 if (data->main_context != NULL)
1331 g_main_context_ref (data->main_context);
1333 if (cancellable != NULL)
1335 data->cancellable = g_object_ref (cancellable);
1336 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1337 G_CALLBACK (send_message_with_reply_cancelled_cb),
1338 send_message_data_ref (data),
1339 (GDestroyNotify) send_message_data_unref);
1340 g_object_set_data_full (G_OBJECT (simple),
1342 g_object_ref (cancellable),
1343 (GDestroyNotify) g_object_unref);
1346 data->timeout_source = g_timeout_source_new (timeout_msec);
1347 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1348 g_source_set_callback (data->timeout_source,
1349 send_message_with_reply_timeout_cb,
1350 send_message_data_ref (data),
1351 (GDestroyNotify) send_message_data_unref);
1352 g_source_attach (data->timeout_source, data->main_context);
1353 g_source_unref (data->timeout_source);
1355 g_hash_table_insert (connection->priv->map_method_serial_to_send_message_data,
1356 GUINT_TO_POINTER (*out_serial),
1364 * g_dbus_connection_send_message_with_reply:
1365 * @connection: A #GDBusConnection.
1366 * @message: A #GDBusMessage.
1367 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1368 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1369 * @cancellable: A #GCancellable or %NULL.
1370 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1371 * care about the result.
1372 * @user_data: The data to pass to @callback.
1374 * Asynchronously sends @message to the peer represented by @connection.
1376 * If @out_serial is not %NULL, then the serial number assigned to
1377 * @message by @connection will be written to this location prior to
1378 * submitting the message to the underlying transport.
1380 * If @connection is closed then the operation will fail with
1381 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1382 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1383 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1385 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1386 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1387 * of the thread you are calling this method from. You can then call
1388 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1389 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1391 * See <xref linkend="gdbus-server"/> and <xref
1392 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1393 * low-level API to send and receive UNIX file descriptors.
1398 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1399 GDBusMessage *message,
1401 volatile guint32 *out_serial,
1402 GCancellable *cancellable,
1403 GAsyncReadyCallback callback,
1406 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1407 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1408 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1410 CONNECTION_LOCK (connection);
1411 g_dbus_connection_send_message_with_reply_unlocked (connection,
1418 CONNECTION_UNLOCK (connection);
1422 * g_dbus_connection_send_message_with_reply_finish:
1423 * @connection: a #GDBusConnection
1424 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1425 * @error: Return location for error or %NULL.
1427 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1429 * Note that @error is only set if a local in-process error
1430 * occured. That is to say that the returned #GDBusMessage object may
1431 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1432 * g_dbus_message_to_gerror() to transcode this to a #GError.
1434 * See <xref linkend="gdbus-server"/> and <xref
1435 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1436 * low-level API to send and receive UNIX file descriptors.
1438 * Returns: A #GDBusMessage or %NULL if @error is set.
1443 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1447 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1448 GDBusMessage *reply;
1449 GCancellable *cancellable;
1451 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1452 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1456 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1458 if (g_simple_async_result_propagate_error (simple, error))
1461 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1462 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1463 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1465 g_object_unref (reply);
1467 g_set_error_literal (error,
1469 G_IO_ERROR_CANCELLED,
1470 _("Operation was cancelled"));
1476 /* ---------------------------------------------------------------------------------------------------- */
1481 GMainContext *context;
1483 } SendMessageSyncData;
1486 send_message_with_reply_sync_cb (GDBusConnection *connection,
1490 SendMessageSyncData *data = user_data;
1491 data->res = g_object_ref (res);
1492 g_main_loop_quit (data->loop);
1496 * g_dbus_connection_send_message_with_reply_sync:
1497 * @connection: A #GDBusConnection.
1498 * @message: A #GDBusMessage.
1499 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
1500 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1501 * @cancellable: A #GCancellable or %NULL.
1502 * @error: Return location for error or %NULL.
1504 * Synchronously sends @message to the peer represented by @connection
1505 * and blocks the calling thread until a reply is received or the
1506 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1507 * for the asynchronous version of this method.
1509 * If @out_serial is not %NULL, then the serial number assigned to
1510 * @message by @connection will be written to this location prior to
1511 * submitting the message to the underlying transport.
1513 * If @connection is closed then the operation will fail with
1514 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1515 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1516 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1518 * Note that @error is only set if a local in-process error
1519 * occured. That is to say that the returned #GDBusMessage object may
1520 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1521 * g_dbus_message_to_gerror() to transcode this to a #GError.
1523 * See <xref linkend="gdbus-server"/> and <xref
1524 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1525 * low-level API to send and receive UNIX file descriptors.
1527 * Returns: A #GDBusMessage that is the reply to @message or %NULL if @error is set.
1532 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1533 GDBusMessage *message,
1535 volatile guint32 *out_serial,
1536 GCancellable *cancellable,
1539 SendMessageSyncData *data;
1540 GDBusMessage *reply;
1542 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1543 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1544 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1545 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1547 data = g_new0 (SendMessageSyncData, 1);
1548 data->context = g_main_context_new ();
1549 data->loop = g_main_loop_new (data->context, FALSE);
1551 g_main_context_push_thread_default (data->context);
1553 g_dbus_connection_send_message_with_reply (connection,
1558 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
1560 g_main_loop_run (data->loop);
1561 reply = g_dbus_connection_send_message_with_reply_finish (connection,
1565 g_main_context_pop_thread_default (data->context);
1567 g_main_context_unref (data->context);
1568 g_main_loop_unref (data->loop);
1569 g_object_unref (data->res);
1575 /* ---------------------------------------------------------------------------------------------------- */
1579 GDBusMessageFilterFunction func;
1586 GDBusMessageFilterFunction filter_function;
1588 GDestroyNotify user_data_free_func;
1591 /* Called in worker's thread - we must not block */
1593 on_worker_message_received (GDBusWorker *worker,
1594 GDBusMessage *message,
1597 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1598 FilterCallback *filters;
1599 gboolean consumed_by_filter;
1603 //g_debug ("in on_worker_message_received");
1605 g_object_ref (connection);
1607 /* First collect the set of callback functions */
1608 CONNECTION_LOCK (connection);
1609 num_filters = connection->priv->filters->len;
1610 filters = g_new0 (FilterCallback, num_filters);
1611 for (n = 0; n < num_filters; n++)
1613 FilterData *data = connection->priv->filters->pdata[n];
1614 filters[n].func = data->filter_function;
1615 filters[n].user_data = data->user_data;
1617 CONNECTION_UNLOCK (connection);
1619 /* the call the filters in order (without holding the lock) */
1620 consumed_by_filter = FALSE;
1621 for (n = 0; n < num_filters; n++)
1623 consumed_by_filter = filters[n].func (connection,
1625 filters[n].user_data);
1626 if (consumed_by_filter)
1630 /* Standard dispatch unless the filter ate the message */
1631 if (!consumed_by_filter)
1633 GDBusMessageType message_type;
1635 message_type = g_dbus_message_get_message_type (message);
1636 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
1638 guint32 reply_serial;
1639 SendMessageData *send_message_data;
1641 reply_serial = g_dbus_message_get_reply_serial (message);
1642 CONNECTION_LOCK (connection);
1643 send_message_data = g_hash_table_lookup (connection->priv->map_method_serial_to_send_message_data,
1644 GUINT_TO_POINTER (reply_serial));
1645 if (send_message_data != NULL)
1647 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
1648 send_message_data_deliver_reply_unlocked (send_message_data, message);
1652 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
1654 CONNECTION_UNLOCK (connection);
1656 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
1658 CONNECTION_LOCK (connection);
1659 distribute_signals (connection, message);
1660 CONNECTION_UNLOCK (connection);
1662 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
1664 CONNECTION_LOCK (connection);
1665 distribute_method_call (connection, message);
1666 CONNECTION_UNLOCK (connection);
1670 g_object_unref (connection);
1674 /* Called in worker's thread - we must not block */
1676 on_worker_closed (GDBusWorker *worker,
1677 gboolean remote_peer_vanished,
1681 GDBusConnection *connection = G_DBUS_CONNECTION (user_data);
1683 //g_debug ("in on_worker_closed: %s", error->message);
1685 CONNECTION_LOCK (connection);
1686 if (!connection->priv->closed)
1687 set_closed_unlocked (connection, remote_peer_vanished, error);
1688 CONNECTION_UNLOCK (connection);
1691 /* ---------------------------------------------------------------------------------------------------- */
1693 /* Determines the biggest set of capabilities we can support on this connection */
1694 static GDBusCapabilityFlags
1695 get_offered_capabilities_max (GDBusConnection *connection)
1697 GDBusCapabilityFlags ret;
1698 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
1700 if (G_IS_UNIX_CONNECTION (connection->priv->stream))
1701 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
1707 initable_init (GInitable *initable,
1708 GCancellable *cancellable,
1711 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
1714 /* This method needs to be idempotent to work with the singleton
1715 * pattern. See the docs for g_initable_init(). We implement this by
1718 * Unfortunately we can't use the main lock since the on_worker_*()
1719 * callbacks above needs the lock during initialization (for message
1720 * bus connections we do a synchronous Hello() call on the bus).
1722 g_mutex_lock (connection->priv->init_lock);
1726 if (connection->priv->is_initialized)
1728 if (connection->priv->stream != NULL)
1731 g_assert (connection->priv->initialization_error != NULL);
1734 g_assert (connection->priv->initialization_error == NULL);
1736 /* The user can pass multiple (but mutally exclusive) construct
1739 * - stream (of type GIOStream)
1740 * - address (of type gchar*)
1742 * At the end of the day we end up with a non-NULL GIOStream
1743 * object in connection->priv->stream.
1745 if (connection->priv->address != NULL)
1747 g_assert (connection->priv->stream == NULL);
1749 if ((connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
1750 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
1752 g_set_error_literal (error,
1754 G_IO_ERROR_INVALID_ARGUMENT,
1755 _("Unsupported flags encountered when constructing a client-side connection"));
1759 connection->priv->stream = g_dbus_address_get_stream_sync (connection->priv->address,
1760 NULL, /* TODO: out_guid */
1762 &connection->priv->initialization_error);
1763 if (connection->priv->stream == NULL)
1766 else if (connection->priv->stream != NULL)
1772 g_assert_not_reached ();
1775 /* Authenticate the connection */
1776 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
1778 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
1779 g_assert (connection->priv->guid != NULL);
1780 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1781 if (!_g_dbus_auth_run_server (connection->priv->auth,
1782 connection->priv->authentication_observer,
1783 connection->priv->guid,
1784 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
1785 get_offered_capabilities_max (connection),
1786 &connection->priv->capabilities,
1787 &connection->priv->crendentials,
1789 &connection->priv->initialization_error))
1792 else if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
1794 g_assert (!(connection->priv->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
1795 g_assert (connection->priv->guid == NULL);
1796 connection->priv->auth = _g_dbus_auth_new (connection->priv->stream);
1797 connection->priv->guid = _g_dbus_auth_run_client (connection->priv->auth,
1798 get_offered_capabilities_max (connection),
1799 &connection->priv->capabilities,
1801 &connection->priv->initialization_error);
1802 if (connection->priv->guid == NULL)
1806 if (connection->priv->authentication_observer != NULL)
1808 g_object_unref (connection->priv->authentication_observer);
1809 connection->priv->authentication_observer = NULL;
1812 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->priv->stream)
1814 //g_debug ("haz unix fd passing powers: %d", connection->priv->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
1818 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
1822 if (G_IS_SOCKET_CONNECTION (connection->priv->stream))
1824 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->priv->stream)), FALSE);
1827 connection->priv->worker = _g_dbus_worker_new (connection->priv->stream,
1828 connection->priv->capabilities,
1829 on_worker_message_received,
1833 /* if a bus connection, invoke org.freedesktop.DBus.Hello - this is how we're getting a name */
1834 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
1836 GVariant *hello_result;
1838 hello_result = g_dbus_connection_call_sync (connection,
1839 "org.freedesktop.DBus", /* name */
1840 "/org/freedesktop/DBus", /* path */
1841 "org.freedesktop.DBus", /* interface */
1843 NULL, /* parameters */
1844 G_DBUS_CALL_FLAGS_NONE,
1846 NULL, /* TODO: cancellable */
1847 &connection->priv->initialization_error);
1848 if (hello_result == NULL)
1851 g_variant_get (hello_result, "(s)", &connection->priv->bus_unique_name);
1852 g_variant_unref (hello_result);
1853 //g_debug ("unique name is `%s'", connection->priv->bus_unique_name);
1856 connection->priv->is_initialized = TRUE;
1862 g_assert (connection->priv->initialization_error != NULL);
1863 g_propagate_error (error, g_error_copy (connection->priv->initialization_error));
1866 g_mutex_unlock (connection->priv->init_lock);
1872 initable_iface_init (GInitableIface *initable_iface)
1874 initable_iface->init = initable_init;
1877 /* ---------------------------------------------------------------------------------------------------- */
1880 async_init_thread (GSimpleAsyncResult *res,
1882 GCancellable *cancellable)
1884 GError *error = NULL;
1886 if (!g_initable_init (G_INITABLE (object), cancellable, &error))
1888 g_simple_async_result_set_from_error (res, error);
1889 g_error_free (error);
1894 async_initable_init_async (GAsyncInitable *initable,
1896 GCancellable *cancellable,
1897 GAsyncReadyCallback callback,
1900 GSimpleAsyncResult *res;
1902 g_return_if_fail (G_IS_INITABLE (initable));
1904 res = g_simple_async_result_new (G_OBJECT (initable), callback, user_data,
1905 async_initable_init_async);
1906 g_simple_async_result_run_in_thread (res, async_init_thread,
1907 io_priority, cancellable);
1908 g_object_unref (res);
1912 async_initable_init_finish (GAsyncInitable *initable,
1916 return TRUE; /* Errors handled by base impl */
1920 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
1922 /* We basically just want to use GIO's default implementation - though that one is
1923 * unfortunately broken, see #615111. So we copy-paste a fixed-up version.
1925 async_initable_iface->init_async = async_initable_init_async;
1926 async_initable_iface->init_finish = async_initable_init_finish;
1929 /* ---------------------------------------------------------------------------------------------------- */
1932 * g_dbus_connection_new:
1933 * @stream: A #GIOStream.
1934 * @guid: The GUID to use if a authenticating as a server or %NULL.
1935 * @flags: Flags describing how to make the connection.
1936 * @observer: A #GDBusAuthObserver or %NULL.
1937 * @cancellable: A #GCancellable or %NULL.
1938 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
1939 * @user_data: The data to pass to @callback.
1941 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
1942 * with the end represented by @stream.
1944 * If @observer is not %NULL it may be used to control the
1945 * authentication process.
1947 * When the operation is finished, @callback will be invoked. You can
1948 * then call g_dbus_connection_new_finish() to get the result of the
1951 * This is a asynchronous failable constructor. See
1952 * g_dbus_connection_new_sync() for the synchronous
1958 g_dbus_connection_new (GIOStream *stream,
1960 GDBusConnectionFlags flags,
1961 GDBusAuthObserver *observer,
1962 GCancellable *cancellable,
1963 GAsyncReadyCallback callback,
1966 g_return_if_fail (G_IS_IO_STREAM (stream));
1967 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
1975 "authentication-observer", observer,
1980 * g_dbus_connection_new_finish:
1981 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
1982 * @error: Return location for error or %NULL.
1984 * Finishes an operation started with g_dbus_connection_new().
1986 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
1991 g_dbus_connection_new_finish (GAsyncResult *res,
1995 GObject *source_object;
1997 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
1998 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2000 source_object = g_async_result_get_source_object (res);
2001 g_assert (source_object != NULL);
2002 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2005 g_object_unref (source_object);
2007 return G_DBUS_CONNECTION (object);
2013 * g_dbus_connection_new_sync:
2014 * @stream: A #GIOStream.
2015 * @guid: The GUID to use if a authenticating as a server or %NULL.
2016 * @flags: Flags describing how to make the connection.
2017 * @observer: A #GDBusAuthObserver or %NULL.
2018 * @cancellable: A #GCancellable or %NULL.
2019 * @error: Return location for error or %NULL.
2021 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2022 * with the end represented by @stream.
2024 * If @observer is not %NULL it may be used to control the
2025 * authentication process.
2027 * This is a synchronous failable constructor. See
2028 * g_dbus_connection_new() for the asynchronous version.
2030 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2035 g_dbus_connection_new_sync (GIOStream *stream,
2037 GDBusConnectionFlags flags,
2038 GDBusAuthObserver *observer,
2039 GCancellable *cancellable,
2042 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2043 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2044 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2050 "authentication-observer", observer,
2054 /* ---------------------------------------------------------------------------------------------------- */
2057 * g_dbus_connection_new_for_address:
2058 * @address: A D-Bus address.
2059 * @flags: Flags describing how to make the connection.
2060 * @observer: A #GDBusAuthObserver or %NULL.
2061 * @cancellable: A #GCancellable or %NULL.
2062 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2063 * @user_data: The data to pass to @callback.
2065 * Asynchronously connects and sets up a D-Bus client connection for
2066 * exchanging D-Bus messages with an endpoint specified by @address
2067 * which must be in the D-Bus address format.
2069 * This constructor can only be used to initiate client-side
2070 * connections - use g_dbus_connection_new() if you need to act as the
2071 * server. In particular, @flags cannot contain the
2072 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2073 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2075 * When the operation is finished, @callback will be invoked. You can
2076 * then call g_dbus_connection_new_finish() to get the result of the
2079 * If @observer is not %NULL it may be used to control the
2080 * authentication process.
2082 * This is a asynchronous failable constructor. See
2083 * g_dbus_connection_new_for_address_sync() for the synchronous
2089 g_dbus_connection_new_for_address (const gchar *address,
2090 GDBusConnectionFlags flags,
2091 GDBusAuthObserver *observer,
2092 GCancellable *cancellable,
2093 GAsyncReadyCallback callback,
2096 g_return_if_fail (address != NULL);
2097 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2104 "authentication-observer", observer,
2109 * g_dbus_connection_new_for_address_finish:
2110 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2111 * @error: Return location for error or %NULL.
2113 * Finishes an operation started with g_dbus_connection_new_for_address().
2115 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2120 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2124 GObject *source_object;
2126 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2127 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2129 source_object = g_async_result_get_source_object (res);
2130 g_assert (source_object != NULL);
2131 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2134 g_object_unref (source_object);
2136 return G_DBUS_CONNECTION (object);
2142 * g_dbus_connection_new_for_address_sync:
2143 * @address: A D-Bus address.
2144 * @flags: Flags describing how to make the connection.
2145 * @observer: A #GDBusAuthObserver or %NULL.
2146 * @cancellable: A #GCancellable or %NULL.
2147 * @error: Return location for error or %NULL.
2149 * Synchronously connects and sets up a D-Bus client connection for
2150 * exchanging D-Bus messages with an endpoint specified by @address
2151 * which must be in the D-Bus address format.
2153 * This constructor can only be used to initiate client-side
2154 * connections - use g_dbus_connection_new_sync() if you need to act
2155 * as the server. In particular, @flags cannot contain the
2156 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2157 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2159 * This is a synchronous failable constructor. See
2160 * g_dbus_connection_new_for_address() for the asynchronous version.
2162 * If @observer is not %NULL it may be used to control the
2163 * authentication process.
2165 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2170 g_dbus_connection_new_for_address_sync (const gchar *address,
2171 GDBusConnectionFlags flags,
2172 GDBusAuthObserver *observer,
2173 GCancellable *cancellable,
2176 g_return_val_if_fail (address != NULL, NULL);
2177 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2178 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2183 "authentication-observer", observer,
2187 /* ---------------------------------------------------------------------------------------------------- */
2190 * g_dbus_connection_set_exit_on_close:
2191 * @connection: A #GDBusConnection.
2192 * @exit_on_close: Whether the process should be terminated
2193 * when @connection is closed by the remote peer.
2195 * Sets whether the process should be terminated when @connection is
2196 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2202 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2203 gboolean exit_on_close)
2205 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2206 connection->priv->exit_on_close = exit_on_close;
2210 * g_dbus_connection_get_exit_on_close:
2211 * @connection: A #GDBusConnection.
2213 * Gets whether the process is terminated when @connection is
2214 * closed by the remote peer. See
2215 * #GDBusConnection:exit-on-close for more details.
2217 * Returns: Whether the process is terminated when @connection is
2218 * closed by the remote peer.
2223 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2225 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2226 return connection->priv->exit_on_close;
2230 * g_dbus_connection_get_guid:
2231 * @connection: A #GDBusConnection.
2233 * The GUID of the peer performing the role of server when
2234 * authenticating. See #GDBusConnection:guid for more details.
2236 * Returns: The GUID. Do not free this string, it is owned by
2242 g_dbus_connection_get_guid (GDBusConnection *connection)
2244 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2245 return connection->priv->guid;
2249 * g_dbus_connection_get_unique_name:
2250 * @connection: A #GDBusConnection.
2252 * Gets the unique name of @connection as assigned by the message
2253 * bus. This can also be used to figure out if @connection is a
2254 * message bus connection.
2256 * Returns: The unique name or %NULL if @connection is not a message
2257 * bus connection. Do not free this string, it is owned by
2263 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2265 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2266 return connection->priv->bus_unique_name;
2270 * g_dbus_connection_get_peer_credentials:
2271 * @connection: A #GDBusConnection.
2273 * Gets the credentials of the authenticated peer. This will always
2274 * return %NULL unless @connection acted as a server
2275 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2276 * when set up and the client passed credentials as part of the
2277 * authentication process.
2279 * In a message bus setup, the message bus is always the server and
2280 * each application is a client. So this method will always return
2281 * %NULL for message bus clients.
2283 * Returns: A #GCredentials or %NULL if not available. Do not free
2284 * this object, it is owned by @connection.
2289 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2291 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2292 return connection->priv->crendentials;
2295 /* ---------------------------------------------------------------------------------------------------- */
2297 static guint _global_filter_id = 1;
2300 * g_dbus_connection_add_filter:
2301 * @connection: A #GDBusConnection.
2302 * @filter_function: A filter function.
2303 * @user_data: User data to pass to @filter_function.
2304 * @user_data_free_func: Function to free @user_data with when filter
2305 * is removed or %NULL.
2307 * Adds a message filter. Filters are handlers that are run on all
2308 * incoming messages, prior to standard dispatch. Filters are run in
2309 * the order that they were added. The same handler can be added as a
2310 * filter more than once, in which case it will be run more than once.
2311 * Filters added during a filter callback won't be run on the message
2314 * Note that filters are run in a dedicated message handling thread so
2315 * they can't block and, generally, can't do anything but signal a
2316 * worker thread. Also note that filters are rarely needed - use API
2317 * such as g_dbus_connection_send_message_with_reply(),
2318 * g_dbus_connection_signal_subscribe() or
2319 * g_dbus_connection_call() instead.
2321 * Returns: A filter identifier that can be used with
2322 * g_dbus_connection_remove_filter().
2327 g_dbus_connection_add_filter (GDBusConnection *connection,
2328 GDBusMessageFilterFunction filter_function,
2330 GDestroyNotify user_data_free_func)
2334 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2335 g_return_val_if_fail (filter_function != NULL, 0);
2337 CONNECTION_LOCK (connection);
2338 data = g_new0 (FilterData, 1);
2339 data->id = _global_filter_id++; /* TODO: overflow etc. */
2340 data->filter_function = filter_function;
2341 data->user_data = user_data;
2342 data->user_data_free_func = user_data_free_func;
2343 g_ptr_array_add (connection->priv->filters, data);
2344 CONNECTION_UNLOCK (connection);
2349 /* only called from finalize(), removes all filters */
2351 purge_all_filters (GDBusConnection *connection)
2354 for (n = 0; n < connection->priv->filters->len; n++)
2356 FilterData *data = connection->priv->filters->pdata[n];
2357 if (data->user_data_free_func != NULL)
2358 data->user_data_free_func (data->user_data);
2364 * g_dbus_connection_remove_filter:
2365 * @connection: a #GDBusConnection
2366 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2373 g_dbus_connection_remove_filter (GDBusConnection *connection,
2377 FilterData *to_destroy;
2379 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2381 CONNECTION_LOCK (connection);
2383 for (n = 0; n < connection->priv->filters->len; n++)
2385 FilterData *data = connection->priv->filters->pdata[n];
2386 if (data->id == filter_id)
2388 g_ptr_array_remove_index (connection->priv->filters, n);
2393 CONNECTION_UNLOCK (connection);
2395 /* do free without holding lock */
2396 if (to_destroy != NULL)
2398 if (to_destroy->user_data_free_func != NULL)
2399 to_destroy->user_data_free_func (to_destroy->user_data);
2400 g_free (to_destroy);
2404 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2408 /* ---------------------------------------------------------------------------------------------------- */
2414 gchar *interface_name;
2418 GArray *subscribers;
2423 GDBusSignalCallback callback;
2425 GDestroyNotify user_data_free_func;
2427 GMainContext *context;
2431 signal_data_free (SignalData *data)
2433 g_free (data->rule);
2434 g_free (data->sender);
2435 g_free (data->interface_name);
2436 g_free (data->member);
2437 g_free (data->object_path);
2438 g_free (data->arg0);
2439 g_array_free (data->subscribers, TRUE);
2444 args_to_rule (const gchar *sender,
2445 const gchar *interface_name,
2446 const gchar *member,
2447 const gchar *object_path,
2452 rule = g_string_new ("type='signal'");
2454 g_string_append_printf (rule, ",sender='%s'", sender);
2455 if (interface_name != NULL)
2456 g_string_append_printf (rule, ",interface='%s'", interface_name);
2458 g_string_append_printf (rule, ",member='%s'", member);
2459 if (object_path != NULL)
2460 g_string_append_printf (rule, ",path='%s'", object_path);
2462 g_string_append_printf (rule, ",arg0='%s'", arg0);
2464 return g_string_free (rule, FALSE);
2467 static guint _global_subscriber_id = 1;
2468 static guint _global_registration_id = 1;
2469 static guint _global_subtree_registration_id = 1;
2471 /* ---------------------------------------------------------------------------------------------------- */
2473 /* must hold lock when calling */
2475 add_match_rule (GDBusConnection *connection,
2476 const gchar *match_rule)
2479 GDBusMessage *message;
2481 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2482 "/org/freedesktop/DBus", /* path */
2483 "org.freedesktop.DBus", /* interface */
2485 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2488 if (!g_dbus_connection_send_message_unlocked (connection,
2493 g_critical ("Error while sending AddMatch() message: %s", error->message);
2494 g_error_free (error);
2496 g_object_unref (message);
2499 /* ---------------------------------------------------------------------------------------------------- */
2501 /* must hold lock when calling */
2503 remove_match_rule (GDBusConnection *connection,
2504 const gchar *match_rule)
2507 GDBusMessage *message;
2509 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
2510 "/org/freedesktop/DBus", /* path */
2511 "org.freedesktop.DBus", /* interface */
2513 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
2516 if (!g_dbus_connection_send_message_unlocked (connection,
2521 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
2522 g_error_free (error);
2524 g_object_unref (message);
2527 /* ---------------------------------------------------------------------------------------------------- */
2530 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
2532 return g_strcmp0 (signal_data->sender, "org.freedesktop.DBus") == 0 &&
2533 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
2534 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
2535 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
2536 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
2539 /* ---------------------------------------------------------------------------------------------------- */
2542 * g_dbus_connection_signal_subscribe:
2543 * @connection: A #GDBusConnection.
2544 * @sender: Sender name to match on. Must be either <literal>org.freedesktop.DBus</literal> (for listening to signals from the message bus daemon) or a unique name or %NULL to listen from all senders.
2545 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
2546 * @member: D-Bus signal name to match on or %NULL to match on all signals.
2547 * @object_path: Object path to match on or %NULL to match on all object paths.
2548 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
2549 * @callback: Callback to invoke when there is a signal matching the requested data.
2550 * @user_data: User data to pass to @callback.
2551 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
2553 * Subscribes to signals on @connection and invokes @callback with a
2554 * whenever the signal is received. Note that @callback
2555 * will be invoked in the <link
2556 * linkend="g-main-context-push-thread-default">thread-default main
2557 * loop</link> of the thread you are calling this method from.
2559 * It is considered a programming error to use this function if @connection is closed.
2561 * Note that if @sender is not <literal>org.freedesktop.DBus</literal> (for listening to signals from the
2562 * message bus daemon), then it needs to be a unique bus name or %NULL (for listening to signals from any
2563 * name) - you cannot pass a name like <literal>com.example.MyApp</literal>.
2564 * Use e.g. g_bus_watch_name() to find the unique name for the owner of the name you are interested in. Also note
2565 * that this function does not remove a subscription if @sender vanishes from the bus. You have to manually
2566 * call g_dbus_connection_signal_unsubscribe() to remove a subscription.
2568 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
2573 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
2574 const gchar *sender,
2575 const gchar *interface_name,
2576 const gchar *member,
2577 const gchar *object_path,
2579 GDBusSignalCallback callback,
2581 GDestroyNotify user_data_free_func)
2584 SignalData *signal_data;
2585 SignalSubscriber subscriber;
2586 GPtrArray *signal_data_array;
2588 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
2589 * an OOM condition. We might want to change that but that would involve making
2590 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
2591 * handle that. And there's really no sensible way of handling this short of retrying
2592 * to add the match rule... and then there's the little thing that, hey, maybe there's
2593 * a reason the bus in an OOM condition.
2595 * Doable, but not really sure it's worth it...
2598 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2599 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
2600 g_return_val_if_fail (sender == NULL || ((strcmp (sender, "org.freedesktop.DBus") == 0 || sender[0] == ':') &&
2601 (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
2602 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
2603 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
2604 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
2605 g_return_val_if_fail (callback != NULL, 0);
2607 CONNECTION_LOCK (connection);
2609 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
2614 subscriber.callback = callback;
2615 subscriber.user_data = user_data;
2616 subscriber.user_data_free_func = user_data_free_func;
2617 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
2618 subscriber.context = g_main_context_get_thread_default ();
2619 if (subscriber.context != NULL)
2620 g_main_context_ref (subscriber.context);
2622 /* see if we've already have this rule */
2623 signal_data = g_hash_table_lookup (connection->priv->map_rule_to_signal_data, rule);
2624 if (signal_data != NULL)
2626 g_array_append_val (signal_data->subscribers, subscriber);
2631 signal_data = g_new0 (SignalData, 1);
2632 signal_data->rule = rule;
2633 signal_data->sender = g_strdup (sender);
2634 signal_data->interface_name = g_strdup (interface_name);
2635 signal_data->member = g_strdup (member);
2636 signal_data->object_path = g_strdup (object_path);
2637 signal_data->arg0 = g_strdup (arg0);
2638 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2639 g_array_append_val (signal_data->subscribers, subscriber);
2641 g_hash_table_insert (connection->priv->map_rule_to_signal_data,
2645 /* Add the match rule to the bus...
2647 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
2648 * always send such messages to us.
2650 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2652 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2653 add_match_rule (connection, signal_data->rule);
2657 g_hash_table_insert (connection->priv->map_id_to_signal_data,
2658 GUINT_TO_POINTER (subscriber.id),
2661 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2662 signal_data->sender);
2663 if (signal_data_array == NULL)
2665 signal_data_array = g_ptr_array_new ();
2666 g_hash_table_insert (connection->priv->map_sender_to_signal_data_array,
2667 g_strdup (signal_data->sender),
2670 g_ptr_array_add (signal_data_array, signal_data);
2672 CONNECTION_UNLOCK (connection);
2674 return subscriber.id;
2677 /* ---------------------------------------------------------------------------------------------------- */
2679 /* must hold lock when calling this */
2681 unsubscribe_id_internal (GDBusConnection *connection,
2682 guint subscription_id,
2683 GArray *out_removed_subscribers)
2685 SignalData *signal_data;
2686 GPtrArray *signal_data_array;
2689 signal_data = g_hash_table_lookup (connection->priv->map_id_to_signal_data,
2690 GUINT_TO_POINTER (subscription_id));
2691 if (signal_data == NULL)
2693 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
2697 for (n = 0; n < signal_data->subscribers->len; n++)
2699 SignalSubscriber *subscriber;
2701 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
2702 if (subscriber->id != subscription_id)
2705 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_signal_data,
2706 GUINT_TO_POINTER (subscription_id)));
2707 g_array_append_val (out_removed_subscribers, *subscriber);
2708 g_array_remove_index (signal_data->subscribers, n);
2710 if (signal_data->subscribers->len == 0)
2711 g_warn_if_fail (g_hash_table_remove (connection->priv->map_rule_to_signal_data, signal_data->rule));
2713 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array,
2714 signal_data->sender);
2715 g_warn_if_fail (signal_data_array != NULL);
2716 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
2718 if (signal_data_array->len == 0)
2720 g_warn_if_fail (g_hash_table_remove (connection->priv->map_sender_to_signal_data_array, signal_data->sender));
2722 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
2723 if (connection->priv->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2725 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
2726 remove_match_rule (connection, signal_data->rule);
2729 signal_data_free (signal_data);
2735 g_assert_not_reached ();
2742 * g_dbus_connection_signal_unsubscribe:
2743 * @connection: A #GDBusConnection.
2744 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
2746 * Unsubscribes from signals.
2751 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
2752 guint subscription_id)
2754 GArray *subscribers;
2757 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2759 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2761 CONNECTION_LOCK (connection);
2762 unsubscribe_id_internal (connection,
2765 CONNECTION_UNLOCK (connection);
2768 g_assert (subscribers->len == 0 || subscribers->len == 1);
2770 /* call GDestroyNotify without lock held */
2771 for (n = 0; n < subscribers->len; n++)
2773 SignalSubscriber *subscriber;
2774 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
2775 if (subscriber->user_data_free_func != NULL)
2776 subscriber->user_data_free_func (subscriber->user_data);
2777 if (subscriber->context != NULL)
2778 g_main_context_unref (subscriber->context);
2781 g_array_free (subscribers, TRUE);
2784 /* ---------------------------------------------------------------------------------------------------- */
2788 guint subscription_id;
2789 GDBusSignalCallback callback;
2791 GDBusMessage *message;
2792 GDBusConnection *connection;
2793 const gchar *sender;
2795 const gchar *interface;
2796 const gchar *member;
2799 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
2803 emit_signal_instance_in_idle_cb (gpointer data)
2805 SignalInstance *signal_instance = data;
2806 GVariant *parameters;
2807 gboolean has_subscription;
2809 parameters = g_dbus_message_get_body (signal_instance->message);
2810 if (parameters == NULL)
2812 parameters = g_variant_new ("()");
2813 g_variant_ref_sink (parameters);
2817 g_variant_ref_sink (parameters);
2821 g_debug ("in emit_signal_instance_in_idle_cb (sender=%s path=%s interface=%s member=%s params=%s)",
2822 signal_instance->sender,
2823 signal_instance->path,
2824 signal_instance->interface,
2825 signal_instance->member,
2826 g_variant_print (parameters, TRUE));
2829 /* Careful here, don't do the callback if we no longer has the subscription */
2830 CONNECTION_LOCK (signal_instance->connection);
2831 has_subscription = FALSE;
2832 if (g_hash_table_lookup (signal_instance->connection->priv->map_id_to_signal_data,
2833 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
2834 has_subscription = TRUE;
2835 CONNECTION_UNLOCK (signal_instance->connection);
2837 if (has_subscription)
2838 signal_instance->callback (signal_instance->connection,
2839 signal_instance->sender,
2840 signal_instance->path,
2841 signal_instance->interface,
2842 signal_instance->member,
2844 signal_instance->user_data);
2846 if (parameters != NULL)
2847 g_variant_unref (parameters);
2853 signal_instance_free (SignalInstance *signal_instance)
2855 g_object_unref (signal_instance->message);
2856 g_object_unref (signal_instance->connection);
2857 g_free (signal_instance);
2860 /* called in message handler thread WITH lock held */
2862 schedule_callbacks (GDBusConnection *connection,
2863 GPtrArray *signal_data_array,
2864 GDBusMessage *message,
2865 const gchar *sender)
2868 const gchar *interface;
2869 const gchar *member;
2878 interface = g_dbus_message_get_interface (message);
2879 member = g_dbus_message_get_member (message);
2880 path = g_dbus_message_get_path (message);
2881 arg0 = g_dbus_message_get_arg0 (message);
2884 g_debug ("sender = `%s'", sender);
2885 g_debug ("interface = `%s'", interface);
2886 g_debug ("member = `%s'", member);
2887 g_debug ("path = `%s'", path);
2888 g_debug ("arg0 = `%s'", arg0);
2891 /* TODO: if this is slow, then we can change signal_data_array into
2892 * map_object_path_to_signal_data_array or something.
2894 for (n = 0; n < signal_data_array->len; n++)
2896 SignalData *signal_data = signal_data_array->pdata[n];
2898 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
2901 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
2904 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
2907 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
2910 for (m = 0; m < signal_data->subscribers->len; m++)
2912 SignalSubscriber *subscriber;
2913 GSource *idle_source;
2914 SignalInstance *signal_instance;
2916 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
2918 signal_instance = g_new0 (SignalInstance, 1);
2919 signal_instance->subscription_id = subscriber->id;
2920 signal_instance->callback = subscriber->callback;
2921 signal_instance->user_data = subscriber->user_data;
2922 signal_instance->message = g_object_ref (message);
2923 signal_instance->connection = g_object_ref (connection);
2924 signal_instance->sender = sender;
2925 signal_instance->path = path;
2926 signal_instance->interface = interface;
2927 signal_instance->member = member;
2929 idle_source = g_idle_source_new ();
2930 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
2931 g_source_set_callback (idle_source,
2932 emit_signal_instance_in_idle_cb,
2934 (GDestroyNotify) signal_instance_free);
2935 g_source_attach (idle_source, subscriber->context);
2936 g_source_unref (idle_source);
2941 /* called in message handler thread with lock held */
2943 distribute_signals (GDBusConnection *connection,
2944 GDBusMessage *message)
2946 GPtrArray *signal_data_array;
2947 const gchar *sender;
2949 sender = g_dbus_message_get_sender (message);
2951 /* collect subscribers that match on sender */
2954 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, sender);
2955 if (signal_data_array != NULL)
2956 schedule_callbacks (connection, signal_data_array, message, sender);
2959 /* collect subscribers not matching on sender */
2960 signal_data_array = g_hash_table_lookup (connection->priv->map_sender_to_signal_data_array, "");
2961 if (signal_data_array != NULL)
2962 schedule_callbacks (connection, signal_data_array, message, sender);
2965 /* ---------------------------------------------------------------------------------------------------- */
2967 /* only called from finalize(), removes all subscriptions */
2969 purge_all_signal_subscriptions (GDBusConnection *connection)
2971 GHashTableIter iter;
2974 GArray *subscribers;
2977 ids = g_array_new (FALSE, FALSE, sizeof (guint));
2978 g_hash_table_iter_init (&iter, connection->priv->map_id_to_signal_data);
2979 while (g_hash_table_iter_next (&iter, &key, NULL))
2981 guint subscription_id = GPOINTER_TO_UINT (key);
2982 g_array_append_val (ids, subscription_id);
2985 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
2986 for (n = 0; n < ids->len; n++)
2988 guint subscription_id = g_array_index (ids, guint, n);
2989 unsubscribe_id_internal (connection,
2993 g_array_free (ids, TRUE);
2995 /* call GDestroyNotify without lock held */
2996 for (n = 0; n < subscribers->len; n++)
2998 SignalSubscriber *subscriber;
2999 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3000 if (subscriber->user_data_free_func != NULL)
3001 subscriber->user_data_free_func (subscriber->user_data);
3002 if (subscriber->context != NULL)
3003 g_main_context_unref (subscriber->context);
3006 g_array_free (subscribers, TRUE);
3009 /* ---------------------------------------------------------------------------------------------------- */
3011 struct ExportedObject
3014 GDBusConnection *connection;
3016 /* maps gchar* -> ExportedInterface* */
3017 GHashTable *map_if_name_to_ei;
3020 /* only called with lock held */
3022 exported_object_free (ExportedObject *eo)
3024 g_free (eo->object_path);
3025 g_hash_table_unref (eo->map_if_name_to_ei);
3034 gchar *interface_name;
3035 const GDBusInterfaceVTable *vtable;
3036 const GDBusInterfaceInfo *introspection_data;
3038 GMainContext *context;
3040 GDestroyNotify user_data_free_func;
3041 } ExportedInterface;
3043 /* called with lock held */
3045 exported_interface_free (ExportedInterface *ei)
3047 if (ei->user_data_free_func != NULL)
3048 /* TODO: push to thread-default mainloop */
3049 ei->user_data_free_func (ei->user_data);
3051 if (ei->context != NULL)
3052 g_main_context_unref (ei->context);
3054 g_free (ei->interface_name);
3058 /* ---------------------------------------------------------------------------------------------------- */
3062 GDBusConnection *connection;
3063 GDBusMessage *message;
3065 const char *property_name;
3066 const GDBusInterfaceVTable *vtable;
3067 const GDBusInterfaceInfo *interface_info;
3068 const GDBusPropertyInfo *property_info;
3072 property_data_free (PropertyData *data)
3074 g_object_unref (data->connection);
3075 g_object_unref (data->message);
3079 /* called in thread where object was registered - no locks held */
3081 invoke_get_property_in_idle_cb (gpointer _data)
3083 PropertyData *data = _data;
3086 GDBusMessage *reply;
3089 value = data->vtable->get_property (data->connection,
3090 g_dbus_message_get_sender (data->message),
3091 g_dbus_message_get_path (data->message),
3092 data->interface_info->name,
3093 data->property_name,
3100 g_assert_no_error (error);
3102 g_variant_ref_sink (value);
3103 reply = g_dbus_message_new_method_reply (data->message);
3104 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3105 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3106 g_variant_unref (value);
3107 g_object_unref (reply);
3111 gchar *dbus_error_name;
3113 g_assert (error != NULL);
3115 dbus_error_name = g_dbus_error_encode_gerror (error);
3116 reply = g_dbus_message_new_method_error_literal (data->message,
3119 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3120 g_free (dbus_error_name);
3121 g_error_free (error);
3122 g_object_unref (reply);
3128 /* called in thread where object was registered - no locks held */
3130 invoke_set_property_in_idle_cb (gpointer _data)
3132 PropertyData *data = _data;
3134 GDBusMessage *reply;
3140 g_variant_get (g_dbus_message_get_body (data->message),
3146 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3147 * of the given value is wrong
3149 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3151 reply = g_dbus_message_new_method_error (data->message,
3152 "org.freedesktop.DBus.Error.InvalidArgs",
3153 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3154 data->property_info->name,
3155 data->property_info->signature,
3156 g_variant_get_type_string (value));
3160 if (!data->vtable->set_property (data->connection,
3161 g_dbus_message_get_sender (data->message),
3162 g_dbus_message_get_path (data->message),
3163 data->interface_info->name,
3164 data->property_name,
3169 gchar *dbus_error_name;
3170 g_assert (error != NULL);
3171 dbus_error_name = g_dbus_error_encode_gerror (error);
3172 reply = g_dbus_message_new_method_error_literal (data->message,
3175 g_free (dbus_error_name);
3176 g_error_free (error);
3180 reply = g_dbus_message_new_method_reply (data->message);
3184 g_assert (reply != NULL);
3185 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3186 g_object_unref (reply);
3191 /* called with lock held */
3193 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3194 GDBusMessage *message,
3196 const GDBusInterfaceInfo *introspection_data,
3197 const GDBusInterfaceVTable *vtable,
3198 GMainContext *main_context,
3202 const char *interface_name;
3203 const char *property_name;
3204 const GDBusPropertyInfo *property_info;
3205 GSource *idle_source;
3206 PropertyData *property_data;
3207 GDBusMessage *reply;
3212 g_variant_get (g_dbus_message_get_body (message),
3217 g_variant_get (g_dbus_message_get_body (message),
3226 if (vtable == NULL || vtable->get_property == NULL)
3231 if (vtable == NULL || vtable->set_property == NULL)
3235 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3237 property_info = NULL;
3239 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3240 property_info = g_dbus_interface_info_lookup_property (introspection_data, property_name);
3241 if (property_info == NULL)
3243 reply = g_dbus_message_new_method_error (message,
3244 "org.freedesktop.DBus.Error.InvalidArgs",
3245 _("No such property `%s'"),
3247 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3248 g_object_unref (reply);
3253 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3255 reply = g_dbus_message_new_method_error (message,
3256 "org.freedesktop.DBus.Error.InvalidArgs",
3257 _("Property `%s' is not readable"),
3259 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3260 g_object_unref (reply);
3264 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3266 reply = g_dbus_message_new_method_error (message,
3267 "org.freedesktop.DBus.Error.InvalidArgs",
3268 _("Property `%s' is not writable"),
3270 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3271 g_object_unref (reply);
3276 /* ok, got the property info - call user code in an idle handler */
3277 property_data = g_new0 (PropertyData, 1);
3278 property_data->connection = g_object_ref (connection);
3279 property_data->message = g_object_ref (message);
3280 property_data->user_data = user_data;
3281 property_data->property_name = property_name;
3282 property_data->vtable = vtable;
3283 property_data->interface_info = introspection_data;
3284 property_data->property_info = property_info;
3286 idle_source = g_idle_source_new ();
3287 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3288 g_source_set_callback (idle_source,
3289 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3291 (GDestroyNotify) property_data_free);
3292 g_source_attach (idle_source, main_context);
3293 g_source_unref (idle_source);
3301 /* called with lock held */
3303 handle_getset_property (GDBusConnection *connection,
3305 GDBusMessage *message,
3308 ExportedInterface *ei;
3310 const char *interface_name;
3311 const char *property_name;
3316 g_variant_get (g_dbus_message_get_body (message),
3321 g_variant_get (g_dbus_message_get_body (message),
3327 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3328 * no such interface registered
3330 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3333 GDBusMessage *reply;
3334 reply = g_dbus_message_new_method_error (message,
3335 "org.freedesktop.DBus.Error.InvalidArgs",
3336 _("No such interface `%s'"),
3338 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3339 g_object_unref (reply);
3344 handled = validate_and_maybe_schedule_property_getset (eo->connection,
3347 ei->introspection_data,
3355 /* ---------------------------------------------------------------------------------------------------- */
3359 GDBusConnection *connection;
3360 GDBusMessage *message;
3362 const GDBusInterfaceVTable *vtable;
3363 const GDBusInterfaceInfo *interface_info;
3364 } PropertyGetAllData;
3367 property_get_all_data_free (PropertyData *data)
3369 g_object_unref (data->connection);
3370 g_object_unref (data->message);
3374 /* called in thread where object was registered - no locks held */
3376 invoke_get_all_properties_in_idle_cb (gpointer _data)
3378 PropertyGetAllData *data = _data;
3379 GVariantBuilder *builder;
3383 GDBusMessage *reply;
3388 /* TODO: Right now we never fail this call - we just omit values if
3389 * a get_property() call is failing.
3391 * We could fail the whole call if just a single get_property() call
3392 * returns an error. We need clarification in the D-Bus spec about this.
3394 builder = g_variant_builder_new (G_VARIANT_TYPE_ARRAY);
3395 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
3397 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
3400 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3403 value = data->vtable->get_property (data->connection,
3404 g_dbus_message_get_sender (data->message),
3405 g_dbus_message_get_path (data->message),
3406 data->interface_info->name,
3407 property_info->name,
3414 g_variant_ref_sink (value);
3415 g_variant_builder_add (builder,
3417 property_info->name,
3419 g_variant_unref (value);
3421 result = g_variant_builder_end (builder);
3423 builder = g_variant_builder_new (G_VARIANT_TYPE_TUPLE);
3424 g_variant_builder_add_value (builder, result); /* steals result since result is floating */
3425 packed = g_variant_builder_end (builder);
3427 reply = g_dbus_message_new_method_reply (data->message);
3428 g_dbus_message_set_body (reply, packed);
3429 g_dbus_connection_send_message (data->connection, reply, NULL, NULL);
3430 g_object_unref (reply);
3435 /* called with lock held */
3437 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
3438 GDBusMessage *message,
3439 const GDBusInterfaceInfo *introspection_data,
3440 const GDBusInterfaceVTable *vtable,
3441 GMainContext *main_context,
3445 const char *interface_name;
3446 GSource *idle_source;
3447 PropertyGetAllData *property_get_all_data;
3451 g_variant_get (g_dbus_message_get_body (message),
3455 if (vtable == NULL || vtable->get_property == NULL)
3458 /* ok, got the property info - call user in an idle handler */
3459 property_get_all_data = g_new0 (PropertyGetAllData, 1);
3460 property_get_all_data->connection = g_object_ref (connection);
3461 property_get_all_data->message = g_object_ref (message);
3462 property_get_all_data->user_data = user_data;
3463 property_get_all_data->vtable = vtable;
3464 property_get_all_data->interface_info = introspection_data;
3466 idle_source = g_idle_source_new ();
3467 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3468 g_source_set_callback (idle_source,
3469 invoke_get_all_properties_in_idle_cb,
3470 property_get_all_data,
3471 (GDestroyNotify) property_get_all_data_free);
3472 g_source_attach (idle_source, main_context);
3473 g_source_unref (idle_source);
3481 /* called with lock held */
3483 handle_get_all_properties (GDBusConnection *connection,
3485 GDBusMessage *message)
3487 ExportedInterface *ei;
3489 const char *interface_name;
3493 g_variant_get (g_dbus_message_get_body (message),
3497 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3498 * no such interface registered
3500 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3503 GDBusMessage *reply;
3504 reply = g_dbus_message_new_method_error (message,
3505 "org.freedesktop.DBus.Error.InvalidArgs",
3506 _("No such interface"),
3508 g_dbus_connection_send_message_unlocked (eo->connection, reply, NULL, NULL);
3509 g_object_unref (reply);
3514 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
3516 ei->introspection_data,
3524 /* ---------------------------------------------------------------------------------------------------- */
3526 static const gchar introspect_header[] =
3527 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
3528 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
3529 "<!-- GDBus " PACKAGE_VERSION " -->\n"
3532 static const gchar introspect_tail[] =
3535 static const gchar introspect_standard_interfaces[] =
3536 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
3537 " <method name=\"Get\">\n"
3538 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3539 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3540 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
3542 " <method name=\"GetAll\">\n"
3543 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3544 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
3546 " <method name=\"Set\">\n"
3547 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
3548 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
3549 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
3551 " <signal name=\"PropertiesChanged\">\n"
3552 " <arg type=\"s\" name=\"interface_name\"/>\n"
3553 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
3554 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
3557 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
3558 " <method name=\"Introspect\">\n"
3559 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
3562 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
3563 " <method name=\"Ping\"/>\n"
3564 " <method name=\"GetMachineId\">\n"
3565 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
3570 introspect_append_header (GString *s)
3572 g_string_append (s, introspect_header);
3576 introspect_append_standard_interfaces (GString *s)
3578 g_string_append (s, introspect_standard_interfaces);
3582 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
3584 if (g_str_has_prefix (object_path, path) && strlen (object_path) >= path_len)
3590 begin = object_path + path_len;
3591 end = strchr (begin, '/');
3594 s = g_strndup (begin, end - begin);
3596 s = g_strdup (begin);
3598 if (g_hash_table_lookup (set, s) == NULL)
3599 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
3605 /* TODO: we want a nicer public interface for this */
3607 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
3612 GHashTableIter hash_iter;
3613 const gchar *object_path;
3619 CONNECTION_ENSURE_LOCK (connection);
3621 path_len = strlen (path);
3625 set = g_hash_table_new (g_str_hash, g_str_equal);
3627 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_eo);
3628 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3629 maybe_add_path (path, path_len, object_path, set);
3631 g_hash_table_iter_init (&hash_iter, connection->priv->map_object_path_to_es);
3632 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
3633 maybe_add_path (path, path_len, object_path, set);
3635 p = g_ptr_array_new ();
3636 keys = g_hash_table_get_keys (set);
3637 for (l = keys; l != NULL; l = l->next)
3638 g_ptr_array_add (p, l->data);
3639 g_hash_table_unref (set);
3642 g_ptr_array_add (p, NULL);
3643 ret = (gchar **) g_ptr_array_free (p, FALSE);
3648 g_dbus_connection_list_registered (GDBusConnection *connection,
3652 CONNECTION_LOCK (connection);
3653 ret = g_dbus_connection_list_registered_unlocked (connection, path);
3654 CONNECTION_UNLOCK (connection);
3658 /* called in message handler thread with lock held */
3660 handle_introspect (GDBusConnection *connection,
3662 GDBusMessage *message)
3666 GDBusMessage *reply;
3667 GHashTableIter hash_iter;
3668 ExportedInterface *ei;
3671 /* first the header with the standard interfaces */
3672 s = g_string_sized_new (sizeof (introspect_header) +
3673 sizeof (introspect_standard_interfaces) +
3674 sizeof (introspect_tail));
3675 introspect_append_header (s);
3676 introspect_append_standard_interfaces (s);
3678 /* then include the registered interfaces */
3679 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
3680 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
3681 g_dbus_interface_info_generate_xml (ei->introspection_data, 2, s);
3683 /* finally include nodes registered below us */
3684 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
3685 for (n = 0; registered != NULL && registered[n] != NULL; n++)
3686 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
3687 g_strfreev (registered);
3688 g_string_append (s, introspect_tail);
3690 reply = g_dbus_message_new_method_reply (message);
3691 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
3692 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3693 g_object_unref (reply);
3694 g_string_free (s, TRUE);
3699 /* called in thread where object was registered - no locks held */
3701 call_in_idle_cb (gpointer user_data)
3703 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
3704 GDBusInterfaceVTable *vtable;
3706 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
3707 g_assert (vtable != NULL && vtable->method_call != NULL);
3709 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
3710 g_dbus_method_invocation_get_sender (invocation),
3711 g_dbus_method_invocation_get_object_path (invocation),
3712 g_dbus_method_invocation_get_interface_name (invocation),
3713 g_dbus_method_invocation_get_method_name (invocation),
3714 g_dbus_method_invocation_get_parameters (invocation),
3715 g_object_ref (invocation),
3716 g_dbus_method_invocation_get_user_data (invocation));
3721 /* called in message handler thread with lock held */
3723 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
3724 GDBusMessage *message,
3725 const GDBusInterfaceInfo *introspection_data,
3726 const GDBusInterfaceVTable *vtable,
3727 GMainContext *main_context,
3730 GDBusMethodInvocation *invocation;
3731 const GDBusMethodInfo *method_info;
3732 GDBusMessage *reply;
3733 GVariant *parameters;
3734 GSource *idle_source;
3736 gchar *in_signature;
3740 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3741 method_info = g_dbus_interface_info_lookup_method (introspection_data, g_dbus_message_get_member (message));
3743 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
3744 * error to the caller
3746 if (method_info == NULL)
3748 reply = g_dbus_message_new_method_error (message,
3749 "org.freedesktop.DBus.Error.UnknownMethod",
3750 _("No such method `%s'"),
3751 g_dbus_message_get_member (message));
3752 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3753 g_object_unref (reply);
3758 /* Check that the incoming args are of the right type - if they are not, return
3759 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
3761 * TODO: might also be worth caching the combined signature.
3763 in_signature = _g_dbus_compute_complete_signature (method_info->in_args, FALSE);
3764 if (g_strcmp0 (g_dbus_message_get_signature (message), in_signature) != 0)
3766 reply = g_dbus_message_new_method_error (message,
3767 "org.freedesktop.DBus.Error.InvalidArgs",
3768 _("Signature of message, `%s', does not match expected signature `%s'"),
3769 g_dbus_message_get_signature (message),
3771 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
3772 g_object_unref (reply);
3773 g_free (in_signature);
3777 g_free (in_signature);
3779 parameters = g_dbus_message_get_body (message);
3780 if (parameters == NULL)
3782 parameters = g_variant_new ("()");
3783 g_variant_ref_sink (parameters);
3787 g_variant_ref (parameters);
3790 /* schedule the call in idle */
3791 invocation = g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
3792 g_dbus_message_get_path (message),
3793 g_dbus_message_get_interface (message),
3794 g_dbus_message_get_member (message),
3800 g_variant_unref (parameters);
3801 g_object_set_data (G_OBJECT (invocation),
3802 "g-dbus-interface-vtable",
3805 idle_source = g_idle_source_new ();
3806 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3807 g_source_set_callback (idle_source,
3811 g_source_attach (idle_source, main_context);
3812 g_source_unref (idle_source);
3820 /* ---------------------------------------------------------------------------------------------------- */
3822 /* called in message handler thread with lock held */
3824 obj_message_func (GDBusConnection *connection,
3826 GDBusMessage *message)
3828 const gchar *interface_name;
3829 const gchar *member;
3830 const gchar *signature;
3835 interface_name = g_dbus_message_get_interface (message);
3836 member = g_dbus_message_get_member (message);
3837 signature = g_dbus_message_get_signature (message);
3839 /* see if we have an interface for handling this call */
3840 if (interface_name != NULL)
3842 ExportedInterface *ei;
3843 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3846 /* we do - invoke the handler in idle in the right thread */
3848 /* handle no vtable or handler being present */
3849 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
3852 handled = validate_and_maybe_schedule_method_call (connection,
3854 ei->introspection_data,
3862 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
3863 g_strcmp0 (member, "Introspect") == 0 &&
3864 g_strcmp0 (signature, "") == 0)
3866 handled = handle_introspect (connection, eo, message);
3869 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3870 g_strcmp0 (member, "Get") == 0 &&
3871 g_strcmp0 (signature, "ss") == 0)
3873 handled = handle_getset_property (connection, eo, message, TRUE);
3876 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3877 g_strcmp0 (member, "Set") == 0 &&
3878 g_strcmp0 (signature, "ssv") == 0)
3880 handled = handle_getset_property (connection, eo, message, FALSE);
3883 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
3884 g_strcmp0 (member, "GetAll") == 0 &&
3885 g_strcmp0 (signature, "s") == 0)
3887 handled = handle_get_all_properties (connection, eo, message);
3896 * g_dbus_connection_register_object:
3897 * @connection: A #GDBusConnection.
3898 * @object_path: The object path to register at.
3899 * @introspection_data: Introspection data for the interface.
3900 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
3901 * @user_data: Data to pass to functions in @vtable.
3902 * @user_data_free_func: Function to call when the object path is unregistered.
3903 * @error: Return location for error or %NULL.
3905 * Registers callbacks for exported objects at @object_path with the
3906 * D-Bus interface that is described in @introspection_data.
3908 * Calls to functions in @vtable (and @user_data_free_func) will
3909 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
3910 * loop</link> of the thread you are calling this method from.
3912 * Note that all #GVariant values passed to functions in @vtable will match
3913 * the signature given in @introspection_data - if a remote caller passes
3914 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
3915 * is returned to the remote caller.
3917 * Additionally, if the remote caller attempts to invoke methods or
3918 * access properties not mentioned in @introspection_data the
3919 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
3920 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
3921 * are returned to the caller.
3923 * It is considered a programming error if the
3924 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
3925 * #GVariant of incorrect type.
3927 * If an existing callback is already registered at @object_path and
3928 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
3930 * GDBus automatically implements the standard D-Bus interfaces
3931 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
3932 * and org.freedesktop.Peer, so you don't have to implement those for
3933 * the objects you export. You <emphasis>can</emphasis> implement
3934 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
3935 * and setting of properties asynchronously.
3937 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
3939 * Returns: 0 if @error is set, otherwise a registration id (never 0)
3940 * that can be used with g_dbus_connection_unregister_object() .
3945 g_dbus_connection_register_object (GDBusConnection *connection,
3946 const gchar *object_path,
3947 const GDBusInterfaceInfo *introspection_data,
3948 const GDBusInterfaceVTable *vtable,
3950 GDestroyNotify user_data_free_func,
3954 ExportedInterface *ei;
3957 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3958 g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
3959 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
3960 g_return_val_if_fail (introspection_data != NULL, 0);
3961 g_return_val_if_fail (g_dbus_is_interface_name (introspection_data->name), 0);
3962 g_return_val_if_fail (error == NULL || *error == NULL, 0);
3966 CONNECTION_LOCK (connection);
3968 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
3971 eo = g_new0 (ExportedObject, 1);
3972 eo->object_path = g_strdup (object_path);
3973 eo->connection = connection;
3974 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
3977 (GDestroyNotify) exported_interface_free);
3978 g_hash_table_insert (connection->priv->map_object_path_to_eo, eo->object_path, eo);
3981 ei = g_hash_table_lookup (eo->map_if_name_to_ei, introspection_data->name);
3987 _("An object is already exported for the interface %s at %s"),
3988 introspection_data->name,
3993 ei = g_new0 (ExportedInterface, 1);
3994 ei->id = _global_registration_id++; /* TODO: overflow etc. */
3996 ei->user_data = user_data;
3997 ei->user_data_free_func = user_data_free_func;
3998 ei->vtable = vtable;
3999 ei->introspection_data = introspection_data;
4000 ei->interface_name = g_strdup (introspection_data->name);
4001 ei->context = g_main_context_get_thread_default ();
4002 if (ei->context != NULL)
4003 g_main_context_ref (ei->context);
4005 g_hash_table_insert (eo->map_if_name_to_ei,
4006 (gpointer) ei->interface_name,
4008 g_hash_table_insert (connection->priv->map_id_to_ei,
4009 GUINT_TO_POINTER (ei->id),
4015 CONNECTION_UNLOCK (connection);
4021 * g_dbus_connection_unregister_object:
4022 * @connection: A #GDBusConnection.
4023 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4025 * Unregisters an object.
4027 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4032 g_dbus_connection_unregister_object (GDBusConnection *connection,
4033 guint registration_id)
4035 ExportedInterface *ei;
4039 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4043 CONNECTION_LOCK (connection);
4045 ei = g_hash_table_lookup (connection->priv->map_id_to_ei,
4046 GUINT_TO_POINTER (registration_id));
4052 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4053 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4054 /* unregister object path if we have no more exported interfaces */
4055 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4056 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_eo,
4062 CONNECTION_UNLOCK (connection);
4067 /* ---------------------------------------------------------------------------------------------------- */
4070 * g_dbus_connection_emit_signal:
4071 * @connection: A #GDBusConnection.
4072 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4073 * @object_path: Path of remote object.
4074 * @interface_name: D-Bus interface to emit a signal on.
4075 * @signal_name: The name of the signal to emit.
4076 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4077 * @error: Return location for error or %NULL.
4081 * If the parameters GVariant is floating, it is consumed.
4083 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4085 * Returns: %TRUE unless @error is set.
4090 g_dbus_connection_emit_signal (GDBusConnection *connection,
4091 const gchar *destination_bus_name,
4092 const gchar *object_path,
4093 const gchar *interface_name,
4094 const gchar *signal_name,
4095 GVariant *parameters,
4098 GDBusMessage *message;
4104 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4105 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4106 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4107 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4108 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4109 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4111 message = g_dbus_message_new_signal (object_path,
4115 if (destination_bus_name != NULL)
4116 g_dbus_message_set_header (message,
4117 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4118 g_variant_new_string (destination_bus_name));
4120 if (parameters != NULL)
4121 g_dbus_message_set_body (message, parameters);
4123 ret = g_dbus_connection_send_message (connection, message, NULL, error);
4124 g_object_unref (message);
4130 add_call_flags (GDBusMessage *message,
4131 GDBusCallFlags flags)
4133 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4134 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4138 * g_dbus_connection_call:
4139 * @connection: A #GDBusConnection.
4140 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4141 * @object_path: Path of remote object.
4142 * @interface_name: D-Bus interface to invoke method on.
4143 * @method_name: The name of the method to invoke.
4144 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4145 * @flags: Flags from the #GDBusCallFlags enumeration.
4146 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4147 * @cancellable: A #GCancellable or %NULL.
4148 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4149 * care about the result of the method invocation.
4150 * @user_data: The data to pass to @callback.
4152 * Asynchronously invokes the @method_name method on the
4153 * @interface_name D-Bus interface on the remote object at
4154 * @object_path owned by @bus_name.
4156 * If @connection is closed then the operation will fail with
4157 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
4158 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
4159 * not compatible with the D-Bus protocol, the operation fails with
4160 * %G_IO_ERROR_INVALID_ARGUMENT.
4162 * If the @parameters #GVariant is floating, it is consumed. This allows
4163 * convenient 'inline' use of g_variant_new(), e.g.:
4165 * g_dbus_connection_call (connection,
4166 * "org.freedesktop.StringThings",
4167 * "/org/freedesktop/StringThings",
4168 * "org.freedesktop.StringThings",
4170 * g_variant_new ("(ss)",
4173 * G_DBUS_CALL_FLAGS_NONE,
4176 * (GAsyncReadyCallback) two_strings_done,
4180 * This is an asynchronous method. When the operation is finished, @callback will be invoked
4181 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
4182 * of the thread you are calling this method from. You can then call
4183 * g_dbus_connection_call_finish() to get the result of the operation.
4184 * See g_dbus_connection_call_sync() for the synchronous version of this
4190 g_dbus_connection_call (GDBusConnection *connection,
4191 const gchar *bus_name,
4192 const gchar *object_path,
4193 const gchar *interface_name,
4194 const gchar *method_name,
4195 GVariant *parameters,
4196 GDBusCallFlags flags,
4198 GCancellable *cancellable,
4199 GAsyncReadyCallback callback,
4202 GDBusMessage *message;
4204 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
4205 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
4206 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
4207 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
4208 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
4209 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
4210 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
4212 message = g_dbus_message_new_method_call (bus_name,
4216 add_call_flags (message, flags);
4217 if (parameters != NULL)
4218 g_dbus_message_set_body (message, parameters);
4220 g_dbus_connection_send_message_with_reply (connection,
4223 NULL, /* volatile guint32 *out_serial */
4228 if (message != NULL)
4229 g_object_unref (message);
4233 decode_method_reply (GDBusMessage *reply,
4239 switch (g_dbus_message_get_message_type (reply))
4241 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4242 result = g_dbus_message_get_body (reply);
4245 result = g_variant_new ("()");
4246 g_variant_ref_sink (result);
4250 g_variant_ref (result);
4254 case G_DBUS_MESSAGE_TYPE_ERROR:
4255 g_dbus_message_to_gerror (reply, error);
4259 g_assert_not_reached ();
4267 * g_dbus_connection_call_finish:
4268 * @connection: A #GDBusConnection.
4269 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
4270 * @error: Return location for error or %NULL.
4272 * Finishes an operation started with g_dbus_connection_call().
4274 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4275 * return values. Free with g_variant_unref().
4280 g_dbus_connection_call_finish (GDBusConnection *connection,
4284 GDBusMessage *reply;
4287 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4288 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
4289 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
4293 reply = g_dbus_connection_send_message_with_reply_finish (connection, res, error);
4297 result = decode_method_reply (reply, error);
4299 g_object_unref (reply);
4305 /* ---------------------------------------------------------------------------------------------------- */
4308 * g_dbus_connection_call_sync:
4309 * @connection: A #GDBusConnection.
4310 * @bus_name: A unique or well-known bus name.
4311 * @object_path: Path of remote object.
4312 * @interface_name: D-Bus interface to invoke method on.
4313 * @method_name: The name of the method to invoke.
4314 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4315 * @flags: Flags from the #GDBusCallFlags enumeration.
4316 * @timeout_msec: The timeout in milliseconds or -1 to use the default timeout.
4317 * @cancellable: A #GCancellable or %NULL.
4318 * @error: Return location for error or %NULL.
4320 * Synchronously invokes the @method_name method on the
4321 * @interface_name D-Bus interface on the remote object at
4322 * @object_path owned by @bus_name.
4324 * If @connection is closed then the operation will fail with
4325 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
4326 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
4327 * contains a value not compatible with the D-Bus protocol, the operation
4328 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
4330 * If the @parameters #GVariant is floating, it is consumed.
4331 * This allows convenient 'inline' use of g_variant_new(), e.g.:
4333 * g_dbus_connection_call_sync (connection,
4334 * "org.freedesktop.StringThings",
4335 * "/org/freedesktop/StringThings",
4336 * "org.freedesktop.StringThings",
4338 * g_variant_new ("(ss)",
4341 * G_DBUS_CALL_FLAGS_NONE,
4347 * The calling thread is blocked until a reply is received. See
4348 * g_dbus_connection_call() for the asynchronous version of
4351 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
4352 * return values. Free with g_variant_unref().
4357 g_dbus_connection_call_sync (GDBusConnection *connection,
4358 const gchar *bus_name,
4359 const gchar *object_path,
4360 const gchar *interface_name,
4361 const gchar *method_name,
4362 GVariant *parameters,
4363 GDBusCallFlags flags,
4365 GCancellable *cancellable,
4368 GDBusMessage *message;
4369 GDBusMessage *reply;
4376 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
4377 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
4378 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
4379 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
4380 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
4381 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
4382 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
4384 message = g_dbus_message_new_method_call (bus_name,
4388 add_call_flags (message, flags);
4389 if (parameters != NULL)
4390 g_dbus_message_set_body (message, parameters);
4392 reply = g_dbus_connection_send_message_with_reply_sync (connection,
4395 NULL, /* volatile guint32 *out_serial */
4402 result = decode_method_reply (reply, error);
4405 if (message != NULL)
4406 g_object_unref (message);
4408 g_object_unref (reply);
4413 /* ---------------------------------------------------------------------------------------------------- */
4415 struct ExportedSubtree
4419 GDBusConnection *connection;
4420 const GDBusSubtreeVTable *vtable;
4421 GDBusSubtreeFlags flags;
4423 GMainContext *context;
4425 GDestroyNotify user_data_free_func;
4429 exported_subtree_free (ExportedSubtree *es)
4431 if (es->user_data_free_func != NULL)
4432 /* TODO: push to thread-default mainloop */
4433 es->user_data_free_func (es->user_data);
4435 if (es->context != NULL)
4436 g_main_context_unref (es->context);
4438 g_free (es->object_path);
4442 /* called without lock held */
4444 handle_subtree_introspect (GDBusConnection *connection,
4445 ExportedSubtree *es,
4446 GDBusMessage *message)
4450 GDBusMessage *reply;
4453 const gchar *sender;
4454 const gchar *requested_object_path;
4455 const gchar *requested_node;
4456 GPtrArray *interfaces;
4458 gchar **subnode_paths;
4462 requested_object_path = g_dbus_message_get_path (message);
4463 sender = g_dbus_message_get_sender (message);
4464 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4466 s = g_string_new (NULL);
4467 introspect_append_header (s);
4469 /* Strictly we don't need the children in dynamic mode, but we avoid the
4470 * conditionals to preserve code clarity
4472 children = es->vtable->enumerate (es->connection,
4479 requested_node = strrchr (requested_object_path, '/') + 1;
4481 /* Assert existence of object if we are not dynamic */
4482 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4483 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4488 requested_node = "/";
4491 interfaces = es->vtable->introspect (es->connection,
4496 if (interfaces != NULL)
4498 if (interfaces->len > 0)
4500 /* we're in business */
4501 introspect_append_standard_interfaces (s);
4503 for (n = 0; n < interfaces->len; n++)
4505 const GDBusInterfaceInfo *interface_info = interfaces->pdata[n];
4506 g_dbus_interface_info_generate_xml (interface_info, 2, s);
4509 g_ptr_array_unref (interfaces);
4512 /* then include <node> entries from the Subtree for the root */
4515 for (n = 0; children != NULL && children[n] != NULL; n++)
4516 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
4519 /* finally include nodes registered below us */
4520 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
4521 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
4522 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
4523 g_strfreev (subnode_paths);
4525 g_string_append (s, "</node>\n");
4527 reply = g_dbus_message_new_method_reply (message);
4528 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4529 g_dbus_connection_send_message (connection, reply, NULL, NULL);
4530 g_object_unref (reply);
4535 g_string_free (s, TRUE);
4536 g_strfreev (children);
4540 /* called without lock held */
4542 handle_subtree_method_invocation (GDBusConnection *connection,
4543 ExportedSubtree *es,
4544 GDBusMessage *message)
4547 const gchar *sender;
4548 const gchar *interface_name;
4549 const gchar *member;
4550 const gchar *signature;
4551 const gchar *requested_object_path;
4552 const gchar *requested_node;
4555 const GDBusInterfaceInfo *introspection_data;
4556 const GDBusInterfaceVTable *interface_vtable;
4557 gpointer interface_user_data;
4559 GPtrArray *interfaces;
4560 gboolean is_property_get;
4561 gboolean is_property_set;
4562 gboolean is_property_get_all;
4567 requested_object_path = g_dbus_message_get_path (message);
4568 sender = g_dbus_message_get_sender (message);
4569 interface_name = g_dbus_message_get_interface (message);
4570 member = g_dbus_message_get_member (message);
4571 signature = g_dbus_message_get_signature (message);
4572 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
4574 is_property_get = FALSE;
4575 is_property_set = FALSE;
4576 is_property_get_all = FALSE;
4577 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
4579 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
4580 is_property_get = TRUE;
4581 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
4582 is_property_set = TRUE;
4583 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
4584 is_property_get_all = TRUE;
4587 children = es->vtable->enumerate (es->connection,
4594 requested_node = strrchr (requested_object_path, '/') + 1;
4596 /* If not dynamic, skip if requested node is not part of children */
4597 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
4598 !_g_strv_has_string ((const gchar * const *) children, requested_node))
4603 requested_node = "/";
4606 /* get introspection data for the node */
4607 interfaces = es->vtable->introspect (es->connection,
4609 requested_object_path,
4612 g_assert (interfaces != NULL);
4613 introspection_data = NULL;
4614 for (n = 0; n < interfaces->len; n++)
4616 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4617 if (g_strcmp0 (id_n->name, interface_name) == 0)
4618 introspection_data = id_n;
4621 /* dispatch the call if the user wants to handle it */
4622 if (introspection_data != NULL)
4624 /* figure out where to dispatch the method call */
4625 interface_user_data = NULL;
4626 interface_vtable = es->vtable->dispatch (es->connection,
4631 &interface_user_data,
4633 if (interface_vtable == NULL)
4636 CONNECTION_LOCK (connection);
4637 handled = validate_and_maybe_schedule_method_call (es->connection,
4642 interface_user_data);
4643 CONNECTION_UNLOCK (connection);
4645 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
4646 else if (is_property_get || is_property_set || is_property_get_all)
4648 if (is_property_get)
4649 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
4650 else if (is_property_set)
4651 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
4652 else if (is_property_get_all)
4653 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
4655 g_assert_not_reached ();
4657 /* see if the object supports this interface at all */
4658 for (n = 0; n < interfaces->len; n++)
4660 const GDBusInterfaceInfo *id_n = (const GDBusInterfaceInfo *) interfaces->pdata[n];
4661 if (g_strcmp0 (id_n->name, interface_name) == 0)
4662 introspection_data = id_n;
4665 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
4666 * claims it won't support the interface
4668 if (introspection_data == NULL)
4670 GDBusMessage *reply;
4671 reply = g_dbus_message_new_method_error (message,
4672 "org.freedesktop.DBus.Error.InvalidArgs",
4673 _("No such interface `%s'"),
4675 g_dbus_connection_send_message (es->connection, reply, NULL, NULL);
4676 g_object_unref (reply);
4681 /* figure out where to dispatch the property get/set/getall calls */
4682 interface_user_data = NULL;
4683 interface_vtable = es->vtable->dispatch (es->connection,
4688 &interface_user_data,
4690 if (interface_vtable == NULL)
4693 if (is_property_get || is_property_set)
4695 CONNECTION_LOCK (connection);
4696 handled = validate_and_maybe_schedule_property_getset (es->connection,
4702 interface_user_data);
4703 CONNECTION_UNLOCK (connection);
4705 else if (is_property_get_all)
4707 CONNECTION_LOCK (connection);
4708 handled = validate_and_maybe_schedule_property_get_all (es->connection,
4713 interface_user_data);
4714 CONNECTION_UNLOCK (connection);
4719 if (interfaces != NULL)
4720 g_ptr_array_unref (interfaces);
4721 g_strfreev (children);
4727 GDBusMessage *message;
4728 ExportedSubtree *es;
4729 } SubtreeDeferredData;
4732 subtree_deferred_data_free (SubtreeDeferredData *data)
4734 g_object_unref (data->message);
4738 /* called without lock held in the thread where the caller registered the subtree */
4740 process_subtree_vtable_message_in_idle_cb (gpointer _data)
4742 SubtreeDeferredData *data = _data;
4747 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
4748 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
4749 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
4750 handled = handle_subtree_introspect (data->es->connection,
4754 handled = handle_subtree_method_invocation (data->es->connection,
4760 CONNECTION_LOCK (data->es->connection);
4761 handled = handle_generic_unlocked (data->es->connection, data->message);
4762 CONNECTION_UNLOCK (data->es->connection);
4765 /* if we couldn't handle the request, just bail with the UnknownMethod error */
4768 GDBusMessage *reply;
4769 reply = g_dbus_message_new_method_error (data->message,
4770 "org.freedesktop.DBus.Error.UnknownMethod",
4771 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
4772 g_dbus_message_get_member (data->message),
4773 g_dbus_message_get_interface (data->message),
4774 g_dbus_message_get_signature (data->message));
4775 g_dbus_connection_send_message (data->es->connection, reply, NULL, NULL);
4776 g_object_unref (reply);
4782 /* called in message handler thread with lock held */
4784 subtree_message_func (GDBusConnection *connection,
4785 ExportedSubtree *es,
4786 GDBusMessage *message)
4788 GSource *idle_source;
4789 SubtreeDeferredData *data;
4791 data = g_new0 (SubtreeDeferredData, 1);
4792 data->message = g_object_ref (message);
4795 /* defer this call to an idle handler in the right thread */
4796 idle_source = g_idle_source_new ();
4797 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
4798 g_source_set_callback (idle_source,
4799 process_subtree_vtable_message_in_idle_cb,
4801 (GDestroyNotify) subtree_deferred_data_free);
4802 g_source_attach (idle_source, es->context);
4803 g_source_unref (idle_source);
4805 /* since we own the entire subtree, handlers for objects not in the subtree have been
4806 * tried already by libdbus-1 - so we just need to ensure that we're always going
4807 * to reply to the message
4813 * g_dbus_connection_register_subtree:
4814 * @connection: A #GDBusConnection.
4815 * @object_path: The object path to register the subtree at.
4816 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
4817 * @flags: Flags used to fine tune the behavior of the subtree.
4818 * @user_data: Data to pass to functions in @vtable.
4819 * @user_data_free_func: Function to call when the subtree is unregistered.
4820 * @error: Return location for error or %NULL.
4822 * Registers a whole subtree of <quote>dynamic</quote> objects.
4824 * The @enumerate and @introspection functions in @vtable are used to
4825 * convey, to remote callers, what nodes exist in the subtree rooted
4828 * When handling remote calls into any node in the subtree, first the
4829 * @enumerate function is used to check if the node exists. If the node exists
4830 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
4831 * the @introspection function is used to check if the node supports the
4832 * requested method. If so, the @dispatch function is used to determine
4833 * where to dispatch the call. The collected #GDBusInterfaceVTable and
4834 * #gpointer will be used to call into the interface vtable for processing
4837 * All calls into user-provided code will be invoked in the <link
4838 * linkend="g-main-context-push-thread-default">thread-default main
4839 * loop</link> of the thread you are calling this method from.
4841 * If an existing subtree is already registered at @object_path or
4842 * then @error is set to #G_IO_ERROR_EXISTS.
4844 * Note that it is valid to register regular objects (using
4845 * g_dbus_connection_register_object()) in a subtree registered with
4846 * g_dbus_connection_register_subtree() - if so, the subtree handler
4847 * is tried as the last resort. One way to think about a subtree
4848 * handler is to consider it a <quote>fallback handler</quote>
4849 * for object paths not registered via g_dbus_connection_register_object()
4850 * or other bindings.
4852 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
4854 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
4855 * that can be used with g_dbus_connection_unregister_subtree() .
4860 g_dbus_connection_register_subtree (GDBusConnection *connection,
4861 const gchar *object_path,
4862 const GDBusSubtreeVTable *vtable,
4863 GDBusSubtreeFlags flags,
4865 GDestroyNotify user_data_free_func,
4869 ExportedSubtree *es;
4871 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4872 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4873 g_return_val_if_fail (vtable != NULL, 0);
4874 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4878 CONNECTION_LOCK (connection);
4880 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
4886 _("A subtree is already exported for %s"),
4891 es = g_new0 (ExportedSubtree, 1);
4892 es->object_path = g_strdup (object_path);
4893 es->connection = connection;
4895 es->vtable = vtable;
4897 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
4898 es->user_data = user_data;
4899 es->user_data_free_func = user_data_free_func;
4900 es->context = g_main_context_get_thread_default ();
4901 if (es->context != NULL)
4902 g_main_context_ref (es->context);
4904 g_hash_table_insert (connection->priv->map_object_path_to_es, es->object_path, es);
4905 g_hash_table_insert (connection->priv->map_id_to_es,
4906 GUINT_TO_POINTER (es->id),
4912 CONNECTION_UNLOCK (connection);
4917 /* ---------------------------------------------------------------------------------------------------- */
4920 * g_dbus_connection_unregister_subtree:
4921 * @connection: A #GDBusConnection.
4922 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
4924 * Unregisters a subtree.
4926 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
4931 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
4932 guint registration_id)
4934 ExportedSubtree *es;
4937 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4941 CONNECTION_LOCK (connection);
4943 es = g_hash_table_lookup (connection->priv->map_id_to_es,
4944 GUINT_TO_POINTER (registration_id));
4948 g_warn_if_fail (g_hash_table_remove (connection->priv->map_id_to_es, GUINT_TO_POINTER (es->id)));
4949 g_warn_if_fail (g_hash_table_remove (connection->priv->map_object_path_to_es, es->object_path));
4954 CONNECTION_UNLOCK (connection);
4959 /* ---------------------------------------------------------------------------------------------------- */
4961 /* must be called with lock held */
4963 handle_generic_ping_unlocked (GDBusConnection *connection,
4964 const gchar *object_path,
4965 GDBusMessage *message)
4967 GDBusMessage *reply;
4968 reply = g_dbus_message_new_method_reply (message);
4969 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
4970 g_object_unref (reply);
4973 /* must be called with lock held */
4975 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
4976 const gchar *object_path,
4977 GDBusMessage *message)
4979 GDBusMessage *reply;
4982 if (connection->priv->machine_id == NULL)
4986 /* TODO: use PACKAGE_LOCALSTATEDIR ? */
4987 if (!g_file_get_contents ("/var/lib/dbus/machine-id",
4988 &connection->priv->machine_id,
4992 reply = g_dbus_message_new_method_error (message,
4993 "org.freedesktop.DBus.Error.Failed",
4994 _("Unable to load /var/lib/dbus/machine-id: %s"),
4996 g_error_free (error);
5000 g_strstrip (connection->priv->machine_id);
5001 /* TODO: validate value */
5007 reply = g_dbus_message_new_method_reply (message);
5008 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->priv->machine_id));
5010 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5011 g_object_unref (reply);
5014 /* must be called with lock held */
5016 handle_generic_introspect_unlocked (GDBusConnection *connection,
5017 const gchar *object_path,
5018 GDBusMessage *message)
5023 GDBusMessage *reply;
5025 /* first the header */
5026 s = g_string_new (NULL);
5027 introspect_append_header (s);
5029 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5030 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5031 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5032 g_strfreev (registered);
5033 g_string_append (s, "</node>\n");
5035 reply = g_dbus_message_new_method_reply (message);
5036 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5037 g_dbus_connection_send_message_unlocked (connection, reply, NULL, NULL);
5038 g_object_unref (reply);
5039 g_string_free (s, TRUE);
5042 /* must be called with lock held */
5044 handle_generic_unlocked (GDBusConnection *connection,
5045 GDBusMessage *message)
5048 const gchar *interface_name;
5049 const gchar *member;
5050 const gchar *signature;
5053 CONNECTION_ENSURE_LOCK (connection);
5057 interface_name = g_dbus_message_get_interface (message);
5058 member = g_dbus_message_get_member (message);
5059 signature = g_dbus_message_get_signature (message);
5060 path = g_dbus_message_get_path (message);
5062 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5063 g_strcmp0 (member, "Introspect") == 0 &&
5064 g_strcmp0 (signature, "") == 0)
5066 handle_generic_introspect_unlocked (connection, path, message);
5069 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5070 g_strcmp0 (member, "Ping") == 0 &&
5071 g_strcmp0 (signature, "") == 0)
5073 handle_generic_ping_unlocked (connection, path, message);
5076 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5077 g_strcmp0 (member, "GetMachineId") == 0 &&
5078 g_strcmp0 (signature, "") == 0)
5080 handle_generic_get_machine_id_unlocked (connection, path, message);
5087 /* ---------------------------------------------------------------------------------------------------- */
5089 /* called in message handler thread with lock held */
5091 distribute_method_call (GDBusConnection *connection,
5092 GDBusMessage *message)
5095 ExportedSubtree *es;
5096 const gchar *object_path;
5097 const gchar *interface_name;
5098 const gchar *member;
5099 const gchar *signature;
5101 gchar *subtree_path;
5104 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
5106 interface_name = g_dbus_message_get_interface (message);
5107 member = g_dbus_message_get_member (message);
5108 signature = g_dbus_message_get_signature (message);
5109 path = g_dbus_message_get_path (message);
5110 subtree_path = g_strdup (path);
5111 needle = strrchr (subtree_path, '/');
5112 if (needle != NULL && needle != subtree_path)
5118 g_free (subtree_path);
5119 subtree_path = NULL;
5123 g_debug ("interface = `%s'", interface_name);
5124 g_debug ("member = `%s'", member);
5125 g_debug ("signature = `%s'", signature);
5126 g_debug ("path = `%s'", path);
5127 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
5130 object_path = g_dbus_message_get_path (message);
5131 g_assert (object_path != NULL);
5133 eo = g_hash_table_lookup (connection->priv->map_object_path_to_eo, object_path);
5136 if (obj_message_func (connection, eo, message))
5140 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, object_path);
5143 if (subtree_message_func (connection, es, message))
5147 if (subtree_path != NULL)
5149 es = g_hash_table_lookup (connection->priv->map_object_path_to_es, subtree_path);
5152 if (subtree_message_func (connection, es, message))
5157 if (handle_generic_unlocked (connection, message))
5160 /* if we end up here, the message has not been not handled */
5163 g_free (subtree_path);
5166 /* ---------------------------------------------------------------------------------------------------- */
5168 static GDBusConnection **
5169 message_bus_get_singleton (GBusType bus_type,
5172 GDBusConnection **ret;
5173 const gchar *starter_bus;
5179 case G_BUS_TYPE_SESSION:
5180 ret = &the_session_bus;
5183 case G_BUS_TYPE_SYSTEM:
5184 ret = &the_system_bus;
5187 case G_BUS_TYPE_STARTER:
5188 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
5189 if (g_strcmp0 (starter_bus, "session") == 0)
5191 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
5194 else if (g_strcmp0 (starter_bus, "system") == 0)
5196 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
5201 if (starter_bus != NULL)
5205 G_IO_ERROR_INVALID_ARGUMENT,
5206 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
5207 " - unknown value `%s'"),
5212 g_set_error_literal (error,
5214 G_IO_ERROR_INVALID_ARGUMENT,
5215 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
5216 "variable is not set"));
5222 g_assert_not_reached ();
5230 static GDBusConnection *
5231 get_uninitialized_connection (GBusType bus_type,
5232 GCancellable *cancellable,
5235 GDBusConnection **singleton;
5236 GDBusConnection *ret;
5240 G_LOCK (message_bus_lock);
5241 singleton = message_bus_get_singleton (bus_type, error);
5242 if (singleton == NULL)
5245 if (*singleton == NULL)
5248 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
5249 if (address == NULL)
5251 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
5253 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
5254 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
5255 "exit-on-close", TRUE,
5260 ret = g_object_ref (*singleton);
5263 g_assert (ret != NULL);
5266 G_UNLOCK (message_bus_lock);
5272 * @bus_type: A #GBusType.
5273 * @cancellable: A #GCancellable or %NULL.
5274 * @error: Return location for error or %NULL.
5276 * Synchronously connects to the message bus specified by @bus_type.
5277 * Note that the returned object may shared with other callers,
5278 * e.g. if two separate parts of a process calls this function with
5279 * the same @bus_type, they will share the same object.
5281 * This is a synchronous failable function. See g_bus_get() and
5282 * g_bus_get_finish() for the asynchronous version.
5284 * The returned object is a singleton, that is, shared with other
5285 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5286 * event that you need a private message bus connection, use
5287 * g_dbus_address_get_for_bus_sync() and
5288 * g_dbus_connection_new_for_address().
5290 * Note that the returned #GDBusConnection object will (usually) have
5291 * the #GDBusConnection:exit-on-close property set to %TRUE.
5293 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5298 g_bus_get_sync (GBusType bus_type,
5299 GCancellable *cancellable,
5302 GDBusConnection *connection;
5304 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5306 connection = get_uninitialized_connection (bus_type, cancellable, error);
5307 if (connection == NULL)
5310 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
5312 g_object_unref (connection);
5321 bus_get_async_initable_cb (GObject *source_object,
5325 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
5329 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
5333 g_assert (error != NULL);
5334 g_simple_async_result_set_from_error (simple, error);
5335 g_error_free (error);
5336 g_object_unref (source_object);
5340 g_simple_async_result_set_op_res_gpointer (simple,
5344 g_simple_async_result_complete_in_idle (simple);
5345 g_object_unref (simple);
5350 * @bus_type: A #GBusType.
5351 * @cancellable: A #GCancellable or %NULL.
5352 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
5353 * @user_data: The data to pass to @callback.
5355 * Asynchronously connects to the message bus specified by @bus_type.
5357 * When the operation is finished, @callback will be invoked. You can
5358 * then call g_bus_get_finish() to get the result of the operation.
5360 * This is a asynchronous failable function. See g_bus_get_sync() for
5361 * the synchronous version.
5366 g_bus_get (GBusType bus_type,
5367 GCancellable *cancellable,
5368 GAsyncReadyCallback callback,
5371 GDBusConnection *connection;
5372 GSimpleAsyncResult *simple;
5375 simple = g_simple_async_result_new (NULL,
5381 connection = get_uninitialized_connection (bus_type, cancellable, &error);
5382 if (connection == NULL)
5384 g_assert (error != NULL);
5385 g_simple_async_result_set_from_error (simple, error);
5386 g_error_free (error);
5387 g_simple_async_result_complete_in_idle (simple);
5388 g_object_unref (simple);
5392 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
5395 bus_get_async_initable_cb,
5402 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
5403 * @error: Return location for error or %NULL.
5405 * Finishes an operation started with g_bus_get().
5407 * The returned object is a singleton, that is, shared with other
5408 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
5409 * event that you need a private message bus connection, use
5410 * g_dbus_address_get_for_bus() and
5411 * g_dbus_connection_new_for_address().
5413 * Note that the returned #GDBusConnection object will (usually) have
5414 * the #GDBusConnection:exit-on-close property set to %TRUE.
5416 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
5421 g_bus_get_finish (GAsyncResult *res,
5424 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
5426 GDBusConnection *ret;
5428 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5430 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
5434 if (g_simple_async_result_propagate_error (simple, error))
5437 object = g_simple_async_result_get_op_res_gpointer (simple);
5438 g_assert (object != NULL);
5439 ret = g_object_ref (G_DBUS_CONNECTION (object));
5445 /* ---------------------------------------------------------------------------------------------------- */
5447 #define __G_DBUS_CONNECTION_C__
5448 #include "gioaliasdef.c"