1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * <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>
153 * <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>
155 * <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>
157 * <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>
160 /* ---------------------------------------------------------------------------------------------------- */
162 typedef struct _GDBusConnectionClass GDBusConnectionClass;
165 * GDBusConnectionClass:
166 * @closed: Signal class handler for the #GDBusConnection::closed signal.
168 * Class structure for #GDBusConnection.
172 struct _GDBusConnectionClass
175 GObjectClass parent_class;
179 void (*closed) (GDBusConnection *connection,
180 gboolean remote_peer_vanished,
184 G_LOCK_DEFINE_STATIC (message_bus_lock);
186 static GDBusConnection *the_session_bus = NULL;
187 static GDBusConnection *the_system_bus = NULL;
189 /* ---------------------------------------------------------------------------------------------------- */
193 GDestroyNotify callback;
195 GMainContext *context;
196 } CallDestroyNotifyData;
199 call_destroy_notify_data_in_idle (gpointer user_data)
201 CallDestroyNotifyData *data = user_data;
202 data->callback (data->user_data);
207 call_destroy_notify_data_free (CallDestroyNotifyData *data)
209 if (data->context != NULL)
210 g_main_context_unref (data->context);
215 * call_destroy_notify: <internal>
216 * @context: A #GMainContext or %NULL.
217 * @callback: A #GDestroyNotify or %NULL.
218 * @user_data: Data to pass to @callback.
220 * Schedules @callback to run in @context.
223 call_destroy_notify (GMainContext *context,
224 GDestroyNotify callback,
227 if (callback == NULL)
230 if (context == g_main_context_get_thread_default ())
232 callback (user_data);
236 GSource *idle_source;
237 CallDestroyNotifyData *data;
239 data = g_new0 (CallDestroyNotifyData, 1);
240 data->callback = callback;
241 data->user_data = user_data;
242 data->context = context;
243 if (data->context != NULL)
244 g_main_context_ref (data->context);
246 idle_source = g_idle_source_new ();
247 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
248 g_source_set_callback (idle_source,
249 call_destroy_notify_data_in_idle,
251 (GDestroyNotify) call_destroy_notify_data_free);
252 g_source_attach (idle_source, data->context);
253 g_source_unref (idle_source);
260 /* ---------------------------------------------------------------------------------------------------- */
263 _g_strv_has_string (const gchar* const *haystack,
268 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
270 if (g_strcmp0 (haystack[n], needle) == 0)
276 /* ---------------------------------------------------------------------------------------------------- */
279 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
281 // TODO: for some reason this doesn't work on Windows
282 #define CONNECTION_ENSURE_LOCK(obj) do { \
283 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
285 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
286 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
291 #define CONNECTION_LOCK(obj) do { \
292 g_mutex_lock (&(obj)->lock); \
295 #define CONNECTION_UNLOCK(obj) do { \
296 g_mutex_unlock (&(obj)->lock); \
302 * The #GDBusConnection structure contains only private data and
303 * should only be accessed using the provided API.
307 struct _GDBusConnection
310 GObject parent_instance;
312 /* ------------------------------------------------------------------------ */
313 /* -- General object state ------------------------------------------------ */
314 /* ------------------------------------------------------------------------ */
316 /* object-wide lock */
319 /* A lock used in the init() method of the GInitable interface - see comments
320 * in initable_init() for why a separate lock is needed
324 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
325 * someone calls org.freedesktop.DBus.GetMachineId()
329 /* The underlying stream used for communication */
332 /* The object used for authentication (if any) */
335 /* Set to TRUE if the connection has been closed */
338 /* Last serial used */
341 /* The object used to send/receive message */
344 /* If connected to a message bus, this contains the unique name assigned to
345 * us by the bus (e.g. ":1.42")
347 gchar *bus_unique_name;
349 /* The GUID returned by the other side if we authenticed as a client or
350 * the GUID to use if authenticating as a server
354 /* set to TRUE exactly when initable_init() has finished running */
355 gboolean is_initialized;
357 /* If the connection could not be established during initable_init(), this GError will set */
358 GError *initialization_error;
360 /* The result of g_main_context_get_thread_default() when the object
361 * was created (the GObject _init() function) - this is used for delivery
362 * of the :closed GObject signal.
364 GMainContext *main_context_at_construction;
366 /* construct properties */
368 GDBusConnectionFlags flags;
370 /* Map used for managing method replies */
371 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
373 /* Maps used for managing signal subscription */
374 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
375 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
376 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
378 /* Maps used for managing exported objects and subtrees */
379 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
380 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
381 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
382 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
384 /* Structure used for message filters */
387 /* Whether to exit on close */
388 gboolean exit_on_close;
390 /* Capabilities negotiated during authentication */
391 GDBusCapabilityFlags capabilities;
393 GDBusAuthObserver *authentication_observer;
394 GCredentials *credentials;
396 /* set to TRUE when finalizing */
400 typedef struct ExportedObject ExportedObject;
401 static void exported_object_free (ExportedObject *eo);
403 typedef struct ExportedSubtree ExportedSubtree;
404 static void exported_subtree_free (ExportedSubtree *es);
422 PROP_CAPABILITY_FLAGS,
423 PROP_AUTHENTICATION_OBSERVER,
426 static void distribute_signals (GDBusConnection *connection,
427 GDBusMessage *message);
429 static void distribute_method_call (GDBusConnection *connection,
430 GDBusMessage *message);
432 static gboolean handle_generic_unlocked (GDBusConnection *connection,
433 GDBusMessage *message);
436 static void purge_all_signal_subscriptions (GDBusConnection *connection);
437 static void purge_all_filters (GDBusConnection *connection);
439 #define _G_ENSURE_LOCK(name) do { \
440 if (G_UNLIKELY (G_TRYLOCK(name))) \
442 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
443 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
447 static guint signals[LAST_SIGNAL] = { 0 };
449 static void initable_iface_init (GInitableIface *initable_iface);
450 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
452 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
453 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
454 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
457 static GHashTable *alive_connections = NULL;
460 g_dbus_connection_dispose (GObject *object)
462 GDBusConnection *connection = G_DBUS_CONNECTION (object);
464 G_LOCK (message_bus_lock);
465 if (connection == the_session_bus)
467 the_session_bus = NULL;
469 else if (connection == the_system_bus)
471 the_system_bus = NULL;
473 CONNECTION_LOCK (connection);
474 if (connection->worker != NULL)
476 _g_dbus_worker_stop (connection->worker);
477 connection->worker = NULL;
478 if (alive_connections != NULL)
479 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
483 if (alive_connections != NULL)
484 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
486 CONNECTION_UNLOCK (connection);
487 G_UNLOCK (message_bus_lock);
489 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
490 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
494 g_dbus_connection_finalize (GObject *object)
496 GDBusConnection *connection = G_DBUS_CONNECTION (object);
498 connection->finalizing = TRUE;
500 purge_all_signal_subscriptions (connection);
502 purge_all_filters (connection);
503 g_ptr_array_unref (connection->filters);
505 if (connection->authentication_observer != NULL)
506 g_object_unref (connection->authentication_observer);
508 if (connection->auth != NULL)
509 g_object_unref (connection->auth);
511 if (connection->credentials)
512 g_object_unref (connection->credentials);
514 if (connection->stream != NULL)
516 g_object_unref (connection->stream);
517 connection->stream = NULL;
520 g_free (connection->address);
522 g_free (connection->guid);
523 g_free (connection->bus_unique_name);
525 if (connection->initialization_error != NULL)
526 g_error_free (connection->initialization_error);
528 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
530 g_hash_table_unref (connection->map_rule_to_signal_data);
531 g_hash_table_unref (connection->map_id_to_signal_data);
532 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
534 g_hash_table_unref (connection->map_id_to_ei);
535 g_hash_table_unref (connection->map_object_path_to_eo);
536 g_hash_table_unref (connection->map_id_to_es);
537 g_hash_table_unref (connection->map_object_path_to_es);
539 if (connection->main_context_at_construction != NULL)
540 g_main_context_unref (connection->main_context_at_construction);
542 g_free (connection->machine_id);
544 g_mutex_clear (&connection->init_lock);
545 g_mutex_clear (&connection->lock);
547 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
551 g_dbus_connection_get_property (GObject *object,
556 GDBusConnection *connection = G_DBUS_CONNECTION (object);
561 g_value_set_object (value, g_dbus_connection_get_stream (connection));
565 g_value_set_string (value, g_dbus_connection_get_guid (connection));
568 case PROP_UNIQUE_NAME:
569 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
573 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
576 case PROP_EXIT_ON_CLOSE:
577 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
580 case PROP_CAPABILITY_FLAGS:
581 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
585 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
591 g_dbus_connection_set_property (GObject *object,
596 GDBusConnection *connection = G_DBUS_CONNECTION (object);
601 connection->stream = g_value_dup_object (value);
605 connection->guid = g_value_dup_string (value);
609 connection->address = g_value_dup_string (value);
613 connection->flags = g_value_get_flags (value);
616 case PROP_EXIT_ON_CLOSE:
617 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
620 case PROP_AUTHENTICATION_OBSERVER:
621 connection->authentication_observer = g_value_dup_object (value);
625 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
631 g_dbus_connection_real_closed (GDBusConnection *connection,
632 gboolean remote_peer_vanished,
635 if (remote_peer_vanished && connection->exit_on_close && connection->is_initialized)
639 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
642 g_quark_to_string (error->domain), error->code);
646 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
653 g_dbus_connection_class_init (GDBusConnectionClass *klass)
655 GObjectClass *gobject_class;
657 gobject_class = G_OBJECT_CLASS (klass);
659 gobject_class->finalize = g_dbus_connection_finalize;
660 gobject_class->dispose = g_dbus_connection_dispose;
661 gobject_class->set_property = g_dbus_connection_set_property;
662 gobject_class->get_property = g_dbus_connection_get_property;
664 klass->closed = g_dbus_connection_real_closed;
667 * GDBusConnection:stream:
669 * The underlying #GIOStream used for I/O.
671 * If this is passed on construction and is a #GSocketConnection,
672 * then the corresponding #GSocket will be put into non-blocking mode.
676 g_object_class_install_property (gobject_class,
678 g_param_spec_object ("stream",
680 P_("The underlying streams used for I/O"),
684 G_PARAM_CONSTRUCT_ONLY |
685 G_PARAM_STATIC_NAME |
686 G_PARAM_STATIC_BLURB |
687 G_PARAM_STATIC_NICK));
690 * GDBusConnection:address:
692 * A D-Bus address specifying potential endpoints that can be used
693 * when establishing the connection.
697 g_object_class_install_property (gobject_class,
699 g_param_spec_string ("address",
701 P_("D-Bus address specifying potential socket endpoints"),
704 G_PARAM_CONSTRUCT_ONLY |
705 G_PARAM_STATIC_NAME |
706 G_PARAM_STATIC_BLURB |
707 G_PARAM_STATIC_NICK));
710 * GDBusConnection:flags:
712 * Flags from the #GDBusConnectionFlags enumeration.
716 g_object_class_install_property (gobject_class,
718 g_param_spec_flags ("flags",
721 G_TYPE_DBUS_CONNECTION_FLAGS,
722 G_DBUS_CONNECTION_FLAGS_NONE,
724 G_PARAM_CONSTRUCT_ONLY |
725 G_PARAM_STATIC_NAME |
726 G_PARAM_STATIC_BLURB |
727 G_PARAM_STATIC_NICK));
730 * GDBusConnection:guid:
732 * The GUID of the peer performing the role of server when
735 * If you are constructing a #GDBusConnection and pass
736 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
737 * #GDBusConnection:flags property then you MUST also set this
738 * property to a valid guid.
740 * If you are constructing a #GDBusConnection and pass
741 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
742 * #GDBusConnection:flags property you will be able to read the GUID
743 * of the other peer here after the connection has been successfully
748 g_object_class_install_property (gobject_class,
750 g_param_spec_string ("guid",
752 P_("GUID of the server peer"),
756 G_PARAM_CONSTRUCT_ONLY |
757 G_PARAM_STATIC_NAME |
758 G_PARAM_STATIC_BLURB |
759 G_PARAM_STATIC_NICK));
762 * GDBusConnection:unique-name:
764 * The unique name as assigned by the message bus or %NULL if the
765 * connection is not open or not a message bus connection.
769 g_object_class_install_property (gobject_class,
771 g_param_spec_string ("unique-name",
773 P_("Unique name of bus connection"),
776 G_PARAM_STATIC_NAME |
777 G_PARAM_STATIC_BLURB |
778 G_PARAM_STATIC_NICK));
781 * GDBusConnection:closed:
783 * A boolean specifying whether the connection has been closed.
787 g_object_class_install_property (gobject_class,
789 g_param_spec_boolean ("closed",
791 P_("Whether the connection is closed"),
794 G_PARAM_STATIC_NAME |
795 G_PARAM_STATIC_BLURB |
796 G_PARAM_STATIC_NICK));
799 * GDBusConnection:exit-on-close:
801 * A boolean specifying whether the process will be terminated (by
802 * calling <literal>raise(SIGTERM)</literal>) if the connection
803 * is closed by the remote peer.
807 g_object_class_install_property (gobject_class,
809 g_param_spec_boolean ("exit-on-close",
811 P_("Whether the process is terminated when the connection is closed"),
815 G_PARAM_STATIC_NAME |
816 G_PARAM_STATIC_BLURB |
817 G_PARAM_STATIC_NICK));
820 * GDBusConnection:capabilities:
822 * Flags from the #GDBusCapabilityFlags enumeration
823 * representing connection features negotiated with the other peer.
827 g_object_class_install_property (gobject_class,
828 PROP_CAPABILITY_FLAGS,
829 g_param_spec_flags ("capabilities",
832 G_TYPE_DBUS_CAPABILITY_FLAGS,
833 G_DBUS_CAPABILITY_FLAGS_NONE,
835 G_PARAM_STATIC_NAME |
836 G_PARAM_STATIC_BLURB |
837 G_PARAM_STATIC_NICK));
840 * GDBusConnection:authentication-observer:
842 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
846 g_object_class_install_property (gobject_class,
847 PROP_AUTHENTICATION_OBSERVER,
848 g_param_spec_object ("authentication-observer",
849 P_("Authentication Observer"),
850 P_("Object used to assist in the authentication process"),
851 G_TYPE_DBUS_AUTH_OBSERVER,
853 G_PARAM_CONSTRUCT_ONLY |
854 G_PARAM_STATIC_NAME |
855 G_PARAM_STATIC_BLURB |
856 G_PARAM_STATIC_NICK));
859 * GDBusConnection::closed:
860 * @connection: The #GDBusConnection emitting the signal.
861 * @remote_peer_vanished: %TRUE if @connection is closed because the
862 * remote peer closed its end of the connection.
863 * @error: A #GError with more details about the event or %NULL.
865 * Emitted when the connection is closed.
867 * The cause of this event can be
870 * If g_dbus_connection_close() is called. In this case
871 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
874 * If the remote peer closes the connection. In this case
875 * @remote_peer_vanished is set to %TRUE and @error is set.
878 * If the remote peer sends invalid or malformed data. In this
879 * case @remote_peer_vanished is set to %FALSE and @error
884 * Upon receiving this signal, you should give up your reference to
885 * @connection. You are guaranteed that this signal is emitted only
890 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
891 G_TYPE_DBUS_CONNECTION,
893 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
904 g_dbus_connection_init (GDBusConnection *connection)
906 g_mutex_init (&connection->lock);
907 g_mutex_init (&connection->init_lock);
909 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
911 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
913 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
915 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
918 (GDestroyNotify) g_ptr_array_unref);
920 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
923 (GDestroyNotify) exported_object_free);
925 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
928 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
931 (GDestroyNotify) exported_subtree_free);
933 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
936 connection->main_context_at_construction = g_main_context_get_thread_default ();
937 if (connection->main_context_at_construction != NULL)
938 g_main_context_ref (connection->main_context_at_construction);
940 connection->filters = g_ptr_array_new ();
944 * g_dbus_connection_get_stream:
945 * @connection: a #GDBusConnection
947 * Gets the underlying stream used for IO.
949 * Returns: (transfer none): the stream used for IO
954 g_dbus_connection_get_stream (GDBusConnection *connection)
956 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
957 return connection->stream;
961 * g_dbus_connection_start_message_processing:
962 * @connection: A #GDBusConnection.
964 * If @connection was created with
965 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
966 * starts processing messages. Does nothing on if @connection wasn't
967 * created with this flag or if the method has already been called.
972 g_dbus_connection_start_message_processing (GDBusConnection *connection)
974 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
975 _g_dbus_worker_unfreeze (connection->worker);
979 * g_dbus_connection_is_closed:
980 * @connection: A #GDBusConnection.
982 * Gets whether @connection is closed.
984 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
989 g_dbus_connection_is_closed (GDBusConnection *connection)
991 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
992 return connection->closed;
996 * g_dbus_connection_get_capabilities:
997 * @connection: A #GDBusConnection.
999 * Gets the capabilities negotiated with the remote peer
1001 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1005 GDBusCapabilityFlags
1006 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1008 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1009 return connection->capabilities;
1012 /* ---------------------------------------------------------------------------------------------------- */
1015 flush_in_thread_func (GSimpleAsyncResult *res,
1017 GCancellable *cancellable)
1022 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1025 g_simple_async_result_take_error (res, error);
1029 * g_dbus_connection_flush:
1030 * @connection: A #GDBusConnection.
1031 * @cancellable: A #GCancellable or %NULL.
1032 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1033 * satisfied or %NULL if you don't care about the result.
1034 * @user_data: The data to pass to @callback.
1036 * Asynchronously flushes @connection, that is, writes all queued
1037 * outgoing message to the transport and then flushes the transport
1038 * (using g_output_stream_flush_async()). This is useful in programs
1039 * that wants to emit a D-Bus signal and then exit
1040 * immediately. Without flushing the connection, there is no guarantee
1041 * that the message has been sent to the networking buffers in the OS
1044 * This is an asynchronous method. When the operation is finished,
1045 * @callback will be invoked in the <link
1046 * linkend="g-main-context-push-thread-default">thread-default main
1047 * loop</link> of the thread you are calling this method from. You can
1048 * then call g_dbus_connection_flush_finish() to get the result of the
1049 * operation. See g_dbus_connection_flush_sync() for the synchronous
1055 g_dbus_connection_flush (GDBusConnection *connection,
1056 GCancellable *cancellable,
1057 GAsyncReadyCallback callback,
1060 GSimpleAsyncResult *simple;
1062 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1064 simple = g_simple_async_result_new (G_OBJECT (connection),
1067 g_dbus_connection_flush);
1068 g_simple_async_result_run_in_thread (simple,
1069 flush_in_thread_func,
1072 g_object_unref (simple);
1076 * g_dbus_connection_flush_finish:
1077 * @connection: A #GDBusConnection.
1078 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1079 * @error: Return location for error or %NULL.
1081 * Finishes an operation started with g_dbus_connection_flush().
1083 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1088 g_dbus_connection_flush_finish (GDBusConnection *connection,
1092 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1097 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1098 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1099 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1101 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1103 if (g_simple_async_result_propagate_error (simple, error))
1113 * g_dbus_connection_flush_sync:
1114 * @connection: A #GDBusConnection.
1115 * @cancellable: A #GCancellable or %NULL.
1116 * @error: Return location for error or %NULL.
1118 * Synchronously flushes @connection. The calling thread is blocked
1119 * until this is done. See g_dbus_connection_flush() for the
1120 * asynchronous version of this method and more details about what it
1123 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1128 g_dbus_connection_flush_sync (GDBusConnection *connection,
1129 GCancellable *cancellable,
1134 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1135 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1139 if (connection->closed)
1141 g_set_error_literal (error,
1144 _("The connection is closed"));
1148 ret = _g_dbus_worker_flush_sync (connection->worker,
1156 /* ---------------------------------------------------------------------------------------------------- */
1160 GDBusConnection *connection;
1162 gboolean remote_peer_vanished;
1166 emit_closed_data_free (EmitClosedData *data)
1168 g_object_unref (data->connection);
1169 if (data->error != NULL)
1170 g_error_free (data->error);
1175 emit_closed_in_idle (gpointer user_data)
1177 EmitClosedData *data = user_data;
1180 g_object_notify (G_OBJECT (data->connection), "closed");
1181 g_signal_emit (data->connection,
1182 signals[CLOSED_SIGNAL],
1184 data->remote_peer_vanished,
1190 /* Can be called from any thread, must hold lock */
1192 set_closed_unlocked (GDBusConnection *connection,
1193 gboolean remote_peer_vanished,
1196 GSource *idle_source;
1197 EmitClosedData *data;
1199 CONNECTION_ENSURE_LOCK (connection);
1201 g_assert (!connection->closed);
1203 connection->closed = TRUE;
1205 data = g_new0 (EmitClosedData, 1);
1206 data->connection = g_object_ref (connection);
1207 data->remote_peer_vanished = remote_peer_vanished;
1208 data->error = error != NULL ? g_error_copy (error) : NULL;
1210 idle_source = g_idle_source_new ();
1211 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1212 g_source_set_callback (idle_source,
1213 emit_closed_in_idle,
1215 (GDestroyNotify) emit_closed_data_free);
1216 g_source_attach (idle_source, connection->main_context_at_construction);
1217 g_source_unref (idle_source);
1220 /* ---------------------------------------------------------------------------------------------------- */
1223 * g_dbus_connection_close:
1224 * @connection: A #GDBusConnection.
1225 * @cancellable: A #GCancellable or %NULL.
1226 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1227 * satisfied or %NULL if you don't care about the result.
1228 * @user_data: The data to pass to @callback.
1230 * Closes @connection. Note that this never causes the process to
1231 * exit (this might only happen if the other end of a shared message
1232 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1234 * Once the connection is closed, operations such as sending a message
1235 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1236 * will not automatically flush the connection so queued messages may
1237 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1239 * If @connection is already closed, this method fails with
1240 * %G_IO_ERROR_CLOSED.
1242 * When @connection has been closed, the #GDBusConnection::closed
1243 * signal is emitted in the <link
1244 * linkend="g-main-context-push-thread-default">thread-default main
1245 * loop</link> of the thread that @connection was constructed in.
1247 * This is an asynchronous method. When the operation is finished,
1248 * @callback will be invoked in the <link
1249 * linkend="g-main-context-push-thread-default">thread-default main
1250 * loop</link> of the thread you are calling this method from. You can
1251 * then call g_dbus_connection_close_finish() to get the result of the
1252 * operation. See g_dbus_connection_close_sync() for the synchronous
1258 g_dbus_connection_close (GDBusConnection *connection,
1259 GCancellable *cancellable,
1260 GAsyncReadyCallback callback,
1263 GSimpleAsyncResult *simple;
1265 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1267 simple = g_simple_async_result_new (G_OBJECT (connection),
1270 g_dbus_connection_close);
1271 _g_dbus_worker_close (connection->worker, cancellable, simple);
1272 g_object_unref (simple);
1276 * g_dbus_connection_close_finish:
1277 * @connection: A #GDBusConnection.
1278 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1279 * @error: Return location for error or %NULL.
1281 * Finishes an operation started with g_dbus_connection_close().
1283 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1288 g_dbus_connection_close_finish (GDBusConnection *connection,
1292 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1297 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1298 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1299 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1301 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1303 if (g_simple_async_result_propagate_error (simple, error))
1314 GAsyncResult *result;
1318 sync_close_cb (GObject *source_object,
1322 SyncCloseData *data = user_data;
1324 data->result = g_object_ref (res);
1325 g_main_loop_quit (data->loop);
1329 * g_dbus_connection_close_sync:
1330 * @connection: A #GDBusConnection.
1331 * @cancellable: A #GCancellable or %NULL.
1332 * @error: Return location for error or %NULL.
1334 * Synchronously closees @connection. The calling thread is blocked
1335 * until this is done. See g_dbus_connection_close() for the
1336 * asynchronous version of this method and more details about what it
1339 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1344 g_dbus_connection_close_sync (GDBusConnection *connection,
1345 GCancellable *cancellable,
1350 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1351 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1355 CONNECTION_LOCK (connection);
1356 if (!connection->closed)
1358 GMainContext *context;
1361 context = g_main_context_new ();
1362 g_main_context_push_thread_default (context);
1363 data.loop = g_main_loop_new (context, TRUE);
1366 CONNECTION_UNLOCK (connection);
1367 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1368 g_main_loop_run (data.loop);
1369 ret = g_dbus_connection_close_finish (connection, data.result, error);
1370 CONNECTION_LOCK (connection);
1372 g_object_unref (data.result);
1373 g_main_loop_unref (data.loop);
1374 g_main_context_pop_thread_default (context);
1375 g_main_context_unref (context);
1379 g_set_error_literal (error,
1382 _("The connection is closed"));
1384 CONNECTION_UNLOCK (connection);
1389 /* ---------------------------------------------------------------------------------------------------- */
1392 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1393 GDBusMessage *message,
1394 GDBusSendMessageFlags flags,
1395 volatile guint32 *out_serial,
1400 guint32 serial_to_use;
1403 CONNECTION_ENSURE_LOCK (connection);
1405 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1406 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1408 /* TODO: check all necessary headers are present */
1413 if (out_serial != NULL)
1416 if (connection->closed)
1418 g_set_error_literal (error,
1421 _("The connection is closed"));
1425 blob = g_dbus_message_to_blob (message,
1427 connection->capabilities,
1432 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1433 serial_to_use = g_dbus_message_get_serial (message);
1435 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1440 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1443 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1446 g_assert_not_reached ();
1451 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1452 blob_size, serial_to_use, connection);
1453 g_printerr ("----\n");
1454 hexdump (blob, blob_size);
1455 g_printerr ("----\n");
1458 /* TODO: use connection->auth to encode the blob */
1460 if (out_serial != NULL)
1461 *out_serial = serial_to_use;
1463 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1464 g_dbus_message_set_serial (message, serial_to_use);
1466 g_dbus_message_lock (message);
1467 _g_dbus_worker_send_message (connection->worker,
1471 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1482 * g_dbus_connection_send_message:
1483 * @connection: A #GDBusConnection.
1484 * @message: A #GDBusMessage
1485 * @flags: Flags affecting how the message is sent.
1486 * @out_serial: (out) (allow-none): Return location for serial number assigned
1487 * to @message when sending it or %NULL.
1488 * @error: Return location for error or %NULL.
1490 * Asynchronously sends @message to the peer represented by @connection.
1492 * Unless @flags contain the
1493 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1494 * will be assigned by @connection and set on @message via
1495 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1496 * serial number used will be written to this location prior to
1497 * submitting the message to the underlying transport.
1499 * If @connection is closed then the operation will fail with
1500 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1501 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1503 * See <xref linkend="gdbus-server"/> and <xref
1504 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1505 * low-level API to send and receive UNIX file descriptors.
1507 * Note that @message must be unlocked, unless @flags contain the
1508 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1510 * Returns: %TRUE if the message was well-formed and queued for
1511 * transmission, %FALSE if @error is set.
1516 g_dbus_connection_send_message (GDBusConnection *connection,
1517 GDBusMessage *message,
1518 GDBusSendMessageFlags flags,
1519 volatile guint32 *out_serial,
1524 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1525 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1526 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1527 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1529 CONNECTION_LOCK (connection);
1530 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1531 CONNECTION_UNLOCK (connection);
1535 /* ---------------------------------------------------------------------------------------------------- */
1539 volatile gint ref_count;
1540 GDBusConnection *connection;
1542 GSimpleAsyncResult *simple;
1544 GMainContext *main_context;
1546 GCancellable *cancellable;
1548 gulong cancellable_handler_id;
1550 GSource *timeout_source;
1555 static SendMessageData *
1556 send_message_data_ref (SendMessageData *data)
1558 g_atomic_int_inc (&data->ref_count);
1563 send_message_data_unref (SendMessageData *data)
1565 if (g_atomic_int_dec_and_test (&data->ref_count))
1567 g_assert (data->timeout_source == NULL);
1568 g_assert (data->simple == NULL);
1569 g_assert (data->cancellable_handler_id == 0);
1570 g_object_unref (data->connection);
1571 if (data->cancellable != NULL)
1572 g_object_unref (data->cancellable);
1573 if (data->main_context != NULL)
1574 g_main_context_unref (data->main_context);
1579 /* ---------------------------------------------------------------------------------------------------- */
1581 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1583 send_message_with_reply_deliver (SendMessageData *data)
1585 CONNECTION_ENSURE_LOCK (data->connection);
1587 g_assert (!data->delivered);
1589 data->delivered = TRUE;
1591 g_simple_async_result_complete_in_idle (data->simple);
1592 g_object_unref (data->simple);
1593 data->simple = NULL;
1595 if (data->timeout_source != NULL)
1597 g_source_destroy (data->timeout_source);
1598 data->timeout_source = NULL;
1600 if (data->cancellable_handler_id > 0)
1602 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1603 data->cancellable_handler_id = 0;
1606 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1607 GUINT_TO_POINTER (data->serial)));
1609 send_message_data_unref (data);
1612 /* ---------------------------------------------------------------------------------------------------- */
1614 /* must hold lock */
1616 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1617 GDBusMessage *reply)
1619 if (data->delivered)
1622 g_simple_async_result_set_op_res_gpointer (data->simple,
1623 g_object_ref (reply),
1626 send_message_with_reply_deliver (data);
1632 /* ---------------------------------------------------------------------------------------------------- */
1635 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1637 SendMessageData *data = user_data;
1639 CONNECTION_LOCK (data->connection);
1640 if (data->delivered)
1643 g_simple_async_result_set_error (data->simple,
1645 G_IO_ERROR_CANCELLED,
1646 _("Operation was cancelled"));
1648 send_message_with_reply_deliver (data);
1651 CONNECTION_UNLOCK (data->connection);
1655 /* Can be called from any thread with or without lock held */
1657 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1660 SendMessageData *data = user_data;
1661 GSource *idle_source;
1663 /* postpone cancellation to idle handler since we may be called directly
1664 * via g_cancellable_connect() (e.g. holding lock)
1666 idle_source = g_idle_source_new ();
1667 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1668 g_source_set_callback (idle_source,
1669 send_message_with_reply_cancelled_idle_cb,
1670 send_message_data_ref (data),
1671 (GDestroyNotify) send_message_data_unref);
1672 g_source_attach (idle_source, data->main_context);
1673 g_source_unref (idle_source);
1676 /* ---------------------------------------------------------------------------------------------------- */
1679 send_message_with_reply_timeout_cb (gpointer user_data)
1681 SendMessageData *data = user_data;
1683 CONNECTION_LOCK (data->connection);
1684 if (data->delivered)
1687 g_simple_async_result_set_error (data->simple,
1689 G_IO_ERROR_TIMED_OUT,
1690 _("Timeout was reached"));
1692 send_message_with_reply_deliver (data);
1695 CONNECTION_UNLOCK (data->connection);
1700 /* ---------------------------------------------------------------------------------------------------- */
1703 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1704 GDBusMessage *message,
1705 GDBusSendMessageFlags flags,
1707 volatile guint32 *out_serial,
1708 GCancellable *cancellable,
1709 GAsyncReadyCallback callback,
1712 GSimpleAsyncResult *simple;
1713 SendMessageData *data;
1715 volatile guint32 serial;
1719 if (out_serial == NULL)
1720 out_serial = &serial;
1722 if (timeout_msec == -1)
1723 timeout_msec = 25 * 1000;
1725 simple = g_simple_async_result_new (G_OBJECT (connection),
1728 g_dbus_connection_send_message_with_reply);
1730 if (g_cancellable_is_cancelled (cancellable))
1732 g_simple_async_result_set_error (simple,
1734 G_IO_ERROR_CANCELLED,
1735 _("Operation was cancelled"));
1736 g_simple_async_result_complete_in_idle (simple);
1737 g_object_unref (simple);
1741 if (connection->closed)
1743 g_simple_async_result_set_error (simple,
1746 _("The connection is closed"));
1747 g_simple_async_result_complete_in_idle (simple);
1748 g_object_unref (simple);
1753 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1755 g_simple_async_result_take_error (simple, error);
1756 g_simple_async_result_complete_in_idle (simple);
1757 g_object_unref (simple);
1761 data = g_new0 (SendMessageData, 1);
1762 data->ref_count = 1;
1763 data->connection = g_object_ref (connection);
1764 data->simple = simple;
1765 data->serial = *out_serial;
1766 data->main_context = g_main_context_get_thread_default ();
1767 if (data->main_context != NULL)
1768 g_main_context_ref (data->main_context);
1770 if (cancellable != NULL)
1772 data->cancellable = g_object_ref (cancellable);
1773 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1774 G_CALLBACK (send_message_with_reply_cancelled_cb),
1775 send_message_data_ref (data),
1776 (GDestroyNotify) send_message_data_unref);
1777 g_object_set_data_full (G_OBJECT (simple),
1779 g_object_ref (cancellable),
1780 (GDestroyNotify) g_object_unref);
1783 if (timeout_msec != G_MAXINT)
1785 data->timeout_source = g_timeout_source_new (timeout_msec);
1786 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1787 g_source_set_callback (data->timeout_source,
1788 send_message_with_reply_timeout_cb,
1789 send_message_data_ref (data),
1790 (GDestroyNotify) send_message_data_unref);
1791 g_source_attach (data->timeout_source, data->main_context);
1792 g_source_unref (data->timeout_source);
1795 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1796 GUINT_TO_POINTER (*out_serial),
1804 * g_dbus_connection_send_message_with_reply:
1805 * @connection: A #GDBusConnection.
1806 * @message: A #GDBusMessage.
1807 * @flags: Flags affecting how the message is sent.
1808 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1809 * timeout or %G_MAXINT for no timeout.
1810 * @out_serial: (out) (allow-none): Return location for serial number assigned
1811 * to @message when sending it or %NULL.
1812 * @cancellable: A #GCancellable or %NULL.
1813 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1814 * satisfied or %NULL if you don't care about the result.
1815 * @user_data: The data to pass to @callback.
1817 * Asynchronously sends @message to the peer represented by @connection.
1819 * Unless @flags contain the
1820 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1821 * will be assigned by @connection and set on @message via
1822 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1823 * serial number used will be written to this location prior to
1824 * submitting the message to the underlying transport.
1826 * If @connection is closed then the operation will fail with
1827 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1828 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1829 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1831 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1832 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1833 * of the thread you are calling this method from. You can then call
1834 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1835 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1837 * Note that @message must be unlocked, unless @flags contain the
1838 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1840 * See <xref linkend="gdbus-server"/> and <xref
1841 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1842 * low-level API to send and receive UNIX file descriptors.
1847 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1848 GDBusMessage *message,
1849 GDBusSendMessageFlags flags,
1851 volatile guint32 *out_serial,
1852 GCancellable *cancellable,
1853 GAsyncReadyCallback callback,
1856 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1857 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1858 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1859 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1861 CONNECTION_LOCK (connection);
1862 g_dbus_connection_send_message_with_reply_unlocked (connection,
1870 CONNECTION_UNLOCK (connection);
1874 * g_dbus_connection_send_message_with_reply_finish:
1875 * @connection: a #GDBusConnection
1876 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1877 * @error: Return location for error or %NULL.
1879 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1881 * Note that @error is only set if a local in-process error
1882 * occurred. That is to say that the returned #GDBusMessage object may
1883 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1884 * g_dbus_message_to_gerror() to transcode this to a #GError.
1886 * See <xref linkend="gdbus-server"/> and <xref
1887 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1888 * low-level API to send and receive UNIX file descriptors.
1890 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
1895 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1899 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1900 GDBusMessage *reply;
1901 GCancellable *cancellable;
1903 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1904 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1908 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1910 if (g_simple_async_result_propagate_error (simple, error))
1913 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1914 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1915 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1917 g_object_unref (reply);
1919 g_set_error_literal (error,
1921 G_IO_ERROR_CANCELLED,
1922 _("Operation was cancelled"));
1928 /* ---------------------------------------------------------------------------------------------------- */
1933 GMainContext *context;
1935 } SendMessageSyncData;
1938 send_message_with_reply_sync_cb (GDBusConnection *connection,
1942 SendMessageSyncData *data = user_data;
1943 data->res = g_object_ref (res);
1944 g_main_loop_quit (data->loop);
1948 * g_dbus_connection_send_message_with_reply_sync:
1949 * @connection: A #GDBusConnection.
1950 * @message: A #GDBusMessage.
1951 * @flags: Flags affecting how the message is sent.
1952 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1953 * timeout or %G_MAXINT for no timeout.
1954 * @out_serial: (out) (allow-none): Return location for serial number assigned
1955 * to @message when sending it or %NULL.
1956 * @cancellable: A #GCancellable or %NULL.
1957 * @error: Return location for error or %NULL.
1959 * Synchronously sends @message to the peer represented by @connection
1960 * and blocks the calling thread until a reply is received or the
1961 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1962 * for the asynchronous version of this method.
1964 * Unless @flags contain the
1965 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1966 * will be assigned by @connection and set on @message via
1967 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1968 * serial number used will be written to this location prior to
1969 * submitting the message to the underlying transport.
1971 * If @connection is closed then the operation will fail with
1972 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1973 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1974 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1976 * Note that @error is only set if a local in-process error
1977 * occurred. That is to say that the returned #GDBusMessage object may
1978 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1979 * g_dbus_message_to_gerror() to transcode this to a #GError.
1981 * See <xref linkend="gdbus-server"/> and <xref
1982 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1983 * low-level API to send and receive UNIX file descriptors.
1985 * Note that @message must be unlocked, unless @flags contain the
1986 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1988 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
1993 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1994 GDBusMessage *message,
1995 GDBusSendMessageFlags flags,
1997 volatile guint32 *out_serial,
1998 GCancellable *cancellable,
2001 SendMessageSyncData *data;
2002 GDBusMessage *reply;
2004 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2005 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2006 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2007 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2008 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2010 data = g_new0 (SendMessageSyncData, 1);
2011 data->context = g_main_context_new ();
2012 data->loop = g_main_loop_new (data->context, FALSE);
2014 g_main_context_push_thread_default (data->context);
2016 g_dbus_connection_send_message_with_reply (connection,
2022 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2024 g_main_loop_run (data->loop);
2025 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2029 g_main_context_pop_thread_default (data->context);
2031 g_main_context_unref (data->context);
2032 g_main_loop_unref (data->loop);
2033 g_object_unref (data->res);
2039 /* ---------------------------------------------------------------------------------------------------- */
2043 GDBusMessageFilterFunction func;
2050 GDBusMessageFilterFunction filter_function;
2052 GDestroyNotify user_data_free_func;
2055 /* Called in worker's thread - we must not block */
2057 on_worker_message_received (GDBusWorker *worker,
2058 GDBusMessage *message,
2061 GDBusConnection *connection;
2062 FilterCallback *filters;
2067 G_LOCK (message_bus_lock);
2068 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2071 G_UNLOCK (message_bus_lock);
2074 connection = G_DBUS_CONNECTION (user_data);
2075 g_object_ref (connection);
2076 G_UNLOCK (message_bus_lock);
2078 //g_debug ("in on_worker_message_received");
2080 g_object_ref (message);
2081 g_dbus_message_lock (message);
2083 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2085 /* First collect the set of callback functions */
2086 CONNECTION_LOCK (connection);
2087 num_filters = connection->filters->len;
2088 filters = g_new0 (FilterCallback, num_filters);
2089 for (n = 0; n < num_filters; n++)
2091 FilterData *data = connection->filters->pdata[n];
2092 filters[n].func = data->filter_function;
2093 filters[n].user_data = data->user_data;
2095 CONNECTION_UNLOCK (connection);
2097 /* then call the filters in order (without holding the lock) */
2098 for (n = 0; n < num_filters; n++)
2100 message = filters[n].func (connection,
2103 filters[n].user_data);
2104 if (message == NULL)
2106 g_dbus_message_lock (message);
2109 /* Standard dispatch unless the filter ate the message - no need to
2110 * do anything if the message was altered
2112 if (message != NULL)
2114 GDBusMessageType message_type;
2116 message_type = g_dbus_message_get_message_type (message);
2117 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2119 guint32 reply_serial;
2120 SendMessageData *send_message_data;
2122 reply_serial = g_dbus_message_get_reply_serial (message);
2123 CONNECTION_LOCK (connection);
2124 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2125 GUINT_TO_POINTER (reply_serial));
2126 if (send_message_data != NULL)
2128 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2129 send_message_data_deliver_reply_unlocked (send_message_data, message);
2133 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2135 CONNECTION_UNLOCK (connection);
2137 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2139 CONNECTION_LOCK (connection);
2140 distribute_signals (connection, message);
2141 CONNECTION_UNLOCK (connection);
2143 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2145 CONNECTION_LOCK (connection);
2146 distribute_method_call (connection, message);
2147 CONNECTION_UNLOCK (connection);
2151 if (message != NULL)
2152 g_object_unref (message);
2153 g_object_unref (connection);
2157 /* Called in worker's thread */
2158 static GDBusMessage *
2159 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2160 GDBusMessage *message,
2163 GDBusConnection *connection;
2164 FilterCallback *filters;
2169 G_LOCK (message_bus_lock);
2170 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2173 G_UNLOCK (message_bus_lock);
2176 connection = G_DBUS_CONNECTION (user_data);
2177 g_object_ref (connection);
2178 G_UNLOCK (message_bus_lock);
2180 //g_debug ("in on_worker_message_about_to_be_sent");
2182 /* First collect the set of callback functions */
2183 CONNECTION_LOCK (connection);
2184 num_filters = connection->filters->len;
2185 filters = g_new0 (FilterCallback, num_filters);
2186 for (n = 0; n < num_filters; n++)
2188 FilterData *data = connection->filters->pdata[n];
2189 filters[n].func = data->filter_function;
2190 filters[n].user_data = data->user_data;
2192 CONNECTION_UNLOCK (connection);
2194 /* then call the filters in order (without holding the lock) */
2195 for (n = 0; n < num_filters; n++)
2197 g_dbus_message_lock (message);
2198 message = filters[n].func (connection,
2201 filters[n].user_data);
2202 if (message == NULL)
2206 g_object_unref (connection);
2212 /* Called in worker's thread - we must not block */
2214 on_worker_closed (GDBusWorker *worker,
2215 gboolean remote_peer_vanished,
2219 GDBusConnection *connection;
2222 G_LOCK (message_bus_lock);
2223 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2226 G_UNLOCK (message_bus_lock);
2229 connection = G_DBUS_CONNECTION (user_data);
2230 g_object_ref (connection);
2231 G_UNLOCK (message_bus_lock);
2233 //g_debug ("in on_worker_closed: %s", error->message);
2235 CONNECTION_LOCK (connection);
2236 if (!connection->closed)
2237 set_closed_unlocked (connection, remote_peer_vanished, error);
2238 CONNECTION_UNLOCK (connection);
2240 g_object_unref (connection);
2243 /* ---------------------------------------------------------------------------------------------------- */
2245 /* Determines the biggest set of capabilities we can support on this connection */
2246 static GDBusCapabilityFlags
2247 get_offered_capabilities_max (GDBusConnection *connection)
2249 GDBusCapabilityFlags ret;
2250 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2252 if (G_IS_UNIX_CONNECTION (connection->stream))
2253 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2259 initable_init (GInitable *initable,
2260 GCancellable *cancellable,
2263 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2266 /* This method needs to be idempotent to work with the singleton
2267 * pattern. See the docs for g_initable_init(). We implement this by
2270 * Unfortunately we can't use the main lock since the on_worker_*()
2271 * callbacks above needs the lock during initialization (for message
2272 * bus connections we do a synchronous Hello() call on the bus).
2274 g_mutex_lock (&connection->init_lock);
2278 /* First, handle the case where the connection already has an
2279 * initialization error set.
2281 if (connection->initialization_error != NULL)
2284 /* Also make this a no-op if we're already initialized fine */
2285 if (connection->is_initialized)
2291 g_assert (connection->initialization_error == NULL && !connection->is_initialized);
2293 /* The user can pass multiple (but mutally exclusive) construct
2296 * - stream (of type GIOStream)
2297 * - address (of type gchar*)
2299 * At the end of the day we end up with a non-NULL GIOStream
2300 * object in connection->stream.
2302 if (connection->address != NULL)
2304 g_assert (connection->stream == NULL);
2306 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2307 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2309 g_set_error_literal (error,
2311 G_IO_ERROR_INVALID_ARGUMENT,
2312 _("Unsupported flags encountered when constructing a client-side connection"));
2316 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2317 NULL, /* TODO: out_guid */
2319 &connection->initialization_error);
2320 if (connection->stream == NULL)
2323 else if (connection->stream != NULL)
2329 g_assert_not_reached ();
2332 /* Authenticate the connection */
2333 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2335 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2336 g_assert (connection->guid != NULL);
2337 connection->auth = _g_dbus_auth_new (connection->stream);
2338 if (!_g_dbus_auth_run_server (connection->auth,
2339 connection->authentication_observer,
2341 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2342 get_offered_capabilities_max (connection),
2343 &connection->capabilities,
2344 &connection->credentials,
2346 &connection->initialization_error))
2349 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2351 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2352 g_assert (connection->guid == NULL);
2353 connection->auth = _g_dbus_auth_new (connection->stream);
2354 connection->guid = _g_dbus_auth_run_client (connection->auth,
2355 get_offered_capabilities_max (connection),
2356 &connection->capabilities,
2358 &connection->initialization_error);
2359 if (connection->guid == NULL)
2363 if (connection->authentication_observer != NULL)
2365 g_object_unref (connection->authentication_observer);
2366 connection->authentication_observer = NULL;
2369 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2371 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2374 /* We want all IO operations to be non-blocking since they happen in
2375 * the worker thread which is shared by _all_ connections.
2377 if (G_IS_SOCKET_CONNECTION (connection->stream))
2379 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2383 G_LOCK (message_bus_lock);
2384 if (alive_connections == NULL)
2385 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2386 g_hash_table_insert (alive_connections, connection, connection);
2387 G_UNLOCK (message_bus_lock);
2389 connection->worker = _g_dbus_worker_new (connection->stream,
2390 connection->capabilities,
2391 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2392 on_worker_message_received,
2393 on_worker_message_about_to_be_sent,
2397 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2398 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2400 GVariant *hello_result;
2402 /* we could lift this restriction by adding code in gdbusprivate.c */
2403 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2405 g_set_error_literal (&connection->initialization_error,
2408 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2412 hello_result = g_dbus_connection_call_sync (connection,
2413 "org.freedesktop.DBus", /* name */
2414 "/org/freedesktop/DBus", /* path */
2415 "org.freedesktop.DBus", /* interface */
2417 NULL, /* parameters */
2418 G_VARIANT_TYPE ("(s)"),
2419 G_DBUS_CALL_FLAGS_NONE,
2421 NULL, /* TODO: cancellable */
2422 &connection->initialization_error);
2423 if (hello_result == NULL)
2426 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2427 g_variant_unref (hello_result);
2428 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2431 connection->is_initialized = TRUE;
2437 g_assert (connection->initialization_error != NULL);
2438 g_propagate_error (error, g_error_copy (connection->initialization_error));
2441 g_mutex_unlock (&connection->init_lock);
2447 initable_iface_init (GInitableIface *initable_iface)
2449 initable_iface->init = initable_init;
2452 /* ---------------------------------------------------------------------------------------------------- */
2455 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2460 /* ---------------------------------------------------------------------------------------------------- */
2463 * g_dbus_connection_new:
2464 * @stream: A #GIOStream.
2465 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2466 * @flags: Flags describing how to make the connection.
2467 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2468 * @cancellable: A #GCancellable or %NULL.
2469 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2470 * @user_data: The data to pass to @callback.
2472 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2473 * with the end represented by @stream.
2475 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2476 * will be put into non-blocking mode.
2478 * If @observer is not %NULL it may be used to control the
2479 * authentication process.
2481 * When the operation is finished, @callback will be invoked. You can
2482 * then call g_dbus_connection_new_finish() to get the result of the
2485 * This is a asynchronous failable constructor. See
2486 * g_dbus_connection_new_sync() for the synchronous
2492 g_dbus_connection_new (GIOStream *stream,
2494 GDBusConnectionFlags flags,
2495 GDBusAuthObserver *observer,
2496 GCancellable *cancellable,
2497 GAsyncReadyCallback callback,
2500 g_return_if_fail (G_IS_IO_STREAM (stream));
2501 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2509 "authentication-observer", observer,
2514 * g_dbus_connection_new_finish:
2515 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2516 * @error: Return location for error or %NULL.
2518 * Finishes an operation started with g_dbus_connection_new().
2520 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2525 g_dbus_connection_new_finish (GAsyncResult *res,
2529 GObject *source_object;
2531 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2532 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2534 source_object = g_async_result_get_source_object (res);
2535 g_assert (source_object != NULL);
2536 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2539 g_object_unref (source_object);
2541 return G_DBUS_CONNECTION (object);
2547 * g_dbus_connection_new_sync:
2548 * @stream: A #GIOStream.
2549 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2550 * @flags: Flags describing how to make the connection.
2551 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2552 * @cancellable: A #GCancellable or %NULL.
2553 * @error: Return location for error or %NULL.
2555 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2556 * with the end represented by @stream.
2558 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2559 * will be put into non-blocking mode.
2561 * If @observer is not %NULL it may be used to control the
2562 * authentication process.
2564 * This is a synchronous failable constructor. See
2565 * g_dbus_connection_new() for the asynchronous version.
2567 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2572 g_dbus_connection_new_sync (GIOStream *stream,
2574 GDBusConnectionFlags flags,
2575 GDBusAuthObserver *observer,
2576 GCancellable *cancellable,
2579 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2580 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2581 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2587 "authentication-observer", observer,
2591 /* ---------------------------------------------------------------------------------------------------- */
2594 * g_dbus_connection_new_for_address:
2595 * @address: A D-Bus address.
2596 * @flags: Flags describing how to make the connection.
2597 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2598 * @cancellable: A #GCancellable or %NULL.
2599 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2600 * @user_data: The data to pass to @callback.
2602 * Asynchronously connects and sets up a D-Bus client connection for
2603 * exchanging D-Bus messages with an endpoint specified by @address
2604 * which must be in the D-Bus address format.
2606 * This constructor can only be used to initiate client-side
2607 * connections - use g_dbus_connection_new() if you need to act as the
2608 * server. In particular, @flags cannot contain the
2609 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2610 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2612 * When the operation is finished, @callback will be invoked. You can
2613 * then call g_dbus_connection_new_finish() to get the result of the
2616 * If @observer is not %NULL it may be used to control the
2617 * authentication process.
2619 * This is a asynchronous failable constructor. See
2620 * g_dbus_connection_new_for_address_sync() for the synchronous
2626 g_dbus_connection_new_for_address (const gchar *address,
2627 GDBusConnectionFlags flags,
2628 GDBusAuthObserver *observer,
2629 GCancellable *cancellable,
2630 GAsyncReadyCallback callback,
2633 g_return_if_fail (address != NULL);
2634 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2641 "authentication-observer", observer,
2646 * g_dbus_connection_new_for_address_finish:
2647 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2648 * @error: Return location for error or %NULL.
2650 * Finishes an operation started with g_dbus_connection_new_for_address().
2652 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2657 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2661 GObject *source_object;
2663 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2664 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2666 source_object = g_async_result_get_source_object (res);
2667 g_assert (source_object != NULL);
2668 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2671 g_object_unref (source_object);
2673 return G_DBUS_CONNECTION (object);
2679 * g_dbus_connection_new_for_address_sync:
2680 * @address: A D-Bus address.
2681 * @flags: Flags describing how to make the connection.
2682 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2683 * @cancellable: A #GCancellable or %NULL.
2684 * @error: Return location for error or %NULL.
2686 * Synchronously connects and sets up a D-Bus client connection for
2687 * exchanging D-Bus messages with an endpoint specified by @address
2688 * which must be in the D-Bus address format.
2690 * This constructor can only be used to initiate client-side
2691 * connections - use g_dbus_connection_new_sync() if you need to act
2692 * as the server. In particular, @flags cannot contain the
2693 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2694 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2696 * This is a synchronous failable constructor. See
2697 * g_dbus_connection_new_for_address() for the asynchronous version.
2699 * If @observer is not %NULL it may be used to control the
2700 * authentication process.
2702 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2707 g_dbus_connection_new_for_address_sync (const gchar *address,
2708 GDBusConnectionFlags flags,
2709 GDBusAuthObserver *observer,
2710 GCancellable *cancellable,
2713 g_return_val_if_fail (address != NULL, NULL);
2714 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2715 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2720 "authentication-observer", observer,
2724 /* ---------------------------------------------------------------------------------------------------- */
2727 * g_dbus_connection_set_exit_on_close:
2728 * @connection: A #GDBusConnection.
2729 * @exit_on_close: Whether the process should be terminated
2730 * when @connection is closed by the remote peer.
2732 * Sets whether the process should be terminated when @connection is
2733 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2736 * Note that this function should be used with care. Most modern UNIX
2737 * desktops tie the notion of a user session the session bus, and expect
2738 * all of a users applications to quit when their bus connection goes away.
2739 * If you are setting @exit_on_close to %FALSE for the shared session
2740 * bus connection, you should make sure that your application exits
2741 * when the user session ends.
2746 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2747 gboolean exit_on_close)
2749 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2750 connection->exit_on_close = exit_on_close;
2754 * g_dbus_connection_get_exit_on_close:
2755 * @connection: A #GDBusConnection.
2757 * Gets whether the process is terminated when @connection is
2758 * closed by the remote peer. See
2759 * #GDBusConnection:exit-on-close for more details.
2761 * Returns: Whether the process is terminated when @connection is
2762 * closed by the remote peer.
2767 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2769 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2770 return connection->exit_on_close;
2774 * g_dbus_connection_get_guid:
2775 * @connection: A #GDBusConnection.
2777 * The GUID of the peer performing the role of server when
2778 * authenticating. See #GDBusConnection:guid for more details.
2780 * Returns: The GUID. Do not free this string, it is owned by
2786 g_dbus_connection_get_guid (GDBusConnection *connection)
2788 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2789 return connection->guid;
2793 * g_dbus_connection_get_unique_name:
2794 * @connection: A #GDBusConnection.
2796 * Gets the unique name of @connection as assigned by the message
2797 * bus. This can also be used to figure out if @connection is a
2798 * message bus connection.
2800 * Returns: The unique name or %NULL if @connection is not a message
2801 * bus connection. Do not free this string, it is owned by
2807 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2809 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2810 return connection->bus_unique_name;
2814 * g_dbus_connection_get_peer_credentials:
2815 * @connection: A #GDBusConnection.
2817 * Gets the credentials of the authenticated peer. This will always
2818 * return %NULL unless @connection acted as a server
2819 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2820 * when set up and the client passed credentials as part of the
2821 * authentication process.
2823 * In a message bus setup, the message bus is always the server and
2824 * each application is a client. So this method will always return
2825 * %NULL for message bus clients.
2827 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
2828 * this object, it is owned by @connection.
2833 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2835 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2836 return connection->credentials;
2839 /* ---------------------------------------------------------------------------------------------------- */
2841 static guint _global_filter_id = 1;
2844 * g_dbus_connection_add_filter:
2845 * @connection: A #GDBusConnection.
2846 * @filter_function: A filter function.
2847 * @user_data: User data to pass to @filter_function.
2848 * @user_data_free_func: Function to free @user_data with when filter
2849 * is removed or %NULL.
2851 * Adds a message filter. Filters are handlers that are run on all
2852 * incoming and outgoing messages, prior to standard dispatch. Filters
2853 * are run in the order that they were added. The same handler can be
2854 * added as a filter more than once, in which case it will be run more
2855 * than once. Filters added during a filter callback won't be run on
2856 * the message being processed. Filter functions are allowed to modify
2857 * and even drop messages.
2859 * Note that filters are run in a dedicated message handling thread so
2860 * they can't block and, generally, can't do anything but signal a
2861 * worker thread. Also note that filters are rarely needed - use API
2862 * such as g_dbus_connection_send_message_with_reply(),
2863 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
2865 * If a filter consumes an incoming message the message is not
2866 * dispatched anywhere else - not even the standard dispatch machinery
2867 * (that API such as g_dbus_connection_signal_subscribe() and
2868 * g_dbus_connection_send_message_with_reply() relies on) will see the
2869 * message. Similary, if a filter consumes an outgoing message, the
2870 * message will not be sent to the other peer.
2872 * Returns: A filter identifier that can be used with
2873 * g_dbus_connection_remove_filter().
2878 g_dbus_connection_add_filter (GDBusConnection *connection,
2879 GDBusMessageFilterFunction filter_function,
2881 GDestroyNotify user_data_free_func)
2885 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2886 g_return_val_if_fail (filter_function != NULL, 0);
2888 CONNECTION_LOCK (connection);
2889 data = g_new0 (FilterData, 1);
2890 data->id = _global_filter_id++; /* TODO: overflow etc. */
2891 data->filter_function = filter_function;
2892 data->user_data = user_data;
2893 data->user_data_free_func = user_data_free_func;
2894 g_ptr_array_add (connection->filters, data);
2895 CONNECTION_UNLOCK (connection);
2900 /* only called from finalize(), removes all filters */
2902 purge_all_filters (GDBusConnection *connection)
2905 for (n = 0; n < connection->filters->len; n++)
2907 FilterData *data = connection->filters->pdata[n];
2908 if (data->user_data_free_func != NULL)
2909 data->user_data_free_func (data->user_data);
2915 * g_dbus_connection_remove_filter:
2916 * @connection: a #GDBusConnection
2917 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2924 g_dbus_connection_remove_filter (GDBusConnection *connection,
2928 FilterData *to_destroy;
2930 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2932 CONNECTION_LOCK (connection);
2934 for (n = 0; n < connection->filters->len; n++)
2936 FilterData *data = connection->filters->pdata[n];
2937 if (data->id == filter_id)
2939 g_ptr_array_remove_index (connection->filters, n);
2944 CONNECTION_UNLOCK (connection);
2946 /* do free without holding lock */
2947 if (to_destroy != NULL)
2949 if (to_destroy->user_data_free_func != NULL)
2950 to_destroy->user_data_free_func (to_destroy->user_data);
2951 g_free (to_destroy);
2955 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2959 /* ---------------------------------------------------------------------------------------------------- */
2965 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2966 gchar *interface_name;
2970 GArray *subscribers;
2975 GDBusSignalCallback callback;
2977 GDestroyNotify user_data_free_func;
2979 GMainContext *context;
2983 signal_data_free (SignalData *signal_data)
2985 g_free (signal_data->rule);
2986 g_free (signal_data->sender);
2987 g_free (signal_data->sender_unique_name);
2988 g_free (signal_data->interface_name);
2989 g_free (signal_data->member);
2990 g_free (signal_data->object_path);
2991 g_free (signal_data->arg0);
2992 g_array_free (signal_data->subscribers, TRUE);
2993 g_free (signal_data);
2997 args_to_rule (const gchar *sender,
2998 const gchar *interface_name,
2999 const gchar *member,
3000 const gchar *object_path,
3006 rule = g_string_new ("type='signal'");
3008 g_string_prepend_c (rule, '-');
3010 g_string_append_printf (rule, ",sender='%s'", sender);
3011 if (interface_name != NULL)
3012 g_string_append_printf (rule, ",interface='%s'", interface_name);
3014 g_string_append_printf (rule, ",member='%s'", member);
3015 if (object_path != NULL)
3016 g_string_append_printf (rule, ",path='%s'", object_path);
3018 g_string_append_printf (rule, ",arg0='%s'", arg0);
3020 return g_string_free (rule, FALSE);
3023 static guint _global_subscriber_id = 1;
3024 static guint _global_registration_id = 1;
3025 static guint _global_subtree_registration_id = 1;
3027 /* ---------------------------------------------------------------------------------------------------- */
3029 /* must hold lock when calling */
3031 add_match_rule (GDBusConnection *connection,
3032 const gchar *match_rule)
3035 GDBusMessage *message;
3037 if (match_rule[0] == '-')
3040 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3041 "/org/freedesktop/DBus", /* path */
3042 "org.freedesktop.DBus", /* interface */
3044 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3046 if (!g_dbus_connection_send_message_unlocked (connection,
3048 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3052 g_critical ("Error while sending AddMatch() message: %s", error->message);
3053 g_error_free (error);
3055 g_object_unref (message);
3058 /* ---------------------------------------------------------------------------------------------------- */
3060 /* must hold lock when calling */
3062 remove_match_rule (GDBusConnection *connection,
3063 const gchar *match_rule)
3066 GDBusMessage *message;
3068 if (match_rule[0] == '-')
3071 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3072 "/org/freedesktop/DBus", /* path */
3073 "org.freedesktop.DBus", /* interface */
3075 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3078 if (!g_dbus_connection_send_message_unlocked (connection,
3080 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3084 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3085 g_error_free (error);
3087 g_object_unref (message);
3090 /* ---------------------------------------------------------------------------------------------------- */
3093 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3095 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3096 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3097 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3098 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3099 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3102 /* ---------------------------------------------------------------------------------------------------- */
3105 * g_dbus_connection_signal_subscribe:
3106 * @connection: A #GDBusConnection.
3107 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3108 * or %NULL to listen from all senders.
3109 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3110 * match on all interfaces.
3111 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3112 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3113 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3114 * to match on all kinds of arguments.
3115 * @flags: Flags describing how to subscribe to the signal (currently unused).
3116 * @callback: Callback to invoke when there is a signal matching the requested data.
3117 * @user_data: User data to pass to @callback.
3118 * @user_data_free_func: (allow-none): Function to free @user_data with when
3119 * subscription is removed or %NULL.
3121 * Subscribes to signals on @connection and invokes @callback with a
3122 * whenever the signal is received. Note that @callback
3123 * will be invoked in the <link
3124 * linkend="g-main-context-push-thread-default">thread-default main
3125 * loop</link> of the thread you are calling this method from.
3127 * If @connection is not a message bus connection, @sender must be
3130 * If @sender is a well-known name note that @callback is invoked with
3131 * the unique name for the owner of @sender, not the well-known name
3132 * as one would expect. This is because the message bus rewrites the
3133 * name. As such, to avoid certain race conditions, users should be
3134 * tracking the name owner of the well-known name and use that when
3135 * processing the received signal.
3137 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3142 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3143 const gchar *sender,
3144 const gchar *interface_name,
3145 const gchar *member,
3146 const gchar *object_path,
3148 GDBusSignalFlags flags,
3149 GDBusSignalCallback callback,
3151 GDestroyNotify user_data_free_func)
3154 SignalData *signal_data;
3155 SignalSubscriber subscriber;
3156 GPtrArray *signal_data_array;
3157 const gchar *sender_unique_name;
3159 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3160 * an OOM condition. We might want to change that but that would involve making
3161 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3162 * handle that. And there's really no sensible way of handling this short of retrying
3163 * to add the match rule... and then there's the little thing that, hey, maybe there's
3164 * a reason the bus in an OOM condition.
3166 * Doable, but not really sure it's worth it...
3169 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3170 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3171 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3172 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3173 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3174 g_return_val_if_fail (callback != NULL, 0);
3176 CONNECTION_LOCK (connection);
3178 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3179 * with a '-' character to prefix the rule (which will otherwise be
3182 * This allows us to hash the rule and do our lifecycle tracking in
3183 * the usual way, but the '-' prevents the match rule from ever
3184 * actually being send to the bus (either for add or remove).
3186 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3187 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3189 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3190 sender_unique_name = sender;
3192 sender_unique_name = "";
3194 subscriber.callback = callback;
3195 subscriber.user_data = user_data;
3196 subscriber.user_data_free_func = user_data_free_func;
3197 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3198 subscriber.context = g_main_context_get_thread_default ();
3199 if (subscriber.context != NULL)
3200 g_main_context_ref (subscriber.context);
3202 /* see if we've already have this rule */
3203 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3204 if (signal_data != NULL)
3206 g_array_append_val (signal_data->subscribers, subscriber);
3211 signal_data = g_new0 (SignalData, 1);
3212 signal_data->rule = rule;
3213 signal_data->sender = g_strdup (sender);
3214 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3215 signal_data->interface_name = g_strdup (interface_name);
3216 signal_data->member = g_strdup (member);
3217 signal_data->object_path = g_strdup (object_path);
3218 signal_data->arg0 = g_strdup (arg0);
3219 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3220 g_array_append_val (signal_data->subscribers, subscriber);
3222 g_hash_table_insert (connection->map_rule_to_signal_data,
3226 /* Add the match rule to the bus...
3228 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3229 * always send such messages to us.
3231 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3233 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3234 add_match_rule (connection, signal_data->rule);
3237 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3238 signal_data->sender_unique_name);
3239 if (signal_data_array == NULL)
3241 signal_data_array = g_ptr_array_new ();
3242 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3243 g_strdup (signal_data->sender_unique_name),
3246 g_ptr_array_add (signal_data_array, signal_data);
3249 g_hash_table_insert (connection->map_id_to_signal_data,
3250 GUINT_TO_POINTER (subscriber.id),
3253 CONNECTION_UNLOCK (connection);
3255 return subscriber.id;
3258 /* ---------------------------------------------------------------------------------------------------- */
3260 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3262 unsubscribe_id_internal (GDBusConnection *connection,
3263 guint subscription_id,
3264 GArray *out_removed_subscribers)
3266 SignalData *signal_data;
3267 GPtrArray *signal_data_array;
3270 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3271 GUINT_TO_POINTER (subscription_id));
3272 if (signal_data == NULL)
3274 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3278 for (n = 0; n < signal_data->subscribers->len; n++)
3280 SignalSubscriber *subscriber;
3282 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3283 if (subscriber->id != subscription_id)
3286 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3287 GUINT_TO_POINTER (subscription_id)));
3288 g_array_append_val (out_removed_subscribers, *subscriber);
3289 g_array_remove_index (signal_data->subscribers, n);
3291 if (signal_data->subscribers->len == 0)
3293 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3295 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3296 signal_data->sender_unique_name);
3297 g_warn_if_fail (signal_data_array != NULL);
3298 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3300 if (signal_data_array->len == 0)
3302 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3303 signal_data->sender_unique_name));
3306 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3307 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3309 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3310 if (!connection->closed && !connection->finalizing)
3311 remove_match_rule (connection, signal_data->rule);
3313 signal_data_free (signal_data);
3319 g_assert_not_reached ();
3326 * g_dbus_connection_signal_unsubscribe:
3327 * @connection: A #GDBusConnection.
3328 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3330 * Unsubscribes from signals.
3335 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3336 guint subscription_id)
3338 GArray *subscribers;
3341 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3343 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3345 CONNECTION_LOCK (connection);
3346 unsubscribe_id_internal (connection,
3349 CONNECTION_UNLOCK (connection);
3352 g_assert (subscribers->len == 0 || subscribers->len == 1);
3354 /* call GDestroyNotify without lock held */
3355 for (n = 0; n < subscribers->len; n++)
3357 SignalSubscriber *subscriber;
3358 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3359 call_destroy_notify (subscriber->context,
3360 subscriber->user_data_free_func,
3361 subscriber->user_data);
3362 if (subscriber->context != NULL)
3363 g_main_context_unref (subscriber->context);
3366 g_array_free (subscribers, TRUE);
3369 /* ---------------------------------------------------------------------------------------------------- */
3373 guint subscription_id;
3374 GDBusSignalCallback callback;
3376 GDBusMessage *message;
3377 GDBusConnection *connection;
3378 const gchar *sender;
3380 const gchar *interface;
3381 const gchar *member;
3384 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3388 emit_signal_instance_in_idle_cb (gpointer data)
3390 SignalInstance *signal_instance = data;
3391 GVariant *parameters;
3392 gboolean has_subscription;
3394 parameters = g_dbus_message_get_body (signal_instance->message);
3395 if (parameters == NULL)
3397 parameters = g_variant_new ("()");
3398 g_variant_ref_sink (parameters);
3402 g_variant_ref_sink (parameters);
3406 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3407 signal_instance->subscription_id,
3408 signal_instance->sender,
3409 signal_instance->path,
3410 signal_instance->interface,
3411 signal_instance->member,
3412 g_variant_print (parameters, TRUE));
3415 /* Careful here, don't do the callback if we no longer has the subscription */
3416 CONNECTION_LOCK (signal_instance->connection);
3417 has_subscription = FALSE;
3418 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3419 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3420 has_subscription = TRUE;
3421 CONNECTION_UNLOCK (signal_instance->connection);
3423 if (has_subscription)
3424 signal_instance->callback (signal_instance->connection,
3425 signal_instance->sender,
3426 signal_instance->path,
3427 signal_instance->interface,
3428 signal_instance->member,
3430 signal_instance->user_data);
3432 g_variant_unref (parameters);
3438 signal_instance_free (SignalInstance *signal_instance)
3440 g_object_unref (signal_instance->message);
3441 g_object_unref (signal_instance->connection);
3442 g_free (signal_instance);
3445 /* called in message handler thread WITH lock held */
3447 schedule_callbacks (GDBusConnection *connection,
3448 GPtrArray *signal_data_array,
3449 GDBusMessage *message,
3450 const gchar *sender)
3453 const gchar *interface;
3454 const gchar *member;
3463 interface = g_dbus_message_get_interface (message);
3464 member = g_dbus_message_get_member (message);
3465 path = g_dbus_message_get_path (message);
3466 arg0 = g_dbus_message_get_arg0 (message);
3469 g_print ("In schedule_callbacks:\n"
3471 " interface = `%s'\n"
3482 /* TODO: if this is slow, then we can change signal_data_array into
3483 * map_object_path_to_signal_data_array or something.
3485 for (n = 0; n < signal_data_array->len; n++)
3487 SignalData *signal_data = signal_data_array->pdata[n];
3489 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3492 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3495 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3498 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3501 for (m = 0; m < signal_data->subscribers->len; m++)
3503 SignalSubscriber *subscriber;
3504 GSource *idle_source;
3505 SignalInstance *signal_instance;
3507 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3509 signal_instance = g_new0 (SignalInstance, 1);
3510 signal_instance->subscription_id = subscriber->id;
3511 signal_instance->callback = subscriber->callback;
3512 signal_instance->user_data = subscriber->user_data;
3513 signal_instance->message = g_object_ref (message);
3514 signal_instance->connection = g_object_ref (connection);
3515 signal_instance->sender = sender;
3516 signal_instance->path = path;
3517 signal_instance->interface = interface;
3518 signal_instance->member = member;
3520 idle_source = g_idle_source_new ();
3521 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3522 g_source_set_callback (idle_source,
3523 emit_signal_instance_in_idle_cb,
3525 (GDestroyNotify) signal_instance_free);
3526 g_source_attach (idle_source, subscriber->context);
3527 g_source_unref (idle_source);
3532 /* called in message handler thread with lock held */
3534 distribute_signals (GDBusConnection *connection,
3535 GDBusMessage *message)
3537 GPtrArray *signal_data_array;
3538 const gchar *sender;
3540 sender = g_dbus_message_get_sender (message);
3542 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3544 _g_dbus_debug_print_lock ();
3545 g_print ("========================================================================\n"
3546 "GDBus-debug:Signal:\n"
3547 " <<<< RECEIVED SIGNAL %s.%s\n"
3549 " sent by name %s\n",
3550 g_dbus_message_get_interface (message),
3551 g_dbus_message_get_member (message),
3552 g_dbus_message_get_path (message),
3553 sender != NULL ? sender : "(none)");
3554 _g_dbus_debug_print_unlock ();
3557 /* collect subscribers that match on sender */
3560 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3561 if (signal_data_array != NULL)
3562 schedule_callbacks (connection, signal_data_array, message, sender);
3565 /* collect subscribers not matching on sender */
3566 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3567 if (signal_data_array != NULL)
3568 schedule_callbacks (connection, signal_data_array, message, sender);
3571 /* ---------------------------------------------------------------------------------------------------- */
3573 /* only called from finalize(), removes all subscriptions */
3575 purge_all_signal_subscriptions (GDBusConnection *connection)
3577 GHashTableIter iter;
3580 GArray *subscribers;
3583 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3584 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3585 while (g_hash_table_iter_next (&iter, &key, NULL))
3587 guint subscription_id = GPOINTER_TO_UINT (key);
3588 g_array_append_val (ids, subscription_id);
3591 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3592 for (n = 0; n < ids->len; n++)
3594 guint subscription_id = g_array_index (ids, guint, n);
3595 unsubscribe_id_internal (connection,
3599 g_array_free (ids, TRUE);
3601 /* call GDestroyNotify without lock held */
3602 for (n = 0; n < subscribers->len; n++)
3604 SignalSubscriber *subscriber;
3605 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3606 call_destroy_notify (subscriber->context,
3607 subscriber->user_data_free_func,
3608 subscriber->user_data);
3609 if (subscriber->context != NULL)
3610 g_main_context_unref (subscriber->context);
3613 g_array_free (subscribers, TRUE);
3616 /* ---------------------------------------------------------------------------------------------------- */
3618 static GDBusInterfaceVTable *
3619 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3621 /* Don't waste memory by copying padding - remember to update this
3622 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3624 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3628 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3633 /* ---------------------------------------------------------------------------------------------------- */
3635 static GDBusSubtreeVTable *
3636 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3638 /* Don't waste memory by copying padding - remember to update this
3639 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3641 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3645 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3650 /* ---------------------------------------------------------------------------------------------------- */
3652 struct ExportedObject
3655 GDBusConnection *connection;
3657 /* maps gchar* -> ExportedInterface* */
3658 GHashTable *map_if_name_to_ei;
3661 /* only called with lock held */
3663 exported_object_free (ExportedObject *eo)
3665 g_free (eo->object_path);
3666 g_hash_table_unref (eo->map_if_name_to_ei);
3675 gchar *interface_name;
3676 GDBusInterfaceVTable *vtable;
3677 GDBusInterfaceInfo *interface_info;
3679 GMainContext *context;
3681 GDestroyNotify user_data_free_func;
3682 } ExportedInterface;
3684 /* called with lock held */
3686 exported_interface_free (ExportedInterface *ei)
3688 g_dbus_interface_info_cache_release (ei->interface_info);
3689 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3691 call_destroy_notify (ei->context,
3692 ei->user_data_free_func,
3695 if (ei->context != NULL)
3696 g_main_context_unref (ei->context);
3698 g_free (ei->interface_name);
3699 _g_dbus_interface_vtable_free (ei->vtable);
3703 /* ---------------------------------------------------------------------------------------------------- */
3705 /* Convenience function to check if @registration_id (if not zero) or
3706 * @subtree_registration_id (if not zero) has been unregistered. If
3707 * so, returns %TRUE.
3709 * Caller must *not* hold lock.
3712 has_object_been_unregistered (GDBusConnection *connection,
3713 guint registration_id,
3714 guint subtree_registration_id)
3718 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3722 CONNECTION_LOCK (connection);
3723 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3724 GUINT_TO_POINTER (registration_id)) == NULL)
3728 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3729 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3733 CONNECTION_UNLOCK (connection);
3738 /* ---------------------------------------------------------------------------------------------------- */
3742 GDBusConnection *connection;
3743 GDBusMessage *message;
3745 const gchar *property_name;
3746 const GDBusInterfaceVTable *vtable;
3747 GDBusInterfaceInfo *interface_info;
3748 const GDBusPropertyInfo *property_info;
3749 guint registration_id;
3750 guint subtree_registration_id;
3754 property_data_free (PropertyData *data)
3756 g_object_unref (data->connection);
3757 g_object_unref (data->message);
3761 /* called in thread where object was registered - no locks held */
3763 invoke_get_property_in_idle_cb (gpointer _data)
3765 PropertyData *data = _data;
3768 GDBusMessage *reply;
3770 if (has_object_been_unregistered (data->connection,
3771 data->registration_id,
3772 data->subtree_registration_id))
3774 reply = g_dbus_message_new_method_error (data->message,
3775 "org.freedesktop.DBus.Error.UnknownMethod",
3776 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3777 g_dbus_message_get_path (data->message));
3778 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3779 g_object_unref (reply);
3784 value = data->vtable->get_property (data->connection,
3785 g_dbus_message_get_sender (data->message),
3786 g_dbus_message_get_path (data->message),
3787 data->interface_info->name,
3788 data->property_name,
3795 g_assert_no_error (error);
3797 g_variant_take_ref (value);
3798 reply = g_dbus_message_new_method_reply (data->message);
3799 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3800 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3801 g_variant_unref (value);
3802 g_object_unref (reply);
3806 gchar *dbus_error_name;
3807 g_assert (error != NULL);
3808 dbus_error_name = g_dbus_error_encode_gerror (error);
3809 reply = g_dbus_message_new_method_error_literal (data->message,
3812 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3813 g_free (dbus_error_name);
3814 g_error_free (error);
3815 g_object_unref (reply);
3822 /* called in thread where object was registered - no locks held */
3824 invoke_set_property_in_idle_cb (gpointer _data)
3826 PropertyData *data = _data;
3828 GDBusMessage *reply;
3834 g_variant_get (g_dbus_message_get_body (data->message),
3840 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3841 * of the given value is wrong
3843 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3845 reply = g_dbus_message_new_method_error (data->message,
3846 "org.freedesktop.DBus.Error.InvalidArgs",
3847 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3848 data->property_info->name,
3849 data->property_info->signature,
3850 g_variant_get_type_string (value));
3854 if (!data->vtable->set_property (data->connection,
3855 g_dbus_message_get_sender (data->message),
3856 g_dbus_message_get_path (data->message),
3857 data->interface_info->name,
3858 data->property_name,
3863 gchar *dbus_error_name;
3864 g_assert (error != NULL);
3865 dbus_error_name = g_dbus_error_encode_gerror (error);
3866 reply = g_dbus_message_new_method_error_literal (data->message,
3869 g_free (dbus_error_name);
3870 g_error_free (error);
3874 reply = g_dbus_message_new_method_reply (data->message);
3878 g_assert (reply != NULL);
3879 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3880 g_object_unref (reply);
3881 g_variant_unref (value);
3886 /* called with lock held */
3888 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3889 GDBusMessage *message,
3890 guint registration_id,
3891 guint subtree_registration_id,
3893 GDBusInterfaceInfo *interface_info,
3894 const GDBusInterfaceVTable *vtable,
3895 GMainContext *main_context,
3899 const char *interface_name;
3900 const char *property_name;
3901 const GDBusPropertyInfo *property_info;
3902 GSource *idle_source;
3903 PropertyData *property_data;
3904 GDBusMessage *reply;
3909 g_variant_get (g_dbus_message_get_body (message),
3914 g_variant_get (g_dbus_message_get_body (message),
3923 if (vtable == NULL || vtable->get_property == NULL)
3928 if (vtable == NULL || vtable->set_property == NULL)
3932 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3934 property_info = NULL;
3936 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3937 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3938 if (property_info == NULL)
3940 reply = g_dbus_message_new_method_error (message,
3941 "org.freedesktop.DBus.Error.InvalidArgs",
3942 _("No such property `%s'"),
3944 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3945 g_object_unref (reply);
3950 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3952 reply = g_dbus_message_new_method_error (message,
3953 "org.freedesktop.DBus.Error.InvalidArgs",
3954 _("Property `%s' is not readable"),
3956 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3957 g_object_unref (reply);
3961 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3963 reply = g_dbus_message_new_method_error (message,
3964 "org.freedesktop.DBus.Error.InvalidArgs",
3965 _("Property `%s' is not writable"),
3967 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3968 g_object_unref (reply);
3973 /* ok, got the property info - call user code in an idle handler */
3974 property_data = g_new0 (PropertyData, 1);
3975 property_data->connection = g_object_ref (connection);
3976 property_data->message = g_object_ref (message);
3977 property_data->user_data = user_data;
3978 property_data->property_name = property_name;
3979 property_data->vtable = vtable;
3980 property_data->interface_info = interface_info;
3981 property_data->property_info = property_info;
3982 property_data->registration_id = registration_id;
3983 property_data->subtree_registration_id = subtree_registration_id;
3985 idle_source = g_idle_source_new ();
3986 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3987 g_source_set_callback (idle_source,
3988 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3990 (GDestroyNotify) property_data_free);
3991 g_source_attach (idle_source, main_context);
3992 g_source_unref (idle_source);
4000 /* called with lock held */
4002 handle_getset_property (GDBusConnection *connection,
4004 GDBusMessage *message,
4007 ExportedInterface *ei;
4009 const char *interface_name;
4010 const char *property_name;
4015 g_variant_get (g_dbus_message_get_body (message),
4020 g_variant_get (g_dbus_message_get_body (message),
4026 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4027 * no such interface registered
4029 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4032 GDBusMessage *reply;
4033 reply = g_dbus_message_new_method_error (message,
4034 "org.freedesktop.DBus.Error.InvalidArgs",
4035 _("No such interface `%s'"),
4037 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4038 g_object_unref (reply);
4043 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4056 /* ---------------------------------------------------------------------------------------------------- */
4060 GDBusConnection *connection;
4061 GDBusMessage *message;
4063 const GDBusInterfaceVTable *vtable;
4064 GDBusInterfaceInfo *interface_info;
4065 guint registration_id;
4066 guint subtree_registration_id;
4067 } PropertyGetAllData;
4070 property_get_all_data_free (PropertyData *data)
4072 g_object_unref (data->connection);
4073 g_object_unref (data->message);
4077 /* called in thread where object was registered - no locks held */
4079 invoke_get_all_properties_in_idle_cb (gpointer _data)
4081 PropertyGetAllData *data = _data;
4082 GVariantBuilder builder;
4083 GDBusMessage *reply;
4086 if (has_object_been_unregistered (data->connection,
4087 data->registration_id,
4088 data->subtree_registration_id))
4090 reply = g_dbus_message_new_method_error (data->message,
4091 "org.freedesktop.DBus.Error.UnknownMethod",
4092 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4093 g_dbus_message_get_path (data->message));
4094 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4095 g_object_unref (reply);
4099 /* TODO: Right now we never fail this call - we just omit values if
4100 * a get_property() call is failing.
4102 * We could fail the whole call if just a single get_property() call
4103 * returns an error. We need clarification in the D-Bus spec about this.
4105 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4106 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4107 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4109 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4112 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4115 value = data->vtable->get_property (data->connection,
4116 g_dbus_message_get_sender (data->message),
4117 g_dbus_message_get_path (data->message),
4118 data->interface_info->name,
4119 property_info->name,
4126 g_variant_take_ref (value);
4127 g_variant_builder_add (&builder,
4129 property_info->name,
4131 g_variant_unref (value);
4133 g_variant_builder_close (&builder);
4135 reply = g_dbus_message_new_method_reply (data->message);
4136 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4137 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4138 g_object_unref (reply);
4144 /* called with lock held */
4146 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4147 GDBusMessage *message,
4148 guint registration_id,
4149 guint subtree_registration_id,
4150 GDBusInterfaceInfo *interface_info,
4151 const GDBusInterfaceVTable *vtable,
4152 GMainContext *main_context,
4156 const char *interface_name;
4157 GSource *idle_source;
4158 PropertyGetAllData *property_get_all_data;
4162 g_variant_get (g_dbus_message_get_body (message),
4166 if (vtable == NULL || vtable->get_property == NULL)
4169 /* ok, got the property info - call user in an idle handler */
4170 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4171 property_get_all_data->connection = g_object_ref (connection);
4172 property_get_all_data->message = g_object_ref (message);
4173 property_get_all_data->user_data = user_data;
4174 property_get_all_data->vtable = vtable;
4175 property_get_all_data->interface_info = interface_info;
4176 property_get_all_data->registration_id = registration_id;
4177 property_get_all_data->subtree_registration_id = subtree_registration_id;
4179 idle_source = g_idle_source_new ();
4180 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4181 g_source_set_callback (idle_source,
4182 invoke_get_all_properties_in_idle_cb,
4183 property_get_all_data,
4184 (GDestroyNotify) property_get_all_data_free);
4185 g_source_attach (idle_source, main_context);
4186 g_source_unref (idle_source);
4194 /* called with lock held */
4196 handle_get_all_properties (GDBusConnection *connection,
4198 GDBusMessage *message)
4200 ExportedInterface *ei;
4202 const char *interface_name;
4206 g_variant_get (g_dbus_message_get_body (message),
4210 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4211 * no such interface registered
4213 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4216 GDBusMessage *reply;
4217 reply = g_dbus_message_new_method_error (message,
4218 "org.freedesktop.DBus.Error.InvalidArgs",
4219 _("No such interface"),
4221 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4222 g_object_unref (reply);
4227 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4239 /* ---------------------------------------------------------------------------------------------------- */
4241 static const gchar introspect_header[] =
4242 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4243 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4244 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4247 static const gchar introspect_tail[] =
4250 static const gchar introspect_properties_interface[] =
4251 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4252 " <method name=\"Get\">\n"
4253 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4254 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4255 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4257 " <method name=\"GetAll\">\n"
4258 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4259 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4261 " <method name=\"Set\">\n"
4262 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4263 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4264 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4266 " <signal name=\"PropertiesChanged\">\n"
4267 " <arg type=\"s\" name=\"interface_name\"/>\n"
4268 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4269 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4273 static const gchar introspect_introspectable_interface[] =
4274 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4275 " <method name=\"Introspect\">\n"
4276 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4279 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4280 " <method name=\"Ping\"/>\n"
4281 " <method name=\"GetMachineId\">\n"
4282 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4287 introspect_append_header (GString *s)
4289 g_string_append (s, introspect_header);
4293 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4295 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4301 begin = object_path + path_len;
4302 end = strchr (begin, '/');
4304 s = g_strndup (begin, end - begin);
4306 s = g_strdup (begin);
4308 if (g_hash_table_lookup (set, s) == NULL)
4309 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4315 /* TODO: we want a nicer public interface for this */
4317 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4322 GHashTableIter hash_iter;
4323 const gchar *object_path;
4329 CONNECTION_ENSURE_LOCK (connection);
4331 path_len = strlen (path);
4335 set = g_hash_table_new (g_str_hash, g_str_equal);
4337 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4338 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4339 maybe_add_path (path, path_len, object_path, set);
4341 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4342 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4343 maybe_add_path (path, path_len, object_path, set);
4345 p = g_ptr_array_new ();
4346 keys = g_hash_table_get_keys (set);
4347 for (l = keys; l != NULL; l = l->next)
4348 g_ptr_array_add (p, l->data);
4349 g_hash_table_unref (set);
4352 g_ptr_array_add (p, NULL);
4353 ret = (gchar **) g_ptr_array_free (p, FALSE);
4358 g_dbus_connection_list_registered (GDBusConnection *connection,
4362 CONNECTION_LOCK (connection);
4363 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4364 CONNECTION_UNLOCK (connection);
4368 /* called in message handler thread with lock held */
4370 handle_introspect (GDBusConnection *connection,
4372 GDBusMessage *message)
4376 GDBusMessage *reply;
4377 GHashTableIter hash_iter;
4378 ExportedInterface *ei;
4381 /* first the header with the standard interfaces */
4382 s = g_string_sized_new (sizeof (introspect_header) +
4383 sizeof (introspect_properties_interface) +
4384 sizeof (introspect_introspectable_interface) +
4385 sizeof (introspect_tail));
4386 introspect_append_header (s);
4387 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4388 "org.freedesktop.DBus.Properties"))
4389 g_string_append (s, introspect_properties_interface);
4391 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4392 "org.freedesktop.DBus.Introspectable"))
4393 g_string_append (s, introspect_introspectable_interface);
4395 /* then include the registered interfaces */
4396 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4397 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4398 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4400 /* finally include nodes registered below us */
4401 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4402 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4403 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4404 g_strfreev (registered);
4405 g_string_append (s, introspect_tail);
4407 reply = g_dbus_message_new_method_reply (message);
4408 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4409 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4410 g_object_unref (reply);
4411 g_string_free (s, TRUE);
4416 /* called in thread where object was registered - no locks held */
4418 call_in_idle_cb (gpointer user_data)
4420 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4421 GDBusInterfaceVTable *vtable;
4422 guint registration_id;
4423 guint subtree_registration_id;
4425 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4426 g_assert (vtable != NULL && vtable->method_call != NULL);
4428 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4429 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4431 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4433 subtree_registration_id))
4435 GDBusMessage *reply;
4436 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4437 "org.freedesktop.DBus.Error.UnknownMethod",
4438 _("No such interface `%s' on object at path %s"),
4439 g_dbus_method_invocation_get_interface_name (invocation),
4440 g_dbus_method_invocation_get_object_path (invocation));
4441 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4442 g_object_unref (reply);
4446 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4447 g_dbus_method_invocation_get_sender (invocation),
4448 g_dbus_method_invocation_get_object_path (invocation),
4449 g_dbus_method_invocation_get_interface_name (invocation),
4450 g_dbus_method_invocation_get_method_name (invocation),
4451 g_dbus_method_invocation_get_parameters (invocation),
4452 g_object_ref (invocation),
4453 g_dbus_method_invocation_get_user_data (invocation));
4459 /* called in message handler thread with lock held */
4461 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4462 GDBusMessage *message,
4463 guint registration_id,
4464 guint subtree_registration_id,
4465 GDBusInterfaceInfo *interface_info,
4466 const GDBusInterfaceVTable *vtable,
4467 GMainContext *main_context,
4470 GDBusMethodInvocation *invocation;
4471 const GDBusMethodInfo *method_info;
4472 GDBusMessage *reply;
4473 GVariant *parameters;
4474 GSource *idle_source;
4476 GVariantType *in_type;
4480 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4481 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4483 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4484 * error to the caller
4486 if (method_info == NULL)
4488 reply = g_dbus_message_new_method_error (message,
4489 "org.freedesktop.DBus.Error.UnknownMethod",
4490 _("No such method `%s'"),
4491 g_dbus_message_get_member (message));
4492 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4493 g_object_unref (reply);
4498 parameters = g_dbus_message_get_body (message);
4499 if (parameters == NULL)
4501 parameters = g_variant_new ("()");
4502 g_variant_ref_sink (parameters);
4506 g_variant_ref (parameters);
4509 /* Check that the incoming args are of the right type - if they are not, return
4510 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4512 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4513 if (!g_variant_is_of_type (parameters, in_type))
4517 type_string = g_variant_type_dup_string (in_type);
4519 reply = g_dbus_message_new_method_error (message,
4520 "org.freedesktop.DBus.Error.InvalidArgs",
4521 _("Type of message, `%s', does not match expected type `%s'"),
4522 g_variant_get_type_string (parameters),
4524 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4525 g_variant_type_free (in_type);
4526 g_variant_unref (parameters);
4527 g_object_unref (reply);
4528 g_free (type_string);
4532 g_variant_type_free (in_type);
4534 /* schedule the call in idle */
4535 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4536 g_dbus_message_get_path (message),
4537 g_dbus_message_get_interface (message),
4538 g_dbus_message_get_member (message),
4544 g_variant_unref (parameters);
4546 /* TODO: would be nicer with a real MethodData like we already
4547 * have PropertyData and PropertyGetAllData... */
4548 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4549 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4550 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4552 idle_source = g_idle_source_new ();
4553 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4554 g_source_set_callback (idle_source,
4558 g_source_attach (idle_source, main_context);
4559 g_source_unref (idle_source);
4567 /* ---------------------------------------------------------------------------------------------------- */
4569 /* called in message handler thread with lock held */
4571 obj_message_func (GDBusConnection *connection,
4573 GDBusMessage *message)
4575 const gchar *interface_name;
4576 const gchar *member;
4577 const gchar *signature;
4582 interface_name = g_dbus_message_get_interface (message);
4583 member = g_dbus_message_get_member (message);
4584 signature = g_dbus_message_get_signature (message);
4586 /* see if we have an interface for handling this call */
4587 if (interface_name != NULL)
4589 ExportedInterface *ei;
4590 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4593 /* we do - invoke the handler in idle in the right thread */
4595 /* handle no vtable or handler being present */
4596 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4599 handled = validate_and_maybe_schedule_method_call (connection,
4611 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4612 g_strcmp0 (member, "Introspect") == 0 &&
4613 g_strcmp0 (signature, "") == 0)
4615 handled = handle_introspect (connection, eo, message);
4618 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4619 g_strcmp0 (member, "Get") == 0 &&
4620 g_strcmp0 (signature, "ss") == 0)
4622 handled = handle_getset_property (connection, eo, message, TRUE);
4625 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4626 g_strcmp0 (member, "Set") == 0 &&
4627 g_strcmp0 (signature, "ssv") == 0)
4629 handled = handle_getset_property (connection, eo, message, FALSE);
4632 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4633 g_strcmp0 (member, "GetAll") == 0 &&
4634 g_strcmp0 (signature, "s") == 0)
4636 handled = handle_get_all_properties (connection, eo, message);
4645 * g_dbus_connection_register_object:
4646 * @connection: A #GDBusConnection.
4647 * @object_path: The object path to register at.
4648 * @interface_info: Introspection data for the interface.
4649 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4650 * @user_data: (allow-none): Data to pass to functions in @vtable.
4651 * @user_data_free_func: Function to call when the object path is unregistered.
4652 * @error: Return location for error or %NULL.
4654 * Registers callbacks for exported objects at @object_path with the
4655 * D-Bus interface that is described in @interface_info.
4657 * Calls to functions in @vtable (and @user_data_free_func) will
4658 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4659 * loop</link> of the thread you are calling this method from.
4661 * Note that all #GVariant values passed to functions in @vtable will match
4662 * the signature given in @interface_info - if a remote caller passes
4663 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4664 * is returned to the remote caller.
4666 * Additionally, if the remote caller attempts to invoke methods or
4667 * access properties not mentioned in @interface_info the
4668 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4669 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4670 * are returned to the caller.
4672 * It is considered a programming error if the
4673 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4674 * #GVariant of incorrect type.
4676 * If an existing callback is already registered at @object_path and
4677 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4679 * GDBus automatically implements the standard D-Bus interfaces
4680 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4681 * and org.freedesktop.Peer, so you don't have to implement those for
4682 * the objects you export. You <emphasis>can</emphasis> implement
4683 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4684 * and setting of properties asynchronously.
4686 * Note that the reference count on @interface_info will be
4687 * incremented by 1 (unless allocated statically, e.g. if the
4688 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4689 * as the object is exported. Also note that @vtable will be copied.
4691 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4693 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4694 * that can be used with g_dbus_connection_unregister_object() .
4699 g_dbus_connection_register_object (GDBusConnection *connection,
4700 const gchar *object_path,
4701 GDBusInterfaceInfo *interface_info,
4702 const GDBusInterfaceVTable *vtable,
4704 GDestroyNotify user_data_free_func,
4708 ExportedInterface *ei;
4711 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4712 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4713 g_return_val_if_fail (interface_info != NULL, 0);
4714 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4715 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4719 CONNECTION_LOCK (connection);
4721 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4724 eo = g_new0 (ExportedObject, 1);
4725 eo->object_path = g_strdup (object_path);
4726 eo->connection = connection;
4727 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4730 (GDestroyNotify) exported_interface_free);
4731 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4734 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4740 _("An object is already exported for the interface %s at %s"),
4741 interface_info->name,
4746 ei = g_new0 (ExportedInterface, 1);
4747 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4749 ei->user_data = user_data;
4750 ei->user_data_free_func = user_data_free_func;
4751 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4752 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4753 g_dbus_interface_info_cache_build (ei->interface_info);
4754 ei->interface_name = g_strdup (interface_info->name);
4755 ei->context = g_main_context_get_thread_default ();
4756 if (ei->context != NULL)
4757 g_main_context_ref (ei->context);
4759 g_hash_table_insert (eo->map_if_name_to_ei,
4760 (gpointer) ei->interface_name,
4762 g_hash_table_insert (connection->map_id_to_ei,
4763 GUINT_TO_POINTER (ei->id),
4769 CONNECTION_UNLOCK (connection);
4775 * g_dbus_connection_unregister_object:
4776 * @connection: A #GDBusConnection.
4777 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4779 * Unregisters an object.
4781 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4786 g_dbus_connection_unregister_object (GDBusConnection *connection,
4787 guint registration_id)
4789 ExportedInterface *ei;
4793 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4797 CONNECTION_LOCK (connection);
4799 ei = g_hash_table_lookup (connection->map_id_to_ei,
4800 GUINT_TO_POINTER (registration_id));
4806 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4807 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4808 /* unregister object path if we have no more exported interfaces */
4809 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4810 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4816 CONNECTION_UNLOCK (connection);
4821 /* ---------------------------------------------------------------------------------------------------- */
4824 * g_dbus_connection_emit_signal:
4825 * @connection: A #GDBusConnection.
4826 * @destination_bus_name: (allow-none): The unique bus name for the destination
4827 * for the signal or %NULL to emit to all listeners.
4828 * @object_path: Path of remote object.
4829 * @interface_name: D-Bus interface to emit a signal on.
4830 * @signal_name: The name of the signal to emit.
4831 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
4832 * or %NULL if not passing parameters.
4833 * @error: Return location for error or %NULL.
4837 * If the parameters GVariant is floating, it is consumed.
4839 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4841 * Returns: %TRUE unless @error is set.
4846 g_dbus_connection_emit_signal (GDBusConnection *connection,
4847 const gchar *destination_bus_name,
4848 const gchar *object_path,
4849 const gchar *interface_name,
4850 const gchar *signal_name,
4851 GVariant *parameters,
4854 GDBusMessage *message;
4860 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4861 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4862 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4863 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4864 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4865 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4867 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4869 _g_dbus_debug_print_lock ();
4870 g_print ("========================================================================\n"
4871 "GDBus-debug:Emission:\n"
4872 " >>>> SIGNAL EMISSION %s.%s()\n"
4874 " destination %s\n",
4875 interface_name, signal_name,
4877 destination_bus_name != NULL ? destination_bus_name : "(none)");
4878 _g_dbus_debug_print_unlock ();
4881 message = g_dbus_message_new_signal (object_path,
4885 if (destination_bus_name != NULL)
4886 g_dbus_message_set_header (message,
4887 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4888 g_variant_new_string (destination_bus_name));
4890 if (parameters != NULL)
4891 g_dbus_message_set_body (message, parameters);
4893 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4894 g_object_unref (message);
4900 add_call_flags (GDBusMessage *message,
4901 GDBusCallFlags flags)
4903 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4904 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4908 decode_method_reply (GDBusMessage *reply,
4909 const gchar *method_name,
4910 const GVariantType *reply_type,
4911 GUnixFDList **out_fd_list,
4917 switch (g_dbus_message_get_message_type (reply))
4919 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4920 result = g_dbus_message_get_body (reply);
4923 result = g_variant_new ("()");
4924 g_variant_ref_sink (result);
4928 g_variant_ref (result);
4931 if (!g_variant_is_of_type (result, reply_type))
4933 gchar *type_string = g_variant_type_dup_string (reply_type);
4937 G_IO_ERROR_INVALID_ARGUMENT,
4938 _("Method `%s' returned type `%s', but expected `%s'"),
4939 method_name, g_variant_get_type_string (result), type_string);
4941 g_variant_unref (result);
4942 g_free (type_string);
4949 if (out_fd_list != NULL)
4951 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
4952 if (*out_fd_list != NULL)
4953 g_object_ref (*out_fd_list);
4959 case G_DBUS_MESSAGE_TYPE_ERROR:
4960 g_dbus_message_to_gerror (reply, error);
4964 g_assert_not_reached ();
4974 GSimpleAsyncResult *simple;
4975 GVariantType *reply_type;
4976 gchar *method_name; /* for error message */
4980 GUnixFDList *fd_list;
4984 call_state_free (CallState *state)
4986 g_variant_type_free (state->reply_type);
4987 g_free (state->method_name);
4989 if (state->value != NULL)
4990 g_variant_unref (state->value);
4991 if (state->fd_list != NULL)
4992 g_object_unref (state->fd_list);
4993 g_slice_free (CallState, state);
4997 g_dbus_connection_call_done (GObject *source,
4998 GAsyncResult *result,
5001 GSimpleAsyncResult *simple;
5002 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5003 CallState *state = user_data;
5005 GDBusMessage *reply;
5008 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5012 if (G_UNLIKELY (_g_dbus_debug_call ()))
5014 _g_dbus_debug_print_lock ();
5015 g_print ("========================================================================\n"
5016 "GDBus-debug:Call:\n"
5017 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5023 g_print ("SUCCESS\n");
5027 g_print ("FAILED: %s\n",
5030 _g_dbus_debug_print_unlock ();
5034 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5036 simple = state->simple; /* why? because state is freed before we unref simple.. */
5039 g_simple_async_result_take_error (state->simple, error);
5040 g_simple_async_result_complete (state->simple);
5041 call_state_free (state);
5045 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5046 g_simple_async_result_complete (state->simple);
5047 g_object_unref (reply);
5049 g_object_unref (simple);
5053 g_dbus_connection_call_internal (GDBusConnection *connection,
5054 const gchar *bus_name,
5055 const gchar *object_path,
5056 const gchar *interface_name,
5057 const gchar *method_name,
5058 GVariant *parameters,
5059 const GVariantType *reply_type,
5060 GDBusCallFlags flags,
5062 GUnixFDList *fd_list,
5063 GCancellable *cancellable,
5064 GAsyncReadyCallback callback,
5067 GDBusMessage *message;
5070 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5071 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5072 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5073 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5074 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5075 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5076 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5078 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5080 g_return_if_fail (fd_list == NULL);
5083 state = g_slice_new0 (CallState);
5084 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5085 callback, user_data,
5086 g_dbus_connection_call_internal);
5087 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5089 if (reply_type == NULL)
5090 reply_type = G_VARIANT_TYPE_ANY;
5092 state->reply_type = g_variant_type_copy (reply_type);
5094 message = g_dbus_message_new_method_call (bus_name,
5098 add_call_flags (message, flags);
5099 if (parameters != NULL)
5100 g_dbus_message_set_body (message, parameters);
5103 if (fd_list != NULL)
5104 g_dbus_message_set_unix_fd_list (message, fd_list);
5107 g_dbus_connection_send_message_with_reply (connection,
5109 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5113 g_dbus_connection_call_done,
5116 if (G_UNLIKELY (_g_dbus_debug_call ()))
5118 _g_dbus_debug_print_lock ();
5119 g_print ("========================================================================\n"
5120 "GDBus-debug:Call:\n"
5121 " >>>> ASYNC %s.%s()\n"
5123 " owned by name %s (serial %d)\n",
5127 bus_name != NULL ? bus_name : "(none)",
5129 _g_dbus_debug_print_unlock ();
5132 if (message != NULL)
5133 g_object_unref (message);
5137 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5138 GUnixFDList **out_fd_list,
5142 GSimpleAsyncResult *simple;
5145 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5146 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5147 g_dbus_connection_call_internal), NULL);
5148 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5150 simple = G_SIMPLE_ASYNC_RESULT (res);
5152 if (g_simple_async_result_propagate_error (simple, error))
5155 state = g_simple_async_result_get_op_res_gpointer (simple);
5156 if (out_fd_list != NULL)
5157 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5158 return g_variant_ref (state->value);
5162 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5163 const gchar *bus_name,
5164 const gchar *object_path,
5165 const gchar *interface_name,
5166 const gchar *method_name,
5167 GVariant *parameters,
5168 const GVariantType *reply_type,
5169 GDBusCallFlags flags,
5171 GUnixFDList *fd_list,
5172 GUnixFDList **out_fd_list,
5173 GCancellable *cancellable,
5176 GDBusMessage *message;
5177 GDBusMessage *reply;
5179 GError *local_error;
5185 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5186 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5187 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5188 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5189 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5190 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5191 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5193 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5195 g_return_val_if_fail (fd_list == NULL, NULL);
5197 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5199 if (reply_type == NULL)
5200 reply_type = G_VARIANT_TYPE_ANY;
5202 message = g_dbus_message_new_method_call (bus_name,
5206 add_call_flags (message, flags);
5207 if (parameters != NULL)
5208 g_dbus_message_set_body (message, parameters);
5211 if (fd_list != NULL)
5212 g_dbus_message_set_unix_fd_list (message, fd_list);
5215 if (G_UNLIKELY (_g_dbus_debug_call ()))
5217 _g_dbus_debug_print_lock ();
5218 g_print ("========================================================================\n"
5219 "GDBus-debug:Call:\n"
5220 " >>>> SYNC %s.%s()\n"
5222 " owned by name %s\n",
5226 bus_name != NULL ? bus_name : "(none)");
5227 _g_dbus_debug_print_unlock ();
5231 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5233 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5235 NULL, /* volatile guint32 *out_serial */
5239 if (G_UNLIKELY (_g_dbus_debug_call ()))
5241 _g_dbus_debug_print_lock ();
5242 g_print ("========================================================================\n"
5243 "GDBus-debug:Call:\n"
5244 " <<<< SYNC COMPLETE %s.%s()\n"
5250 g_print ("SUCCESS\n");
5254 g_print ("FAILED: %s\n",
5255 local_error->message);
5257 _g_dbus_debug_print_unlock ();
5263 *error = local_error;
5265 g_error_free (local_error);
5269 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5272 if (message != NULL)
5273 g_object_unref (message);
5275 g_object_unref (reply);
5280 /* ---------------------------------------------------------------------------------------------------- */
5283 * g_dbus_connection_call:
5284 * @connection: A #GDBusConnection.
5285 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5286 * @connection is not a message bus connection.
5287 * @object_path: Path of remote object.
5288 * @interface_name: D-Bus interface to invoke method on.
5289 * @method_name: The name of the method to invoke.
5290 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5291 * or %NULL if not passing parameters.
5292 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5293 * @flags: Flags from the #GDBusCallFlags enumeration.
5294 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5295 * timeout or %G_MAXINT for no timeout.
5296 * @cancellable: A #GCancellable or %NULL.
5297 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5298 * satisfied or %NULL if you don't * care about the result of the
5299 * method invocation.
5300 * @user_data: The data to pass to @callback.
5302 * Asynchronously invokes the @method_name method on the
5303 * @interface_name D-Bus interface on the remote object at
5304 * @object_path owned by @bus_name.
5306 * If @connection is closed then the operation will fail with
5307 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5308 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5309 * not compatible with the D-Bus protocol, the operation fails with
5310 * %G_IO_ERROR_INVALID_ARGUMENT.
5312 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5313 * error will be raised if it does not match. Said another way, if you give a @reply_type
5314 * then any non-%NULL return value will be of this type.
5316 * If the @parameters #GVariant is floating, it is consumed. This allows
5317 * convenient 'inline' use of g_variant_new(), e.g.:
5319 * g_dbus_connection_call (connection,
5320 * "org.freedesktop.StringThings",
5321 * "/org/freedesktop/StringThings",
5322 * "org.freedesktop.StringThings",
5324 * g_variant_new ("(ss)",
5328 * G_DBUS_CALL_FLAGS_NONE,
5331 * (GAsyncReadyCallback) two_strings_done,
5335 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5336 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5337 * of the thread you are calling this method from. You can then call
5338 * g_dbus_connection_call_finish() to get the result of the operation.
5339 * See g_dbus_connection_call_sync() for the synchronous version of this
5345 g_dbus_connection_call (GDBusConnection *connection,
5346 const gchar *bus_name,
5347 const gchar *object_path,
5348 const gchar *interface_name,
5349 const gchar *method_name,
5350 GVariant *parameters,
5351 const GVariantType *reply_type,
5352 GDBusCallFlags flags,
5354 GCancellable *cancellable,
5355 GAsyncReadyCallback callback,
5358 g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, cancellable, callback, user_data);
5362 * g_dbus_connection_call_finish:
5363 * @connection: A #GDBusConnection.
5364 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5365 * @error: Return location for error or %NULL.
5367 * Finishes an operation started with g_dbus_connection_call().
5369 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5370 * return values. Free with g_variant_unref().
5375 g_dbus_connection_call_finish (GDBusConnection *connection,
5379 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5383 * g_dbus_connection_call_sync:
5384 * @connection: A #GDBusConnection.
5385 * @bus_name: A unique or well-known bus name.
5386 * @object_path: Path of remote object.
5387 * @interface_name: D-Bus interface to invoke method on.
5388 * @method_name: The name of the method to invoke.
5389 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5390 * or %NULL if not passing parameters.
5391 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5392 * @flags: Flags from the #GDBusCallFlags enumeration.
5393 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5394 * timeout or %G_MAXINT for no timeout.
5395 * @cancellable: A #GCancellable or %NULL.
5396 * @error: Return location for error or %NULL.
5398 * Synchronously invokes the @method_name method on the
5399 * @interface_name D-Bus interface on the remote object at
5400 * @object_path owned by @bus_name.
5402 * If @connection is closed then the operation will fail with
5403 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5404 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5405 * contains a value not compatible with the D-Bus protocol, the operation
5406 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5408 * If @reply_type is non-%NULL then the reply will be checked for having
5409 * this type and an error will be raised if it does not match. Said
5410 * another way, if you give a @reply_type then any non-%NULL return
5411 * value will be of this type.
5413 * If the @parameters #GVariant is floating, it is consumed.
5414 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5416 * g_dbus_connection_call_sync (connection,
5417 * "org.freedesktop.StringThings",
5418 * "/org/freedesktop/StringThings",
5419 * "org.freedesktop.StringThings",
5421 * g_variant_new ("(ss)",
5425 * G_DBUS_CALL_FLAGS_NONE,
5431 * The calling thread is blocked until a reply is received. See
5432 * g_dbus_connection_call() for the asynchronous version of
5435 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5436 * return values. Free with g_variant_unref().
5441 g_dbus_connection_call_sync (GDBusConnection *connection,
5442 const gchar *bus_name,
5443 const gchar *object_path,
5444 const gchar *interface_name,
5445 const gchar *method_name,
5446 GVariant *parameters,
5447 const GVariantType *reply_type,
5448 GDBusCallFlags flags,
5450 GCancellable *cancellable,
5453 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, NULL, cancellable, error);
5456 /* ---------------------------------------------------------------------------------------------------- */
5461 * g_dbus_connection_call_with_unix_fd_list:
5462 * @connection: A #GDBusConnection.
5463 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5464 * @connection is not a message bus connection.
5465 * @object_path: Path of remote object.
5466 * @interface_name: D-Bus interface to invoke method on.
5467 * @method_name: The name of the method to invoke.
5468 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5469 * or %NULL if not passing parameters.
5470 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5471 * @flags: Flags from the #GDBusCallFlags enumeration.
5472 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5473 * timeout or %G_MAXINT for no timeout.
5474 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5475 * @cancellable: A #GCancellable or %NULL.
5476 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5477 * satisfied or %NULL if you don't * care about the result of the
5478 * method invocation.
5479 * @user_data: The data to pass to @callback.
5481 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5483 * This method is only available on UNIX.
5488 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5489 const gchar *bus_name,
5490 const gchar *object_path,
5491 const gchar *interface_name,
5492 const gchar *method_name,
5493 GVariant *parameters,
5494 const GVariantType *reply_type,
5495 GDBusCallFlags flags,
5497 GUnixFDList *fd_list,
5498 GCancellable *cancellable,
5499 GAsyncReadyCallback callback,
5502 g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, cancellable, callback, user_data);
5506 * g_dbus_connection_call_with_unix_fd_list_finish:
5507 * @connection: A #GDBusConnection.
5508 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5509 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5510 * @error: Return location for error or %NULL.
5512 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5514 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5515 * return values. Free with g_variant_unref().
5520 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5521 GUnixFDList **out_fd_list,
5525 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5529 * g_dbus_connection_call_with_unix_fd_list_sync:
5530 * @connection: A #GDBusConnection.
5531 * @bus_name: A unique or well-known bus name.
5532 * @object_path: Path of remote object.
5533 * @interface_name: D-Bus interface to invoke method on.
5534 * @method_name: The name of the method to invoke.
5535 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5536 * or %NULL if not passing parameters.
5537 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5538 * @flags: Flags from the #GDBusCallFlags enumeration.
5539 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5540 * timeout or %G_MAXINT for no timeout.
5541 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5542 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5543 * @cancellable: A #GCancellable or %NULL.
5544 * @error: Return location for error or %NULL.
5546 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5548 * This method is only available on UNIX.
5550 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5551 * return values. Free with g_variant_unref().
5556 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5557 const gchar *bus_name,
5558 const gchar *object_path,
5559 const gchar *interface_name,
5560 const gchar *method_name,
5561 GVariant *parameters,
5562 const GVariantType *reply_type,
5563 GDBusCallFlags flags,
5565 GUnixFDList *fd_list,
5566 GUnixFDList **out_fd_list,
5567 GCancellable *cancellable,
5570 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, out_fd_list, cancellable, error);
5573 #endif /* G_OS_UNIX */
5575 /* ---------------------------------------------------------------------------------------------------- */
5577 struct ExportedSubtree
5581 GDBusConnection *connection;
5582 GDBusSubtreeVTable *vtable;
5583 GDBusSubtreeFlags flags;
5585 GMainContext *context;
5587 GDestroyNotify user_data_free_func;
5591 exported_subtree_free (ExportedSubtree *es)
5593 call_destroy_notify (es->context,
5594 es->user_data_free_func,
5597 if (es->context != NULL)
5598 g_main_context_unref (es->context);
5600 _g_dbus_subtree_vtable_free (es->vtable);
5601 g_free (es->object_path);
5605 /* called without lock held */
5607 handle_subtree_introspect (GDBusConnection *connection,
5608 ExportedSubtree *es,
5609 GDBusMessage *message)
5613 GDBusMessage *reply;
5616 const gchar *sender;
5617 const gchar *requested_object_path;
5618 const gchar *requested_node;
5619 GDBusInterfaceInfo **interfaces;
5621 gchar **subnode_paths;
5622 gboolean has_properties_interface;
5623 gboolean has_introspectable_interface;
5627 requested_object_path = g_dbus_message_get_path (message);
5628 sender = g_dbus_message_get_sender (message);
5629 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5631 s = g_string_new (NULL);
5632 introspect_append_header (s);
5634 /* Strictly we don't need the children in dynamic mode, but we avoid the
5635 * conditionals to preserve code clarity
5637 children = es->vtable->enumerate (es->connection,
5644 requested_node = strrchr (requested_object_path, '/') + 1;
5646 /* Assert existence of object if we are not dynamic */
5647 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5648 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5653 requested_node = NULL;
5656 interfaces = es->vtable->introspect (es->connection,
5661 if (interfaces != NULL)
5663 has_properties_interface = FALSE;
5664 has_introspectable_interface = FALSE;
5666 for (n = 0; interfaces[n] != NULL; n++)
5668 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5669 has_properties_interface = TRUE;
5670 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5671 has_introspectable_interface = TRUE;
5673 if (!has_properties_interface)
5674 g_string_append (s, introspect_properties_interface);
5675 if (!has_introspectable_interface)
5676 g_string_append (s, introspect_introspectable_interface);
5678 for (n = 0; interfaces[n] != NULL; n++)
5680 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5681 g_dbus_interface_info_unref (interfaces[n]);
5683 g_free (interfaces);
5686 /* then include <node> entries from the Subtree for the root */
5689 for (n = 0; children != NULL && children[n] != NULL; n++)
5690 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5693 /* finally include nodes registered below us */
5694 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5695 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5696 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5697 g_strfreev (subnode_paths);
5699 g_string_append (s, "</node>\n");
5701 reply = g_dbus_message_new_method_reply (message);
5702 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5703 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5704 g_object_unref (reply);
5709 g_string_free (s, TRUE);
5710 g_strfreev (children);
5714 /* called without lock held */
5716 handle_subtree_method_invocation (GDBusConnection *connection,
5717 ExportedSubtree *es,
5718 GDBusMessage *message)
5721 const gchar *sender;
5722 const gchar *interface_name;
5723 const gchar *member;
5724 const gchar *signature;
5725 const gchar *requested_object_path;
5726 const gchar *requested_node;
5728 GDBusInterfaceInfo *interface_info;
5729 const GDBusInterfaceVTable *interface_vtable;
5730 gpointer interface_user_data;
5732 GDBusInterfaceInfo **interfaces;
5733 gboolean is_property_get;
5734 gboolean is_property_set;
5735 gboolean is_property_get_all;
5740 requested_object_path = g_dbus_message_get_path (message);
5741 sender = g_dbus_message_get_sender (message);
5742 interface_name = g_dbus_message_get_interface (message);
5743 member = g_dbus_message_get_member (message);
5744 signature = g_dbus_message_get_signature (message);
5745 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5747 is_property_get = FALSE;
5748 is_property_set = FALSE;
5749 is_property_get_all = FALSE;
5750 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5752 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5753 is_property_get = TRUE;
5754 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5755 is_property_set = TRUE;
5756 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5757 is_property_get_all = TRUE;
5762 requested_node = strrchr (requested_object_path, '/') + 1;
5764 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5766 /* We don't want to dispatch to unenumerated
5767 * nodes, so ensure that the child exists.
5772 children = es->vtable->enumerate (es->connection,
5777 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5778 g_strfreev (children);
5786 requested_node = NULL;
5789 /* get introspection data for the node */
5790 interfaces = es->vtable->introspect (es->connection,
5792 requested_object_path,
5796 if (interfaces == NULL)
5799 interface_info = NULL;
5800 for (n = 0; interfaces[n] != NULL; n++)
5802 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5803 interface_info = interfaces[n];
5806 /* dispatch the call if the user wants to handle it */
5807 if (interface_info != NULL)
5809 /* figure out where to dispatch the method call */
5810 interface_user_data = NULL;
5811 interface_vtable = es->vtable->dispatch (es->connection,
5816 &interface_user_data,
5818 if (interface_vtable == NULL)
5821 CONNECTION_LOCK (connection);
5822 handled = validate_and_maybe_schedule_method_call (es->connection,
5829 interface_user_data);
5830 CONNECTION_UNLOCK (connection);
5832 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5833 else if (is_property_get || is_property_set || is_property_get_all)
5835 if (is_property_get)
5836 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5837 else if (is_property_set)
5838 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5839 else if (is_property_get_all)
5840 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5842 g_assert_not_reached ();
5844 /* see if the object supports this interface at all */
5845 for (n = 0; interfaces[n] != NULL; n++)
5847 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5848 interface_info = interfaces[n];
5851 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5852 * claims it won't support the interface
5854 if (interface_info == NULL)
5856 GDBusMessage *reply;
5857 reply = g_dbus_message_new_method_error (message,
5858 "org.freedesktop.DBus.Error.InvalidArgs",
5859 _("No such interface `%s'"),
5861 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5862 g_object_unref (reply);
5867 /* figure out where to dispatch the property get/set/getall calls */
5868 interface_user_data = NULL;
5869 interface_vtable = es->vtable->dispatch (es->connection,
5874 &interface_user_data,
5876 if (interface_vtable == NULL)
5878 g_warning ("The subtree introspection function indicates that '%s' "
5879 "is a valid interface name, but calling the dispatch "
5880 "function on that interface gave us NULL", interface_name);
5884 if (is_property_get || is_property_set)
5886 CONNECTION_LOCK (connection);
5887 handled = validate_and_maybe_schedule_property_getset (es->connection,
5895 interface_user_data);
5896 CONNECTION_UNLOCK (connection);
5898 else if (is_property_get_all)
5900 CONNECTION_LOCK (connection);
5901 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5908 interface_user_data);
5909 CONNECTION_UNLOCK (connection);
5914 if (interfaces != NULL)
5916 for (n = 0; interfaces[n] != NULL; n++)
5917 g_dbus_interface_info_unref (interfaces[n]);
5918 g_free (interfaces);
5926 GDBusMessage *message;
5927 ExportedSubtree *es;
5928 } SubtreeDeferredData;
5931 subtree_deferred_data_free (SubtreeDeferredData *data)
5933 g_object_unref (data->message);
5937 /* called without lock held in the thread where the caller registered the subtree */
5939 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5941 SubtreeDeferredData *data = _data;
5946 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5947 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5948 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5949 handled = handle_subtree_introspect (data->es->connection,
5953 handled = handle_subtree_method_invocation (data->es->connection,
5959 CONNECTION_LOCK (data->es->connection);
5960 handled = handle_generic_unlocked (data->es->connection, data->message);
5961 CONNECTION_UNLOCK (data->es->connection);
5964 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5967 GDBusMessage *reply;
5968 reply = g_dbus_message_new_method_error (data->message,
5969 "org.freedesktop.DBus.Error.UnknownMethod",
5970 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5971 g_dbus_message_get_member (data->message),
5972 g_dbus_message_get_interface (data->message),
5973 g_dbus_message_get_signature (data->message));
5974 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5975 g_object_unref (reply);
5981 /* called in message handler thread with lock held */
5983 subtree_message_func (GDBusConnection *connection,
5984 ExportedSubtree *es,
5985 GDBusMessage *message)
5987 GSource *idle_source;
5988 SubtreeDeferredData *data;
5990 data = g_new0 (SubtreeDeferredData, 1);
5991 data->message = g_object_ref (message);
5994 /* defer this call to an idle handler in the right thread */
5995 idle_source = g_idle_source_new ();
5996 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5997 g_source_set_callback (idle_source,
5998 process_subtree_vtable_message_in_idle_cb,
6000 (GDestroyNotify) subtree_deferred_data_free);
6001 g_source_attach (idle_source, es->context);
6002 g_source_unref (idle_source);
6004 /* since we own the entire subtree, handlers for objects not in the subtree have been
6005 * tried already by libdbus-1 - so we just need to ensure that we're always going
6006 * to reply to the message
6012 * g_dbus_connection_register_subtree:
6013 * @connection: A #GDBusConnection.
6014 * @object_path: The object path to register the subtree at.
6015 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6016 * @flags: Flags used to fine tune the behavior of the subtree.
6017 * @user_data: Data to pass to functions in @vtable.
6018 * @user_data_free_func: Function to call when the subtree is unregistered.
6019 * @error: Return location for error or %NULL.
6021 * Registers a whole subtree of <quote>dynamic</quote> objects.
6023 * The @enumerate and @introspection functions in @vtable are used to
6024 * convey, to remote callers, what nodes exist in the subtree rooted
6027 * When handling remote calls into any node in the subtree, first the
6028 * @enumerate function is used to check if the node exists. If the node exists
6029 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6030 * the @introspection function is used to check if the node supports the
6031 * requested method. If so, the @dispatch function is used to determine
6032 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6033 * #gpointer will be used to call into the interface vtable for processing
6036 * All calls into user-provided code will be invoked in the <link
6037 * linkend="g-main-context-push-thread-default">thread-default main
6038 * loop</link> of the thread you are calling this method from.
6040 * If an existing subtree is already registered at @object_path or
6041 * then @error is set to #G_IO_ERROR_EXISTS.
6043 * Note that it is valid to register regular objects (using
6044 * g_dbus_connection_register_object()) in a subtree registered with
6045 * g_dbus_connection_register_subtree() - if so, the subtree handler
6046 * is tried as the last resort. One way to think about a subtree
6047 * handler is to consider it a <quote>fallback handler</quote>
6048 * for object paths not registered via g_dbus_connection_register_object()
6049 * or other bindings.
6051 * Note that @vtable will be copied so you cannot change it after
6054 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6056 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6057 * that can be used with g_dbus_connection_unregister_subtree() .
6062 g_dbus_connection_register_subtree (GDBusConnection *connection,
6063 const gchar *object_path,
6064 const GDBusSubtreeVTable *vtable,
6065 GDBusSubtreeFlags flags,
6067 GDestroyNotify user_data_free_func,
6071 ExportedSubtree *es;
6073 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6074 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6075 g_return_val_if_fail (vtable != NULL, 0);
6076 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6080 CONNECTION_LOCK (connection);
6082 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6088 _("A subtree is already exported for %s"),
6093 es = g_new0 (ExportedSubtree, 1);
6094 es->object_path = g_strdup (object_path);
6095 es->connection = connection;
6097 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6099 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6100 es->user_data = user_data;
6101 es->user_data_free_func = user_data_free_func;
6102 es->context = g_main_context_get_thread_default ();
6103 if (es->context != NULL)
6104 g_main_context_ref (es->context);
6106 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6107 g_hash_table_insert (connection->map_id_to_es,
6108 GUINT_TO_POINTER (es->id),
6114 CONNECTION_UNLOCK (connection);
6119 /* ---------------------------------------------------------------------------------------------------- */
6122 * g_dbus_connection_unregister_subtree:
6123 * @connection: A #GDBusConnection.
6124 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6126 * Unregisters a subtree.
6128 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6133 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6134 guint registration_id)
6136 ExportedSubtree *es;
6139 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6143 CONNECTION_LOCK (connection);
6145 es = g_hash_table_lookup (connection->map_id_to_es,
6146 GUINT_TO_POINTER (registration_id));
6150 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6151 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6156 CONNECTION_UNLOCK (connection);
6161 /* ---------------------------------------------------------------------------------------------------- */
6163 /* must be called with lock held */
6165 handle_generic_ping_unlocked (GDBusConnection *connection,
6166 const gchar *object_path,
6167 GDBusMessage *message)
6169 GDBusMessage *reply;
6170 reply = g_dbus_message_new_method_reply (message);
6171 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6172 g_object_unref (reply);
6175 /* must be called with lock held */
6177 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6178 const gchar *object_path,
6179 GDBusMessage *message)
6181 GDBusMessage *reply;
6184 if (connection->machine_id == NULL)
6189 connection->machine_id = _g_dbus_get_machine_id (&error);
6190 if (connection->machine_id == NULL)
6192 reply = g_dbus_message_new_method_error_literal (message,
6193 "org.freedesktop.DBus.Error.Failed",
6195 g_error_free (error);
6201 reply = g_dbus_message_new_method_reply (message);
6202 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6204 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6205 g_object_unref (reply);
6208 /* must be called with lock held */
6210 handle_generic_introspect_unlocked (GDBusConnection *connection,
6211 const gchar *object_path,
6212 GDBusMessage *message)
6217 GDBusMessage *reply;
6219 /* first the header */
6220 s = g_string_new (NULL);
6221 introspect_append_header (s);
6223 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6224 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6225 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6226 g_strfreev (registered);
6227 g_string_append (s, "</node>\n");
6229 reply = g_dbus_message_new_method_reply (message);
6230 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6231 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6232 g_object_unref (reply);
6233 g_string_free (s, TRUE);
6236 /* must be called with lock held */
6238 handle_generic_unlocked (GDBusConnection *connection,
6239 GDBusMessage *message)
6242 const gchar *interface_name;
6243 const gchar *member;
6244 const gchar *signature;
6247 CONNECTION_ENSURE_LOCK (connection);
6251 interface_name = g_dbus_message_get_interface (message);
6252 member = g_dbus_message_get_member (message);
6253 signature = g_dbus_message_get_signature (message);
6254 path = g_dbus_message_get_path (message);
6256 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6257 g_strcmp0 (member, "Introspect") == 0 &&
6258 g_strcmp0 (signature, "") == 0)
6260 handle_generic_introspect_unlocked (connection, path, message);
6263 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6264 g_strcmp0 (member, "Ping") == 0 &&
6265 g_strcmp0 (signature, "") == 0)
6267 handle_generic_ping_unlocked (connection, path, message);
6270 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6271 g_strcmp0 (member, "GetMachineId") == 0 &&
6272 g_strcmp0 (signature, "") == 0)
6274 handle_generic_get_machine_id_unlocked (connection, path, message);
6281 /* ---------------------------------------------------------------------------------------------------- */
6283 /* called in message handler thread with lock held */
6285 distribute_method_call (GDBusConnection *connection,
6286 GDBusMessage *message)
6288 GDBusMessage *reply;
6290 ExportedSubtree *es;
6291 const gchar *object_path;
6292 const gchar *interface_name;
6293 const gchar *member;
6295 gchar *subtree_path;
6298 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6300 interface_name = g_dbus_message_get_interface (message);
6301 member = g_dbus_message_get_member (message);
6302 path = g_dbus_message_get_path (message);
6303 subtree_path = g_strdup (path);
6304 needle = strrchr (subtree_path, '/');
6305 if (needle != NULL && needle != subtree_path)
6311 g_free (subtree_path);
6312 subtree_path = NULL;
6316 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6318 _g_dbus_debug_print_lock ();
6319 g_print ("========================================================================\n"
6320 "GDBus-debug:Incoming:\n"
6321 " <<<< METHOD INVOCATION %s.%s()\n"
6323 " invoked by name %s\n"
6325 interface_name, member,
6327 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6328 g_dbus_message_get_serial (message));
6329 _g_dbus_debug_print_unlock ();
6332 object_path = g_dbus_message_get_path (message);
6333 g_assert (object_path != NULL);
6335 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6338 if (obj_message_func (connection, eo, message))
6342 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6345 if (subtree_message_func (connection, es, message))
6349 if (subtree_path != NULL)
6351 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6354 if (subtree_message_func (connection, es, message))
6359 if (handle_generic_unlocked (connection, message))
6362 /* if we end up here, the message has not been not handled - so return an error saying this */
6363 reply = g_dbus_message_new_method_error (message,
6364 "org.freedesktop.DBus.Error.UnknownMethod",
6365 _("No such interface `%s' on object at path %s"),
6368 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6369 g_object_unref (reply);
6372 g_free (subtree_path);
6375 /* ---------------------------------------------------------------------------------------------------- */
6377 static GDBusConnection **
6378 message_bus_get_singleton (GBusType bus_type,
6381 GDBusConnection **ret;
6382 const gchar *starter_bus;
6388 case G_BUS_TYPE_SESSION:
6389 ret = &the_session_bus;
6392 case G_BUS_TYPE_SYSTEM:
6393 ret = &the_system_bus;
6396 case G_BUS_TYPE_STARTER:
6397 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6398 if (g_strcmp0 (starter_bus, "session") == 0)
6400 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6403 else if (g_strcmp0 (starter_bus, "system") == 0)
6405 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6410 if (starter_bus != NULL)
6414 G_IO_ERROR_INVALID_ARGUMENT,
6415 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6416 " - unknown value `%s'"),
6421 g_set_error_literal (error,
6423 G_IO_ERROR_INVALID_ARGUMENT,
6424 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6425 "variable is not set"));
6431 g_assert_not_reached ();
6439 static GDBusConnection *
6440 get_uninitialized_connection (GBusType bus_type,
6441 GCancellable *cancellable,
6444 GDBusConnection **singleton;
6445 GDBusConnection *ret;
6449 G_LOCK (message_bus_lock);
6450 singleton = message_bus_get_singleton (bus_type, error);
6451 if (singleton == NULL)
6454 if (*singleton == NULL)
6457 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6458 if (address == NULL)
6460 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6462 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6463 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6464 "exit-on-close", TRUE,
6470 ret = g_object_ref (*singleton);
6473 g_assert (ret != NULL);
6476 G_UNLOCK (message_bus_lock);
6482 * @bus_type: A #GBusType.
6483 * @cancellable: A #GCancellable or %NULL.
6484 * @error: Return location for error or %NULL.
6486 * Synchronously connects to the message bus specified by @bus_type.
6487 * Note that the returned object may shared with other callers,
6488 * e.g. if two separate parts of a process calls this function with
6489 * the same @bus_type, they will share the same object.
6491 * This is a synchronous failable function. See g_bus_get() and
6492 * g_bus_get_finish() for the asynchronous version.
6494 * The returned object is a singleton, that is, shared with other
6495 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6496 * event that you need a private message bus connection, use
6497 * g_dbus_address_get_for_bus_sync() and
6498 * g_dbus_connection_new_for_address().
6500 * Note that the returned #GDBusConnection object will (usually) have
6501 * the #GDBusConnection:exit-on-close property set to %TRUE.
6503 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6508 g_bus_get_sync (GBusType bus_type,
6509 GCancellable *cancellable,
6512 GDBusConnection *connection;
6514 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6516 connection = get_uninitialized_connection (bus_type, cancellable, error);
6517 if (connection == NULL)
6520 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6522 g_object_unref (connection);
6531 bus_get_async_initable_cb (GObject *source_object,
6535 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6539 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6543 g_assert (error != NULL);
6544 g_simple_async_result_take_error (simple, error);
6545 g_object_unref (source_object);
6549 g_simple_async_result_set_op_res_gpointer (simple,
6553 g_simple_async_result_complete_in_idle (simple);
6554 g_object_unref (simple);
6559 * @bus_type: A #GBusType.
6560 * @cancellable: A #GCancellable or %NULL.
6561 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6562 * @user_data: The data to pass to @callback.
6564 * Asynchronously connects to the message bus specified by @bus_type.
6566 * When the operation is finished, @callback will be invoked. You can
6567 * then call g_bus_get_finish() to get the result of the operation.
6569 * This is a asynchronous failable function. See g_bus_get_sync() for
6570 * the synchronous version.
6575 g_bus_get (GBusType bus_type,
6576 GCancellable *cancellable,
6577 GAsyncReadyCallback callback,
6580 GDBusConnection *connection;
6581 GSimpleAsyncResult *simple;
6584 simple = g_simple_async_result_new (NULL,
6590 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6591 if (connection == NULL)
6593 g_assert (error != NULL);
6594 g_simple_async_result_take_error (simple, error);
6595 g_simple_async_result_complete_in_idle (simple);
6596 g_object_unref (simple);
6600 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6603 bus_get_async_initable_cb,
6610 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6611 * @error: Return location for error or %NULL.
6613 * Finishes an operation started with g_bus_get().
6615 * The returned object is a singleton, that is, shared with other
6616 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6617 * event that you need a private message bus connection, use
6618 * g_dbus_address_get_for_bus_sync() and
6619 * g_dbus_connection_new_for_address().
6621 * Note that the returned #GDBusConnection object will (usually) have
6622 * the #GDBusConnection:exit-on-close property set to %TRUE.
6624 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6629 g_bus_get_finish (GAsyncResult *res,
6632 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6634 GDBusConnection *ret;
6636 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6638 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6642 if (g_simple_async_result_propagate_error (simple, error))
6645 object = g_simple_async_result_get_op_res_gpointer (simple);
6646 g_assert (object != NULL);
6647 ret = g_object_ref (G_DBUS_CONNECTION (object));
6653 /* ---------------------------------------------------------------------------------------------------- */