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 (excect
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 acheive 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 "gio-marshal.h"
125 #include "ginitable.h"
126 #include "gasyncinitable.h"
127 #include "giostream.h"
128 #include "gasyncresult.h"
129 #include "gsimpleasyncresult.h"
132 #include "gunixconnection.h"
133 #include "gunixfdmessage.h"
136 #include "glibintl.h"
139 * SECTION:gdbusconnection
140 * @short_description: D-Bus Connections
141 * @include: gio/gio.h
143 * The #GDBusConnection type is used for D-Bus connections to remote
144 * peers such as a message buses. It is a low-level API that offers a
145 * lot of flexibility. For instance, it lets you establish a connection
146 * over any transport that can by represented as an #GIOStream.
148 * This class is rarely used directly in D-Bus clients. If you are writing
149 * an D-Bus client, it is often easier to use the g_bus_own_name(),
150 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
152 * <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>
154 * <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>
156 * <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>
158 * <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>
161 /* ---------------------------------------------------------------------------------------------------- */
163 typedef struct _GDBusConnectionClass GDBusConnectionClass;
166 * GDBusConnectionClass:
167 * @closed: Signal class handler for the #GDBusConnection::closed signal.
169 * Class structure for #GDBusConnection.
173 struct _GDBusConnectionClass
176 GObjectClass parent_class;
180 void (*closed) (GDBusConnection *connection,
181 gboolean remote_peer_vanished,
185 G_LOCK_DEFINE_STATIC (message_bus_lock);
187 static GDBusConnection *the_session_bus = NULL;
188 static GDBusConnection *the_system_bus = NULL;
190 /* ---------------------------------------------------------------------------------------------------- */
194 GDestroyNotify callback;
196 GMainContext *context;
197 } CallDestroyNotifyData;
200 call_destroy_notify_data_in_idle (gpointer user_data)
202 CallDestroyNotifyData *data = user_data;
203 data->callback (data->user_data);
208 call_destroy_notify_data_free (CallDestroyNotifyData *data)
210 if (data->context != NULL)
211 g_main_context_unref (data->context);
216 * call_destroy_notify: <internal>
217 * @context: A #GMainContext or %NULL.
218 * @callback: A #GDestroyNotify or %NULL.
219 * @user_data: Data to pass to @callback.
221 * Schedules @callback to run in @context.
224 call_destroy_notify (GMainContext *context,
225 GDestroyNotify callback,
228 if (callback == NULL)
231 if (context == g_main_context_get_thread_default ())
233 callback (user_data);
237 GSource *idle_source;
238 CallDestroyNotifyData *data;
240 data = g_new0 (CallDestroyNotifyData, 1);
241 data->callback = callback;
242 data->user_data = user_data;
243 data->context = context;
244 if (data->context != NULL)
245 g_main_context_ref (data->context);
247 idle_source = g_idle_source_new ();
248 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
249 g_source_set_callback (idle_source,
250 call_destroy_notify_data_in_idle,
252 (GDestroyNotify) call_destroy_notify_data_free);
253 g_source_attach (idle_source, data->context);
254 g_source_unref (idle_source);
261 /* ---------------------------------------------------------------------------------------------------- */
264 _g_strv_has_string (const gchar* const *haystack,
269 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
271 if (g_strcmp0 (haystack[n], needle) == 0)
277 /* ---------------------------------------------------------------------------------------------------- */
280 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
282 // TODO: for some reason this doesn't work on Windows
283 #define CONNECTION_ENSURE_LOCK(obj) do { \
284 if (G_UNLIKELY (g_mutex_trylock((obj)->lock))) \
286 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
287 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
292 #define CONNECTION_LOCK(obj) do { \
293 g_mutex_lock ((obj)->lock); \
296 #define CONNECTION_UNLOCK(obj) do { \
297 g_mutex_unlock ((obj)->lock); \
303 * The #GDBusConnection structure contains only private data and
304 * should only be accessed using the provided API.
308 struct _GDBusConnection
311 GObject parent_instance;
313 /* ------------------------------------------------------------------------ */
314 /* -- General object state ------------------------------------------------ */
315 /* ------------------------------------------------------------------------ */
317 /* object-wide lock */
320 /* A lock used in the init() method of the GInitable interface - see comments
321 * in initable_init() for why a separate lock is needed
325 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
326 * someone calls org.freedesktop.DBus.GetMachineId()
330 /* The underlying stream used for communication */
333 /* The object used for authentication (if any) */
336 /* Set to TRUE if the connection has been closed */
339 /* Last serial used */
342 /* The object used to send/receive message */
345 /* If connected to a message bus, this contains the unique name assigned to
346 * us by the bus (e.g. ":1.42")
348 gchar *bus_unique_name;
350 /* The GUID returned by the other side if we authenticed as a client or
351 * the GUID to use if authenticating as a server
355 /* set to TRUE exactly when initable_init() has finished running */
356 gboolean is_initialized;
358 /* If the connection could not be established during initable_init(), this GError will set */
359 GError *initialization_error;
361 /* The result of g_main_context_get_thread_default() when the object
362 * was created (the GObject _init() function) - this is used for delivery
363 * of the :closed GObject signal.
365 GMainContext *main_context_at_construction;
367 /* construct properties */
369 GDBusConnectionFlags flags;
371 /* Map used for managing method replies */
372 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
374 /* Maps used for managing signal subscription */
375 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
376 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
377 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
379 /* Maps used for managing exported objects and subtrees */
380 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
381 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
382 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
383 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
385 /* Structure used for message filters */
388 /* Whether to exit on close */
389 gboolean exit_on_close;
391 /* Capabilities negotiated during authentication */
392 GDBusCapabilityFlags capabilities;
394 GDBusAuthObserver *authentication_observer;
395 GCredentials *credentials;
397 /* set to TRUE when finalizing */
401 typedef struct ExportedObject ExportedObject;
402 static void exported_object_free (ExportedObject *eo);
404 typedef struct ExportedSubtree ExportedSubtree;
405 static void exported_subtree_free (ExportedSubtree *es);
423 PROP_CAPABILITY_FLAGS,
424 PROP_AUTHENTICATION_OBSERVER,
427 static void distribute_signals (GDBusConnection *connection,
428 GDBusMessage *message);
430 static void distribute_method_call (GDBusConnection *connection,
431 GDBusMessage *message);
433 static gboolean handle_generic_unlocked (GDBusConnection *connection,
434 GDBusMessage *message);
437 static void purge_all_signal_subscriptions (GDBusConnection *connection);
438 static void purge_all_filters (GDBusConnection *connection);
440 #define _G_ENSURE_LOCK(name) do { \
441 if (G_UNLIKELY (G_TRYLOCK(name))) \
443 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
444 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
448 static guint signals[LAST_SIGNAL] = { 0 };
450 static void initable_iface_init (GInitableIface *initable_iface);
451 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
453 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
454 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
455 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
458 static GHashTable *alive_connections = NULL;
461 g_dbus_connection_dispose (GObject *object)
463 GDBusConnection *connection = G_DBUS_CONNECTION (object);
465 G_LOCK (message_bus_lock);
466 if (connection == the_session_bus)
468 the_session_bus = NULL;
470 else if (connection == the_system_bus)
472 the_system_bus = NULL;
474 CONNECTION_LOCK (connection);
475 if (connection->worker != NULL)
477 _g_dbus_worker_stop (connection->worker);
478 connection->worker = NULL;
479 if (alive_connections != NULL)
480 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
484 if (alive_connections != NULL)
485 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
487 CONNECTION_UNLOCK (connection);
488 G_UNLOCK (message_bus_lock);
490 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
491 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
495 g_dbus_connection_finalize (GObject *object)
497 GDBusConnection *connection = G_DBUS_CONNECTION (object);
499 connection->finalizing = TRUE;
501 purge_all_signal_subscriptions (connection);
503 purge_all_filters (connection);
504 g_ptr_array_unref (connection->filters);
506 if (connection->authentication_observer != NULL)
507 g_object_unref (connection->authentication_observer);
509 if (connection->auth != NULL)
510 g_object_unref (connection->auth);
512 if (connection->credentials)
513 g_object_unref (connection->credentials);
515 if (connection->stream != NULL)
517 /* We don't really care if closing the stream succeeds or not */
518 g_io_stream_close_async (connection->stream,
520 NULL, /* GCancellable */
521 NULL, /* GAsyncReadyCallback */
522 NULL); /* userdata */
523 g_object_unref (connection->stream);
524 connection->stream = NULL;
527 g_free (connection->address);
529 g_free (connection->guid);
530 g_free (connection->bus_unique_name);
532 if (connection->initialization_error != NULL)
533 g_error_free (connection->initialization_error);
535 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
537 g_hash_table_unref (connection->map_rule_to_signal_data);
538 g_hash_table_unref (connection->map_id_to_signal_data);
539 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
541 g_hash_table_unref (connection->map_id_to_ei);
542 g_hash_table_unref (connection->map_object_path_to_eo);
543 g_hash_table_unref (connection->map_id_to_es);
544 g_hash_table_unref (connection->map_object_path_to_es);
546 if (connection->main_context_at_construction != NULL)
547 g_main_context_unref (connection->main_context_at_construction);
549 g_free (connection->machine_id);
551 g_mutex_free (connection->init_lock);
552 g_mutex_free (connection->lock);
554 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
558 g_dbus_connection_get_property (GObject *object,
563 GDBusConnection *connection = G_DBUS_CONNECTION (object);
568 g_value_set_object (value, g_dbus_connection_get_stream (connection));
572 g_value_set_string (value, g_dbus_connection_get_guid (connection));
575 case PROP_UNIQUE_NAME:
576 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
580 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
583 case PROP_EXIT_ON_CLOSE:
584 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
587 case PROP_CAPABILITY_FLAGS:
588 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
592 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
598 g_dbus_connection_set_property (GObject *object,
603 GDBusConnection *connection = G_DBUS_CONNECTION (object);
608 connection->stream = g_value_dup_object (value);
612 connection->guid = g_value_dup_string (value);
616 connection->address = g_value_dup_string (value);
620 connection->flags = g_value_get_flags (value);
623 case PROP_EXIT_ON_CLOSE:
624 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
627 case PROP_AUTHENTICATION_OBSERVER:
628 connection->authentication_observer = g_value_dup_object (value);
632 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
638 g_dbus_connection_real_closed (GDBusConnection *connection,
639 gboolean remote_peer_vanished,
642 if (remote_peer_vanished && connection->exit_on_close)
646 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
649 g_quark_to_string (error->domain), error->code);
653 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
660 g_dbus_connection_class_init (GDBusConnectionClass *klass)
662 GObjectClass *gobject_class;
664 gobject_class = G_OBJECT_CLASS (klass);
666 gobject_class->finalize = g_dbus_connection_finalize;
667 gobject_class->dispose = g_dbus_connection_dispose;
668 gobject_class->set_property = g_dbus_connection_set_property;
669 gobject_class->get_property = g_dbus_connection_get_property;
671 klass->closed = g_dbus_connection_real_closed;
674 * GDBusConnection:stream:
676 * The underlying #GIOStream used for I/O.
680 g_object_class_install_property (gobject_class,
682 g_param_spec_object ("stream",
684 P_("The underlying streams used for I/O"),
688 G_PARAM_CONSTRUCT_ONLY |
689 G_PARAM_STATIC_NAME |
690 G_PARAM_STATIC_BLURB |
691 G_PARAM_STATIC_NICK));
694 * GDBusConnection:address:
696 * A D-Bus address specifying potential endpoints that can be used
697 * when establishing the connection.
701 g_object_class_install_property (gobject_class,
703 g_param_spec_string ("address",
705 P_("D-Bus address specifying potential socket endpoints"),
708 G_PARAM_CONSTRUCT_ONLY |
709 G_PARAM_STATIC_NAME |
710 G_PARAM_STATIC_BLURB |
711 G_PARAM_STATIC_NICK));
714 * GDBusConnection:flags:
716 * Flags from the #GDBusConnectionFlags enumeration.
720 g_object_class_install_property (gobject_class,
722 g_param_spec_flags ("flags",
725 G_TYPE_DBUS_CONNECTION_FLAGS,
726 G_DBUS_CONNECTION_FLAGS_NONE,
728 G_PARAM_CONSTRUCT_ONLY |
729 G_PARAM_STATIC_NAME |
730 G_PARAM_STATIC_BLURB |
731 G_PARAM_STATIC_NICK));
734 * GDBusConnection:guid:
736 * The GUID of the peer performing the role of server when
739 * If you are constructing a #GDBusConnection and pass
740 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
741 * #GDBusConnection:flags property then you MUST also set this
742 * property to a valid guid.
744 * If you are constructing a #GDBusConnection and pass
745 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
746 * #GDBusConnection:flags property you will be able to read the GUID
747 * of the other peer here after the connection has been successfully
752 g_object_class_install_property (gobject_class,
754 g_param_spec_string ("guid",
756 P_("GUID of the server peer"),
760 G_PARAM_CONSTRUCT_ONLY |
761 G_PARAM_STATIC_NAME |
762 G_PARAM_STATIC_BLURB |
763 G_PARAM_STATIC_NICK));
766 * GDBusConnection:unique-name:
768 * The unique name as assigned by the message bus or %NULL if the
769 * connection is not open or not a message bus connection.
773 g_object_class_install_property (gobject_class,
775 g_param_spec_string ("unique-name",
777 P_("Unique name of bus connection"),
780 G_PARAM_STATIC_NAME |
781 G_PARAM_STATIC_BLURB |
782 G_PARAM_STATIC_NICK));
785 * GDBusConnection:closed:
787 * A boolean specifying whether the connection has been closed.
791 g_object_class_install_property (gobject_class,
793 g_param_spec_boolean ("closed",
795 P_("Whether the connection is closed"),
798 G_PARAM_STATIC_NAME |
799 G_PARAM_STATIC_BLURB |
800 G_PARAM_STATIC_NICK));
803 * GDBusConnection:exit-on-close:
805 * A boolean specifying whether the process will be terminated (by
806 * calling <literal>raise(SIGTERM)</literal>) if the connection
807 * is closed by the remote peer.
811 g_object_class_install_property (gobject_class,
813 g_param_spec_boolean ("exit-on-close",
815 P_("Whether the process is terminated when the connection is closed"),
819 G_PARAM_STATIC_NAME |
820 G_PARAM_STATIC_BLURB |
821 G_PARAM_STATIC_NICK));
824 * GDBusConnection:capabilities:
826 * Flags from the #GDBusCapabilityFlags enumeration
827 * representing connection features negotiated with the other peer.
831 g_object_class_install_property (gobject_class,
832 PROP_CAPABILITY_FLAGS,
833 g_param_spec_flags ("capabilities",
836 G_TYPE_DBUS_CAPABILITY_FLAGS,
837 G_DBUS_CAPABILITY_FLAGS_NONE,
839 G_PARAM_STATIC_NAME |
840 G_PARAM_STATIC_BLURB |
841 G_PARAM_STATIC_NICK));
844 * GDBusConnection:authentication-observer:
846 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
850 g_object_class_install_property (gobject_class,
851 PROP_AUTHENTICATION_OBSERVER,
852 g_param_spec_object ("authentication-observer",
853 P_("Authentication Observer"),
854 P_("Object used to assist in the authentication process"),
855 G_TYPE_DBUS_AUTH_OBSERVER,
857 G_PARAM_CONSTRUCT_ONLY |
858 G_PARAM_STATIC_NAME |
859 G_PARAM_STATIC_BLURB |
860 G_PARAM_STATIC_NICK));
863 * GDBusConnection::closed:
864 * @connection: The #GDBusConnection emitting the signal.
865 * @remote_peer_vanished: %TRUE if @connection is closed because the
866 * remote peer closed its end of the connection.
867 * @error: A #GError with more details about the event or %NULL.
869 * Emitted when the connection is closed.
871 * The cause of this event can be
874 * If g_dbus_connection_close() is called. In this case
875 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
878 * If the remote peer closes the connection. In this case
879 * @remote_peer_vanished is set to %TRUE and @error is set.
882 * If the remote peer sends invalid or malformed data. In this
883 * case @remote_peer_vanished is set to %FALSE and @error
888 * Upon receiving this signal, you should give up your reference to
889 * @connection. You are guaranteed that this signal is emitted only
894 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
895 G_TYPE_DBUS_CONNECTION,
897 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
900 _gio_marshal_VOID__BOOLEAN_BOXED,
908 g_dbus_connection_init (GDBusConnection *connection)
910 connection->lock = g_mutex_new ();
911 connection->init_lock = g_mutex_new ();
913 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
915 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
917 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
919 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
922 (GDestroyNotify) g_ptr_array_unref);
924 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
927 (GDestroyNotify) exported_object_free);
929 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
932 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
935 (GDestroyNotify) exported_subtree_free);
937 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
940 connection->main_context_at_construction = g_main_context_get_thread_default ();
941 if (connection->main_context_at_construction != NULL)
942 g_main_context_ref (connection->main_context_at_construction);
944 connection->filters = g_ptr_array_new ();
948 * g_dbus_connection_get_stream:
949 * @connection: a #GDBusConnection
951 * Gets the underlying stream used for IO.
953 * Returns: (transfer none): the stream used for IO
958 g_dbus_connection_get_stream (GDBusConnection *connection)
960 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
961 return connection->stream;
965 * g_dbus_connection_start_message_processing:
966 * @connection: A #GDBusConnection.
968 * If @connection was created with
969 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
970 * starts processing messages. Does nothing on if @connection wasn't
971 * created with this flag or if the method has already been called.
976 g_dbus_connection_start_message_processing (GDBusConnection *connection)
978 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
979 _g_dbus_worker_unfreeze (connection->worker);
983 * g_dbus_connection_is_closed:
984 * @connection: A #GDBusConnection.
986 * Gets whether @connection is closed.
988 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
993 g_dbus_connection_is_closed (GDBusConnection *connection)
995 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
996 return connection->closed;
1000 * g_dbus_connection_get_capabilities:
1001 * @connection: A #GDBusConnection.
1003 * Gets the capabilities negotiated with the remote peer
1005 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1009 GDBusCapabilityFlags
1010 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1012 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1013 return connection->capabilities;
1016 /* ---------------------------------------------------------------------------------------------------- */
1019 flush_in_thread_func (GSimpleAsyncResult *res,
1021 GCancellable *cancellable)
1026 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1029 g_simple_async_result_take_error (res, error);
1033 * g_dbus_connection_flush:
1034 * @connection: A #GDBusConnection.
1035 * @cancellable: A #GCancellable or %NULL.
1036 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1037 * care about the result.
1038 * @user_data: The data to pass to @callback.
1040 * Asynchronously flushes @connection, that is, writes all queued
1041 * outgoing message to the transport and then flushes the transport
1042 * (using g_output_stream_flush_async()). This is useful in programs
1043 * that wants to emit a D-Bus signal and then exit
1044 * immediately. Without flushing the connection, there is no guarantee
1045 * that the message has been sent to the networking buffers in the OS
1048 * This is an asynchronous method. When the operation is finished,
1049 * @callback will be invoked in the <link
1050 * linkend="g-main-context-push-thread-default">thread-default main
1051 * loop</link> of the thread you are calling this method from. You can
1052 * then call g_dbus_connection_flush_finish() to get the result of the
1053 * operation. See g_dbus_connection_flush_sync() for the synchronous
1059 g_dbus_connection_flush (GDBusConnection *connection,
1060 GCancellable *cancellable,
1061 GAsyncReadyCallback callback,
1064 GSimpleAsyncResult *simple;
1066 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1068 simple = g_simple_async_result_new (G_OBJECT (connection),
1071 g_dbus_connection_flush);
1072 g_simple_async_result_run_in_thread (simple,
1073 flush_in_thread_func,
1076 g_object_unref (simple);
1080 * g_dbus_connection_flush_finish:
1081 * @connection: A #GDBusConnection.
1082 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1083 * @error: Return location for error or %NULL.
1085 * Finishes an operation started with g_dbus_connection_flush().
1087 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1092 g_dbus_connection_flush_finish (GDBusConnection *connection,
1096 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1101 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1102 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1103 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1105 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1107 if (g_simple_async_result_propagate_error (simple, error))
1117 * g_dbus_connection_flush_sync:
1118 * @connection: A #GDBusConnection.
1119 * @cancellable: A #GCancellable or %NULL.
1120 * @error: Return location for error or %NULL.
1122 * Synchronously flushes @connection. The calling thread is blocked
1123 * until this is done. See g_dbus_connection_flush() for the
1124 * asynchronous version of this method and more details about what it
1127 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1132 g_dbus_connection_flush_sync (GDBusConnection *connection,
1133 GCancellable *cancellable,
1138 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1139 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1143 if (connection->closed)
1145 g_set_error_literal (error,
1148 _("The connection is closed"));
1152 ret = _g_dbus_worker_flush_sync (connection->worker,
1160 /* ---------------------------------------------------------------------------------------------------- */
1164 GDBusConnection *connection;
1166 gboolean remote_peer_vanished;
1170 emit_closed_data_free (EmitClosedData *data)
1172 g_object_unref (data->connection);
1173 if (data->error != NULL)
1174 g_error_free (data->error);
1179 emit_closed_in_idle (gpointer user_data)
1181 EmitClosedData *data = user_data;
1184 g_object_notify (G_OBJECT (data->connection), "closed");
1185 g_signal_emit (data->connection,
1186 signals[CLOSED_SIGNAL],
1188 data->remote_peer_vanished,
1194 /* Can be called from any thread, must hold lock */
1196 set_closed_unlocked (GDBusConnection *connection,
1197 gboolean remote_peer_vanished,
1200 GSource *idle_source;
1201 EmitClosedData *data;
1203 CONNECTION_ENSURE_LOCK (connection);
1205 g_assert (!connection->closed);
1207 connection->closed = TRUE;
1209 data = g_new0 (EmitClosedData, 1);
1210 data->connection = g_object_ref (connection);
1211 data->remote_peer_vanished = remote_peer_vanished;
1212 data->error = error != NULL ? g_error_copy (error) : NULL;
1214 idle_source = g_idle_source_new ();
1215 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1216 g_source_set_callback (idle_source,
1217 emit_closed_in_idle,
1219 (GDestroyNotify) emit_closed_data_free);
1220 g_source_attach (idle_source, connection->main_context_at_construction);
1221 g_source_unref (idle_source);
1224 /* ---------------------------------------------------------------------------------------------------- */
1227 close_in_thread_func (GSimpleAsyncResult *res,
1229 GCancellable *cancellable)
1234 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1237 g_simple_async_result_take_error (res, error);
1241 * g_dbus_connection_close:
1242 * @connection: A #GDBusConnection.
1243 * @cancellable: A #GCancellable or %NULL.
1244 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1245 * care about the result.
1246 * @user_data: The data to pass to @callback.
1248 * Closes @connection. Note that this never causes the process to
1249 * exit (this might only happen if the other end of a shared message
1250 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1252 * Once the connection is closed, operations such as sending a message
1253 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1254 * will not automatically flush the connection so queued messages may
1255 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1257 * If @connection is already closed, this method fails with
1258 * %G_IO_ERROR_CLOSED.
1260 * When @connection has been closed, the #GDBusConnection::closed
1261 * signal is emitted in the <link
1262 * linkend="g-main-context-push-thread-default">thread-default main
1263 * loop</link> of the thread that @connection was constructed in.
1265 * This is an asynchronous method. When the operation is finished,
1266 * @callback will be invoked in the <link
1267 * linkend="g-main-context-push-thread-default">thread-default main
1268 * loop</link> of the thread you are calling this method from. You can
1269 * then call g_dbus_connection_close_finish() to get the result of the
1270 * operation. See g_dbus_connection_close_sync() for the synchronous
1276 g_dbus_connection_close (GDBusConnection *connection,
1277 GCancellable *cancellable,
1278 GAsyncReadyCallback callback,
1281 GSimpleAsyncResult *simple;
1283 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1285 simple = g_simple_async_result_new (G_OBJECT (connection),
1288 g_dbus_connection_close);
1289 g_simple_async_result_run_in_thread (simple,
1290 close_in_thread_func,
1293 g_object_unref (simple);
1297 * g_dbus_connection_close_finish:
1298 * @connection: A #GDBusConnection.
1299 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1300 * @error: Return location for error or %NULL.
1302 * Finishes an operation started with g_dbus_connection_close().
1304 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1309 g_dbus_connection_close_finish (GDBusConnection *connection,
1313 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1318 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1319 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1320 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1322 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1324 if (g_simple_async_result_propagate_error (simple, error))
1334 * g_dbus_connection_close_sync:
1335 * @connection: A #GDBusConnection.
1336 * @cancellable: A #GCancellable or %NULL.
1337 * @error: Return location for error or %NULL.
1339 * Synchronously closees @connection. The calling thread is blocked
1340 * until this is done. See g_dbus_connection_close() for the
1341 * asynchronous version of this method and more details about what it
1344 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1349 g_dbus_connection_close_sync (GDBusConnection *connection,
1350 GCancellable *cancellable,
1355 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1356 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1360 CONNECTION_LOCK (connection);
1361 if (!connection->closed)
1363 ret = g_io_stream_close (connection->stream,
1367 set_closed_unlocked (connection, FALSE, NULL);
1371 g_set_error_literal (error,
1374 _("The connection is closed"));
1376 CONNECTION_UNLOCK (connection);
1381 /* ---------------------------------------------------------------------------------------------------- */
1384 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1385 GDBusMessage *message,
1386 GDBusSendMessageFlags flags,
1387 volatile guint32 *out_serial,
1392 guint32 serial_to_use;
1395 CONNECTION_ENSURE_LOCK (connection);
1397 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1398 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1400 /* TODO: check all necessary headers are present */
1405 if (out_serial != NULL)
1408 if (connection->closed)
1410 g_set_error_literal (error,
1413 _("The connection is closed"));
1417 blob = g_dbus_message_to_blob (message,
1419 connection->capabilities,
1424 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1425 serial_to_use = g_dbus_message_get_serial (message);
1427 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1432 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1435 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1438 g_assert_not_reached ();
1443 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1444 blob_size, serial_to_use, connection);
1445 g_printerr ("----\n");
1446 hexdump (blob, blob_size);
1447 g_printerr ("----\n");
1450 /* TODO: use connection->auth to encode the blob */
1452 if (out_serial != NULL)
1453 *out_serial = serial_to_use;
1455 g_dbus_message_set_serial (message, serial_to_use);
1457 g_dbus_message_lock (message);
1458 _g_dbus_worker_send_message (connection->worker,
1462 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1473 * g_dbus_connection_send_message:
1474 * @connection: A #GDBusConnection.
1475 * @message: A #GDBusMessage
1476 * @flags: Flags affecting how the message is sent.
1477 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1478 * @error: Return location for error or %NULL.
1480 * Asynchronously sends @message to the peer represented by @connection.
1482 * Unless @flags contain the
1483 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1484 * will be assigned by @connection and set on @message via
1485 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1486 * serial number used will be written to this location prior to
1487 * submitting the message to the underlying transport.
1489 * If @connection is closed then the operation will fail with
1490 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1491 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1493 * See <xref linkend="gdbus-server"/> and <xref
1494 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1495 * low-level API to send and receive UNIX file descriptors.
1497 * Note that @message must be unlocked, unless @flags contain the
1498 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1500 * Returns: %TRUE if the message was well-formed and queued for
1501 * transmission, %FALSE if @error is set.
1506 g_dbus_connection_send_message (GDBusConnection *connection,
1507 GDBusMessage *message,
1508 GDBusSendMessageFlags flags,
1509 volatile guint32 *out_serial,
1514 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1515 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1516 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1517 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1519 CONNECTION_LOCK (connection);
1520 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1521 CONNECTION_UNLOCK (connection);
1525 /* ---------------------------------------------------------------------------------------------------- */
1529 volatile gint ref_count;
1530 GDBusConnection *connection;
1532 GSimpleAsyncResult *simple;
1534 GMainContext *main_context;
1536 GCancellable *cancellable;
1538 gulong cancellable_handler_id;
1540 GSource *timeout_source;
1545 static SendMessageData *
1546 send_message_data_ref (SendMessageData *data)
1548 g_atomic_int_inc (&data->ref_count);
1553 send_message_data_unref (SendMessageData *data)
1555 if (g_atomic_int_dec_and_test (&data->ref_count))
1557 g_assert (data->timeout_source == NULL);
1558 g_assert (data->simple == NULL);
1559 g_assert (data->cancellable_handler_id == 0);
1560 g_object_unref (data->connection);
1561 if (data->cancellable != NULL)
1562 g_object_unref (data->cancellable);
1563 if (data->main_context != NULL)
1564 g_main_context_unref (data->main_context);
1569 /* ---------------------------------------------------------------------------------------------------- */
1571 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1573 send_message_with_reply_deliver (SendMessageData *data)
1575 CONNECTION_ENSURE_LOCK (data->connection);
1577 g_assert (!data->delivered);
1579 data->delivered = TRUE;
1581 g_simple_async_result_complete_in_idle (data->simple);
1582 g_object_unref (data->simple);
1583 data->simple = NULL;
1585 if (data->timeout_source != NULL)
1587 g_source_destroy (data->timeout_source);
1588 data->timeout_source = NULL;
1590 if (data->cancellable_handler_id > 0)
1592 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1593 data->cancellable_handler_id = 0;
1596 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1597 GUINT_TO_POINTER (data->serial)));
1599 send_message_data_unref (data);
1602 /* ---------------------------------------------------------------------------------------------------- */
1604 /* must hold lock */
1606 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1607 GDBusMessage *reply)
1609 if (data->delivered)
1612 g_simple_async_result_set_op_res_gpointer (data->simple,
1613 g_object_ref (reply),
1616 send_message_with_reply_deliver (data);
1622 /* ---------------------------------------------------------------------------------------------------- */
1625 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1627 SendMessageData *data = user_data;
1629 CONNECTION_LOCK (data->connection);
1630 if (data->delivered)
1633 g_simple_async_result_set_error (data->simple,
1635 G_IO_ERROR_CANCELLED,
1636 _("Operation was cancelled"));
1638 send_message_with_reply_deliver (data);
1641 CONNECTION_UNLOCK (data->connection);
1645 /* Can be called from any thread with or without lock held */
1647 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1650 SendMessageData *data = user_data;
1651 GSource *idle_source;
1653 /* postpone cancellation to idle handler since we may be called directly
1654 * via g_cancellable_connect() (e.g. holding lock)
1656 idle_source = g_idle_source_new ();
1657 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1658 g_source_set_callback (idle_source,
1659 send_message_with_reply_cancelled_idle_cb,
1660 send_message_data_ref (data),
1661 (GDestroyNotify) send_message_data_unref);
1662 g_source_attach (idle_source, data->main_context);
1663 g_source_unref (idle_source);
1666 /* ---------------------------------------------------------------------------------------------------- */
1669 send_message_with_reply_timeout_cb (gpointer user_data)
1671 SendMessageData *data = user_data;
1673 CONNECTION_LOCK (data->connection);
1674 if (data->delivered)
1677 g_simple_async_result_set_error (data->simple,
1679 G_IO_ERROR_TIMED_OUT,
1680 _("Timeout was reached"));
1682 send_message_with_reply_deliver (data);
1685 CONNECTION_UNLOCK (data->connection);
1690 /* ---------------------------------------------------------------------------------------------------- */
1693 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1694 GDBusMessage *message,
1695 GDBusSendMessageFlags flags,
1697 volatile guint32 *out_serial,
1698 GCancellable *cancellable,
1699 GAsyncReadyCallback callback,
1702 GSimpleAsyncResult *simple;
1703 SendMessageData *data;
1705 volatile guint32 serial;
1709 if (out_serial == NULL)
1710 out_serial = &serial;
1712 if (timeout_msec == -1)
1713 timeout_msec = 25 * 1000;
1715 simple = g_simple_async_result_new (G_OBJECT (connection),
1718 g_dbus_connection_send_message_with_reply);
1720 if (g_cancellable_is_cancelled (cancellable))
1722 g_simple_async_result_set_error (simple,
1724 G_IO_ERROR_CANCELLED,
1725 _("Operation was cancelled"));
1726 g_simple_async_result_complete_in_idle (simple);
1727 g_object_unref (simple);
1731 if (connection->closed)
1733 g_simple_async_result_set_error (simple,
1736 _("The connection is closed"));
1737 g_simple_async_result_complete_in_idle (simple);
1738 g_object_unref (simple);
1743 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1745 g_simple_async_result_take_error (simple, error);
1746 g_simple_async_result_complete_in_idle (simple);
1747 g_object_unref (simple);
1751 data = g_new0 (SendMessageData, 1);
1752 data->ref_count = 1;
1753 data->connection = g_object_ref (connection);
1754 data->simple = simple;
1755 data->serial = *out_serial;
1756 data->main_context = g_main_context_get_thread_default ();
1757 if (data->main_context != NULL)
1758 g_main_context_ref (data->main_context);
1760 if (cancellable != NULL)
1762 data->cancellable = g_object_ref (cancellable);
1763 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1764 G_CALLBACK (send_message_with_reply_cancelled_cb),
1765 send_message_data_ref (data),
1766 (GDestroyNotify) send_message_data_unref);
1767 g_object_set_data_full (G_OBJECT (simple),
1769 g_object_ref (cancellable),
1770 (GDestroyNotify) g_object_unref);
1773 if (timeout_msec != G_MAXINT)
1775 data->timeout_source = g_timeout_source_new (timeout_msec);
1776 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1777 g_source_set_callback (data->timeout_source,
1778 send_message_with_reply_timeout_cb,
1779 send_message_data_ref (data),
1780 (GDestroyNotify) send_message_data_unref);
1781 g_source_attach (data->timeout_source, data->main_context);
1782 g_source_unref (data->timeout_source);
1785 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1786 GUINT_TO_POINTER (*out_serial),
1794 * g_dbus_connection_send_message_with_reply:
1795 * @connection: A #GDBusConnection.
1796 * @message: A #GDBusMessage.
1797 * @flags: Flags affecting how the message is sent.
1798 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1799 * timeout or %G_MAXINT for no timeout.
1800 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1801 * @cancellable: A #GCancellable or %NULL.
1802 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
1803 * care about the result.
1804 * @user_data: The data to pass to @callback.
1806 * Asynchronously sends @message to the peer represented by @connection.
1808 * Unless @flags contain the
1809 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1810 * will be assigned by @connection and set on @message via
1811 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1812 * serial number used will be written to this location prior to
1813 * submitting the message to the underlying transport.
1815 * If @connection is closed then the operation will fail with
1816 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1817 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1818 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1820 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1821 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1822 * of the thread you are calling this method from. You can then call
1823 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1824 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1826 * Note that @message must be unlocked, unless @flags contain the
1827 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1829 * See <xref linkend="gdbus-server"/> and <xref
1830 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1831 * low-level API to send and receive UNIX file descriptors.
1836 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1837 GDBusMessage *message,
1838 GDBusSendMessageFlags flags,
1840 volatile guint32 *out_serial,
1841 GCancellable *cancellable,
1842 GAsyncReadyCallback callback,
1845 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1846 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1847 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1848 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1850 CONNECTION_LOCK (connection);
1851 g_dbus_connection_send_message_with_reply_unlocked (connection,
1859 CONNECTION_UNLOCK (connection);
1863 * g_dbus_connection_send_message_with_reply_finish:
1864 * @connection: a #GDBusConnection
1865 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1866 * @error: Return location for error or %NULL.
1868 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1870 * Note that @error is only set if a local in-process error
1871 * occured. That is to say that the returned #GDBusMessage object may
1872 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1873 * g_dbus_message_to_gerror() to transcode this to a #GError.
1875 * See <xref linkend="gdbus-server"/> and <xref
1876 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1877 * low-level API to send and receive UNIX file descriptors.
1879 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
1884 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1888 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1889 GDBusMessage *reply;
1890 GCancellable *cancellable;
1892 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1893 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1897 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1899 if (g_simple_async_result_propagate_error (simple, error))
1902 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1903 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1904 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1906 g_object_unref (reply);
1908 g_set_error_literal (error,
1910 G_IO_ERROR_CANCELLED,
1911 _("Operation was cancelled"));
1917 /* ---------------------------------------------------------------------------------------------------- */
1922 GMainContext *context;
1924 } SendMessageSyncData;
1927 send_message_with_reply_sync_cb (GDBusConnection *connection,
1931 SendMessageSyncData *data = user_data;
1932 data->res = g_object_ref (res);
1933 g_main_loop_quit (data->loop);
1937 * g_dbus_connection_send_message_with_reply_sync:
1938 * @connection: A #GDBusConnection.
1939 * @message: A #GDBusMessage.
1940 * @flags: Flags affecting how the message is sent.
1941 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1942 * timeout or %G_MAXINT for no timeout.
1943 * @out_serial: Return location for serial number assigned to @message when sending it or %NULL.
1944 * @cancellable: A #GCancellable or %NULL.
1945 * @error: Return location for error or %NULL.
1947 * Synchronously sends @message to the peer represented by @connection
1948 * and blocks the calling thread until a reply is received or the
1949 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1950 * for the asynchronous version of this method.
1952 * Unless @flags contain the
1953 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1954 * will be assigned by @connection and set on @message via
1955 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1956 * serial number used will be written to this location prior to
1957 * submitting the message to the underlying transport.
1959 * If @connection is closed then the operation will fail with
1960 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1961 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1962 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1964 * Note that @error is only set if a local in-process error
1965 * occured. That is to say that the returned #GDBusMessage object may
1966 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1967 * g_dbus_message_to_gerror() to transcode this to a #GError.
1969 * See <xref linkend="gdbus-server"/> and <xref
1970 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1971 * low-level API to send and receive UNIX file descriptors.
1973 * Note that @message must be unlocked, unless @flags contain the
1974 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1976 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
1981 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1982 GDBusMessage *message,
1983 GDBusSendMessageFlags flags,
1985 volatile guint32 *out_serial,
1986 GCancellable *cancellable,
1989 SendMessageSyncData *data;
1990 GDBusMessage *reply;
1992 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1993 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
1994 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1995 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
1996 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1998 data = g_new0 (SendMessageSyncData, 1);
1999 data->context = g_main_context_new ();
2000 data->loop = g_main_loop_new (data->context, FALSE);
2002 g_main_context_push_thread_default (data->context);
2004 g_dbus_connection_send_message_with_reply (connection,
2010 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2012 g_main_loop_run (data->loop);
2013 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2017 g_main_context_pop_thread_default (data->context);
2019 g_main_context_unref (data->context);
2020 g_main_loop_unref (data->loop);
2021 g_object_unref (data->res);
2027 /* ---------------------------------------------------------------------------------------------------- */
2031 GDBusMessageFilterFunction func;
2038 GDBusMessageFilterFunction filter_function;
2040 GDestroyNotify user_data_free_func;
2043 /* Called in worker's thread - we must not block */
2045 on_worker_message_received (GDBusWorker *worker,
2046 GDBusMessage *message,
2049 GDBusConnection *connection;
2050 FilterCallback *filters;
2051 gboolean consumed_by_filter;
2052 gboolean altered_by_filter;
2057 G_LOCK (message_bus_lock);
2058 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2061 G_UNLOCK (message_bus_lock);
2064 connection = G_DBUS_CONNECTION (user_data);
2065 g_object_ref (connection);
2066 G_UNLOCK (message_bus_lock);
2068 //g_debug ("in on_worker_message_received");
2070 g_object_ref (message);
2071 g_dbus_message_lock (message);
2073 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2075 /* First collect the set of callback functions */
2076 CONNECTION_LOCK (connection);
2077 num_filters = connection->filters->len;
2078 filters = g_new0 (FilterCallback, num_filters);
2079 for (n = 0; n < num_filters; n++)
2081 FilterData *data = connection->filters->pdata[n];
2082 filters[n].func = data->filter_function;
2083 filters[n].user_data = data->user_data;
2085 CONNECTION_UNLOCK (connection);
2087 /* then call the filters in order (without holding the lock) */
2088 consumed_by_filter = FALSE;
2089 altered_by_filter = FALSE;
2090 for (n = 0; n < num_filters; n++)
2092 message = filters[n].func (connection,
2095 filters[n].user_data);
2096 if (message == NULL)
2098 g_dbus_message_lock (message);
2101 /* Standard dispatch unless the filter ate the message - no need to
2102 * do anything if the message was altered
2104 if (message != NULL)
2106 GDBusMessageType message_type;
2108 message_type = g_dbus_message_get_message_type (message);
2109 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2111 guint32 reply_serial;
2112 SendMessageData *send_message_data;
2114 reply_serial = g_dbus_message_get_reply_serial (message);
2115 CONNECTION_LOCK (connection);
2116 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2117 GUINT_TO_POINTER (reply_serial));
2118 if (send_message_data != NULL)
2120 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2121 send_message_data_deliver_reply_unlocked (send_message_data, message);
2125 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2127 CONNECTION_UNLOCK (connection);
2129 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2131 CONNECTION_LOCK (connection);
2132 distribute_signals (connection, message);
2133 CONNECTION_UNLOCK (connection);
2135 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2137 CONNECTION_LOCK (connection);
2138 distribute_method_call (connection, message);
2139 CONNECTION_UNLOCK (connection);
2143 if (message != NULL)
2144 g_object_unref (message);
2145 g_object_unref (connection);
2149 /* Called in worker's thread */
2150 static GDBusMessage *
2151 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2152 GDBusMessage *message,
2155 GDBusConnection *connection;
2156 FilterCallback *filters;
2161 G_LOCK (message_bus_lock);
2162 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2165 G_UNLOCK (message_bus_lock);
2168 connection = G_DBUS_CONNECTION (user_data);
2169 g_object_ref (connection);
2170 G_UNLOCK (message_bus_lock);
2172 //g_debug ("in on_worker_message_about_to_be_sent");
2174 /* First collect the set of callback functions */
2175 CONNECTION_LOCK (connection);
2176 num_filters = connection->filters->len;
2177 filters = g_new0 (FilterCallback, num_filters);
2178 for (n = 0; n < num_filters; n++)
2180 FilterData *data = connection->filters->pdata[n];
2181 filters[n].func = data->filter_function;
2182 filters[n].user_data = data->user_data;
2184 CONNECTION_UNLOCK (connection);
2186 /* then call the filters in order (without holding the lock) */
2187 for (n = 0; n < num_filters; n++)
2189 g_dbus_message_lock (message);
2190 message = filters[n].func (connection,
2193 filters[n].user_data);
2194 if (message == NULL)
2198 g_object_unref (connection);
2204 /* Called in worker's thread - we must not block */
2206 on_worker_closed (GDBusWorker *worker,
2207 gboolean remote_peer_vanished,
2211 GDBusConnection *connection;
2214 G_LOCK (message_bus_lock);
2215 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2218 G_UNLOCK (message_bus_lock);
2221 connection = G_DBUS_CONNECTION (user_data);
2222 g_object_ref (connection);
2223 G_UNLOCK (message_bus_lock);
2225 //g_debug ("in on_worker_closed: %s", error->message);
2227 CONNECTION_LOCK (connection);
2228 if (!connection->closed)
2229 set_closed_unlocked (connection, remote_peer_vanished, error);
2230 CONNECTION_UNLOCK (connection);
2232 g_object_unref (connection);
2235 /* ---------------------------------------------------------------------------------------------------- */
2237 /* Determines the biggest set of capabilities we can support on this connection */
2238 static GDBusCapabilityFlags
2239 get_offered_capabilities_max (GDBusConnection *connection)
2241 GDBusCapabilityFlags ret;
2242 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2244 if (G_IS_UNIX_CONNECTION (connection->stream))
2245 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2251 initable_init (GInitable *initable,
2252 GCancellable *cancellable,
2255 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2258 /* This method needs to be idempotent to work with the singleton
2259 * pattern. See the docs for g_initable_init(). We implement this by
2262 * Unfortunately we can't use the main lock since the on_worker_*()
2263 * callbacks above needs the lock during initialization (for message
2264 * bus connections we do a synchronous Hello() call on the bus).
2266 g_mutex_lock (connection->init_lock);
2270 if (connection->is_initialized)
2272 if (connection->stream != NULL)
2275 g_assert (connection->initialization_error != NULL);
2278 g_assert (connection->initialization_error == NULL);
2280 /* The user can pass multiple (but mutally exclusive) construct
2283 * - stream (of type GIOStream)
2284 * - address (of type gchar*)
2286 * At the end of the day we end up with a non-NULL GIOStream
2287 * object in connection->stream.
2289 if (connection->address != NULL)
2291 g_assert (connection->stream == NULL);
2293 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2294 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2296 g_set_error_literal (error,
2298 G_IO_ERROR_INVALID_ARGUMENT,
2299 _("Unsupported flags encountered when constructing a client-side connection"));
2303 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2304 NULL, /* TODO: out_guid */
2306 &connection->initialization_error);
2307 if (connection->stream == NULL)
2310 else if (connection->stream != NULL)
2316 g_assert_not_reached ();
2319 /* Authenticate the connection */
2320 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2322 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2323 g_assert (connection->guid != NULL);
2324 connection->auth = _g_dbus_auth_new (connection->stream);
2325 if (!_g_dbus_auth_run_server (connection->auth,
2326 connection->authentication_observer,
2328 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2329 get_offered_capabilities_max (connection),
2330 &connection->capabilities,
2331 &connection->credentials,
2333 &connection->initialization_error))
2336 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2338 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2339 g_assert (connection->guid == NULL);
2340 connection->auth = _g_dbus_auth_new (connection->stream);
2341 connection->guid = _g_dbus_auth_run_client (connection->auth,
2342 get_offered_capabilities_max (connection),
2343 &connection->capabilities,
2345 &connection->initialization_error);
2346 if (connection->guid == NULL)
2350 if (connection->authentication_observer != NULL)
2352 g_object_unref (connection->authentication_observer);
2353 connection->authentication_observer = NULL;
2356 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2358 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2363 * https://bugzilla.gnome.org/show_bug.cgi?id=616458
2367 if (G_IS_SOCKET_CONNECTION (connection->stream))
2369 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2373 G_LOCK (message_bus_lock);
2374 if (alive_connections == NULL)
2375 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2376 g_hash_table_insert (alive_connections, connection, connection);
2377 G_UNLOCK (message_bus_lock);
2379 connection->worker = _g_dbus_worker_new (connection->stream,
2380 connection->capabilities,
2381 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2382 on_worker_message_received,
2383 on_worker_message_about_to_be_sent,
2387 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2388 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2390 GVariant *hello_result;
2392 /* we could lift this restriction by adding code in gdbusprivate.c */
2393 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2395 g_set_error_literal (&connection->initialization_error,
2398 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2402 hello_result = g_dbus_connection_call_sync (connection,
2403 "org.freedesktop.DBus", /* name */
2404 "/org/freedesktop/DBus", /* path */
2405 "org.freedesktop.DBus", /* interface */
2407 NULL, /* parameters */
2408 G_VARIANT_TYPE ("(s)"),
2409 G_DBUS_CALL_FLAGS_NONE,
2411 NULL, /* TODO: cancellable */
2412 &connection->initialization_error);
2413 if (hello_result == NULL)
2416 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2417 g_variant_unref (hello_result);
2418 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2421 connection->is_initialized = TRUE;
2427 g_assert (connection->initialization_error != NULL);
2428 g_propagate_error (error, g_error_copy (connection->initialization_error));
2431 g_mutex_unlock (connection->init_lock);
2437 initable_iface_init (GInitableIface *initable_iface)
2439 initable_iface->init = initable_init;
2442 /* ---------------------------------------------------------------------------------------------------- */
2445 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2450 /* ---------------------------------------------------------------------------------------------------- */
2453 * g_dbus_connection_new:
2454 * @stream: A #GIOStream.
2455 * @guid: The GUID to use if a authenticating as a server or %NULL.
2456 * @flags: Flags describing how to make the connection.
2457 * @observer: A #GDBusAuthObserver or %NULL.
2458 * @cancellable: A #GCancellable or %NULL.
2459 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2460 * @user_data: The data to pass to @callback.
2462 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2463 * with the end represented by @stream.
2465 * If @observer is not %NULL it may be used to control the
2466 * authentication process.
2468 * When the operation is finished, @callback will be invoked. You can
2469 * then call g_dbus_connection_new_finish() to get the result of the
2472 * This is a asynchronous failable constructor. See
2473 * g_dbus_connection_new_sync() for the synchronous
2479 g_dbus_connection_new (GIOStream *stream,
2481 GDBusConnectionFlags flags,
2482 GDBusAuthObserver *observer,
2483 GCancellable *cancellable,
2484 GAsyncReadyCallback callback,
2487 g_return_if_fail (G_IS_IO_STREAM (stream));
2488 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2496 "authentication-observer", observer,
2501 * g_dbus_connection_new_finish:
2502 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2503 * @error: Return location for error or %NULL.
2505 * Finishes an operation started with g_dbus_connection_new().
2507 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2512 g_dbus_connection_new_finish (GAsyncResult *res,
2516 GObject *source_object;
2518 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2519 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2521 source_object = g_async_result_get_source_object (res);
2522 g_assert (source_object != NULL);
2523 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2526 g_object_unref (source_object);
2528 return G_DBUS_CONNECTION (object);
2534 * g_dbus_connection_new_sync:
2535 * @stream: A #GIOStream.
2536 * @guid: The GUID to use if a authenticating as a server or %NULL.
2537 * @flags: Flags describing how to make the connection.
2538 * @observer: A #GDBusAuthObserver or %NULL.
2539 * @cancellable: A #GCancellable or %NULL.
2540 * @error: Return location for error or %NULL.
2542 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2543 * with the end represented by @stream.
2545 * If @observer is not %NULL it may be used to control the
2546 * authentication process.
2548 * This is a synchronous failable constructor. See
2549 * g_dbus_connection_new() for the asynchronous version.
2551 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2556 g_dbus_connection_new_sync (GIOStream *stream,
2558 GDBusConnectionFlags flags,
2559 GDBusAuthObserver *observer,
2560 GCancellable *cancellable,
2563 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2564 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2565 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2571 "authentication-observer", observer,
2575 /* ---------------------------------------------------------------------------------------------------- */
2578 * g_dbus_connection_new_for_address:
2579 * @address: A D-Bus address.
2580 * @flags: Flags describing how to make the connection.
2581 * @observer: A #GDBusAuthObserver or %NULL.
2582 * @cancellable: A #GCancellable or %NULL.
2583 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2584 * @user_data: The data to pass to @callback.
2586 * Asynchronously connects and sets up a D-Bus client connection for
2587 * exchanging D-Bus messages with an endpoint specified by @address
2588 * which must be in the D-Bus address format.
2590 * This constructor can only be used to initiate client-side
2591 * connections - use g_dbus_connection_new() if you need to act as the
2592 * server. In particular, @flags cannot contain the
2593 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2594 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2596 * When the operation is finished, @callback will be invoked. You can
2597 * then call g_dbus_connection_new_finish() to get the result of the
2600 * If @observer is not %NULL it may be used to control the
2601 * authentication process.
2603 * This is a asynchronous failable constructor. See
2604 * g_dbus_connection_new_for_address_sync() for the synchronous
2610 g_dbus_connection_new_for_address (const gchar *address,
2611 GDBusConnectionFlags flags,
2612 GDBusAuthObserver *observer,
2613 GCancellable *cancellable,
2614 GAsyncReadyCallback callback,
2617 g_return_if_fail (address != NULL);
2618 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2625 "authentication-observer", observer,
2630 * g_dbus_connection_new_for_address_finish:
2631 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2632 * @error: Return location for error or %NULL.
2634 * Finishes an operation started with g_dbus_connection_new_for_address().
2636 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2641 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2645 GObject *source_object;
2647 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2648 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2650 source_object = g_async_result_get_source_object (res);
2651 g_assert (source_object != NULL);
2652 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2655 g_object_unref (source_object);
2657 return G_DBUS_CONNECTION (object);
2663 * g_dbus_connection_new_for_address_sync:
2664 * @address: A D-Bus address.
2665 * @flags: Flags describing how to make the connection.
2666 * @observer: A #GDBusAuthObserver or %NULL.
2667 * @cancellable: A #GCancellable or %NULL.
2668 * @error: Return location for error or %NULL.
2670 * Synchronously connects and sets up a D-Bus client connection for
2671 * exchanging D-Bus messages with an endpoint specified by @address
2672 * which must be in the D-Bus address format.
2674 * This constructor can only be used to initiate client-side
2675 * connections - use g_dbus_connection_new_sync() if you need to act
2676 * as the server. In particular, @flags cannot contain the
2677 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2678 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2680 * This is a synchronous failable constructor. See
2681 * g_dbus_connection_new_for_address() for the asynchronous version.
2683 * If @observer is not %NULL it may be used to control the
2684 * authentication process.
2686 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2691 g_dbus_connection_new_for_address_sync (const gchar *address,
2692 GDBusConnectionFlags flags,
2693 GDBusAuthObserver *observer,
2694 GCancellable *cancellable,
2697 g_return_val_if_fail (address != NULL, NULL);
2698 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2699 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2704 "authentication-observer", observer,
2708 /* ---------------------------------------------------------------------------------------------------- */
2711 * g_dbus_connection_set_exit_on_close:
2712 * @connection: A #GDBusConnection.
2713 * @exit_on_close: Whether the process should be terminated
2714 * when @connection is closed by the remote peer.
2716 * Sets whether the process should be terminated when @connection is
2717 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2723 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2724 gboolean exit_on_close)
2726 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2727 connection->exit_on_close = exit_on_close;
2731 * g_dbus_connection_get_exit_on_close:
2732 * @connection: A #GDBusConnection.
2734 * Gets whether the process is terminated when @connection is
2735 * closed by the remote peer. See
2736 * #GDBusConnection:exit-on-close for more details.
2738 * Returns: Whether the process is terminated when @connection is
2739 * closed by the remote peer.
2744 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2746 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2747 return connection->exit_on_close;
2751 * g_dbus_connection_get_guid:
2752 * @connection: A #GDBusConnection.
2754 * The GUID of the peer performing the role of server when
2755 * authenticating. See #GDBusConnection:guid for more details.
2757 * Returns: The GUID. Do not free this string, it is owned by
2763 g_dbus_connection_get_guid (GDBusConnection *connection)
2765 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2766 return connection->guid;
2770 * g_dbus_connection_get_unique_name:
2771 * @connection: A #GDBusConnection.
2773 * Gets the unique name of @connection as assigned by the message
2774 * bus. This can also be used to figure out if @connection is a
2775 * message bus connection.
2777 * Returns: The unique name or %NULL if @connection is not a message
2778 * bus connection. Do not free this string, it is owned by
2784 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2786 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2787 return connection->bus_unique_name;
2791 * g_dbus_connection_get_peer_credentials:
2792 * @connection: A #GDBusConnection.
2794 * Gets the credentials of the authenticated peer. This will always
2795 * return %NULL unless @connection acted as a server
2796 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2797 * when set up and the client passed credentials as part of the
2798 * authentication process.
2800 * In a message bus setup, the message bus is always the server and
2801 * each application is a client. So this method will always return
2802 * %NULL for message bus clients.
2804 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
2805 * this object, it is owned by @connection.
2810 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2812 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2813 return connection->credentials;
2816 /* ---------------------------------------------------------------------------------------------------- */
2818 static guint _global_filter_id = 1;
2821 * g_dbus_connection_add_filter:
2822 * @connection: A #GDBusConnection.
2823 * @filter_function: A filter function.
2824 * @user_data: User data to pass to @filter_function.
2825 * @user_data_free_func: Function to free @user_data with when filter
2826 * is removed or %NULL.
2828 * Adds a message filter. Filters are handlers that are run on all
2829 * incoming and outgoing messages, prior to standard dispatch. Filters
2830 * are run in the order that they were added. The same handler can be
2831 * added as a filter more than once, in which case it will be run more
2832 * than once. Filters added during a filter callback won't be run on
2833 * the message being processed. Filter functions are allowed to modify
2834 * and even drop messages - see the #GDBusMessageFilterResult
2835 * enumeration for details.
2837 * Note that filters are run in a dedicated message handling thread so
2838 * they can't block and, generally, can't do anything but signal a
2839 * worker thread. Also note that filters are rarely needed - use API
2840 * such as g_dbus_connection_send_message_with_reply(),
2841 * g_dbus_connection_signal_subscribe() or
2842 * g_dbus_connection_call() instead.
2844 * If a filter consumes an incoming message the message is not
2845 * dispatched anywhere else - not even the standard dispatch machinery
2846 * (that API such as g_dbus_connection_signal_subscribe() and
2847 * g_dbus_connection_send_message_with_reply() relies on) will see the
2848 * message. Similary, if a filter consumes an outgoing message, the
2849 * message will not be sent to the other peer.
2851 * Returns: A filter identifier that can be used with
2852 * g_dbus_connection_remove_filter().
2857 g_dbus_connection_add_filter (GDBusConnection *connection,
2858 GDBusMessageFilterFunction filter_function,
2860 GDestroyNotify user_data_free_func)
2864 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2865 g_return_val_if_fail (filter_function != NULL, 0);
2867 CONNECTION_LOCK (connection);
2868 data = g_new0 (FilterData, 1);
2869 data->id = _global_filter_id++; /* TODO: overflow etc. */
2870 data->filter_function = filter_function;
2871 data->user_data = user_data;
2872 data->user_data_free_func = user_data_free_func;
2873 g_ptr_array_add (connection->filters, data);
2874 CONNECTION_UNLOCK (connection);
2879 /* only called from finalize(), removes all filters */
2881 purge_all_filters (GDBusConnection *connection)
2884 for (n = 0; n < connection->filters->len; n++)
2886 FilterData *data = connection->filters->pdata[n];
2887 if (data->user_data_free_func != NULL)
2888 data->user_data_free_func (data->user_data);
2894 * g_dbus_connection_remove_filter:
2895 * @connection: a #GDBusConnection
2896 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2903 g_dbus_connection_remove_filter (GDBusConnection *connection,
2907 FilterData *to_destroy;
2909 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2911 CONNECTION_LOCK (connection);
2913 for (n = 0; n < connection->filters->len; n++)
2915 FilterData *data = connection->filters->pdata[n];
2916 if (data->id == filter_id)
2918 g_ptr_array_remove_index (connection->filters, n);
2923 CONNECTION_UNLOCK (connection);
2925 /* do free without holding lock */
2926 if (to_destroy != NULL)
2928 if (to_destroy->user_data_free_func != NULL)
2929 to_destroy->user_data_free_func (to_destroy->user_data);
2930 g_free (to_destroy);
2934 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2938 /* ---------------------------------------------------------------------------------------------------- */
2944 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2945 gchar *interface_name;
2949 GArray *subscribers;
2954 GDBusSignalCallback callback;
2956 GDestroyNotify user_data_free_func;
2958 GMainContext *context;
2962 signal_data_free (SignalData *signal_data)
2964 g_free (signal_data->rule);
2965 g_free (signal_data->sender);
2966 g_free (signal_data->sender_unique_name);
2967 g_free (signal_data->interface_name);
2968 g_free (signal_data->member);
2969 g_free (signal_data->object_path);
2970 g_free (signal_data->arg0);
2971 g_array_free (signal_data->subscribers, TRUE);
2972 g_free (signal_data);
2976 args_to_rule (const gchar *sender,
2977 const gchar *interface_name,
2978 const gchar *member,
2979 const gchar *object_path,
2984 rule = g_string_new ("type='signal'");
2986 g_string_append_printf (rule, ",sender='%s'", sender);
2987 if (interface_name != NULL)
2988 g_string_append_printf (rule, ",interface='%s'", interface_name);
2990 g_string_append_printf (rule, ",member='%s'", member);
2991 if (object_path != NULL)
2992 g_string_append_printf (rule, ",path='%s'", object_path);
2994 g_string_append_printf (rule, ",arg0='%s'", arg0);
2996 return g_string_free (rule, FALSE);
2999 static guint _global_subscriber_id = 1;
3000 static guint _global_registration_id = 1;
3001 static guint _global_subtree_registration_id = 1;
3003 /* ---------------------------------------------------------------------------------------------------- */
3005 /* must hold lock when calling */
3007 add_match_rule (GDBusConnection *connection,
3008 const gchar *match_rule)
3011 GDBusMessage *message;
3013 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3014 "/org/freedesktop/DBus", /* path */
3015 "org.freedesktop.DBus", /* interface */
3017 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3019 if (!g_dbus_connection_send_message_unlocked (connection,
3021 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3025 g_critical ("Error while sending AddMatch() message: %s", error->message);
3026 g_error_free (error);
3028 g_object_unref (message);
3031 /* ---------------------------------------------------------------------------------------------------- */
3033 /* must hold lock when calling */
3035 remove_match_rule (GDBusConnection *connection,
3036 const gchar *match_rule)
3039 GDBusMessage *message;
3041 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3042 "/org/freedesktop/DBus", /* path */
3043 "org.freedesktop.DBus", /* interface */
3045 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3048 if (!g_dbus_connection_send_message_unlocked (connection,
3050 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3054 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3055 g_error_free (error);
3057 g_object_unref (message);
3060 /* ---------------------------------------------------------------------------------------------------- */
3063 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3065 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3066 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3067 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3068 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3069 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3072 /* ---------------------------------------------------------------------------------------------------- */
3075 * g_dbus_connection_signal_subscribe:
3076 * @connection: A #GDBusConnection.
3077 * @sender: Sender name to match on (unique or well-known name) or %NULL to listen from all senders.
3078 * @interface_name: D-Bus interface name to match on or %NULL to match on all interfaces.
3079 * @member: D-Bus signal name to match on or %NULL to match on all signals.
3080 * @object_path: Object path to match on or %NULL to match on all object paths.
3081 * @arg0: Contents of first string argument to match on or %NULL to match on all kinds of arguments.
3082 * @flags: Flags describing how to subscribe to the signal (currently unused).
3083 * @callback: Callback to invoke when there is a signal matching the requested data.
3084 * @user_data: User data to pass to @callback.
3085 * @user_data_free_func: Function to free @user_data with when subscription is removed or %NULL.
3087 * Subscribes to signals on @connection and invokes @callback with a
3088 * whenever the signal is received. Note that @callback
3089 * will be invoked in the <link
3090 * linkend="g-main-context-push-thread-default">thread-default main
3091 * loop</link> of the thread you are calling this method from.
3093 * If @connection is not a message bus connection, @sender must be
3096 * If @sender is a well-known name note that @callback is invoked with
3097 * the unique name for the owner of @sender, not the well-known name
3098 * as one would expect. This is because the message bus rewrites the
3099 * name. As such, to avoid certain race conditions, users should be
3100 * tracking the name owner of the well-known name and use that when
3101 * processing the received signal.
3103 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3108 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3109 const gchar *sender,
3110 const gchar *interface_name,
3111 const gchar *member,
3112 const gchar *object_path,
3114 GDBusSignalFlags flags,
3115 GDBusSignalCallback callback,
3117 GDestroyNotify user_data_free_func)
3120 SignalData *signal_data;
3121 SignalSubscriber subscriber;
3122 GPtrArray *signal_data_array;
3123 const gchar *sender_unique_name;
3125 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3126 * an OOM condition. We might want to change that but that would involve making
3127 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3128 * handle that. And there's really no sensible way of handling this short of retrying
3129 * to add the match rule... and then there's the little thing that, hey, maybe there's
3130 * a reason the bus in an OOM condition.
3132 * Doable, but not really sure it's worth it...
3135 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3136 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3137 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3138 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3139 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3140 g_return_val_if_fail (callback != NULL, 0);
3142 CONNECTION_LOCK (connection);
3144 rule = args_to_rule (sender, interface_name, member, object_path, arg0);
3146 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3147 sender_unique_name = sender;
3149 sender_unique_name = "";
3151 subscriber.callback = callback;
3152 subscriber.user_data = user_data;
3153 subscriber.user_data_free_func = user_data_free_func;
3154 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3155 subscriber.context = g_main_context_get_thread_default ();
3156 if (subscriber.context != NULL)
3157 g_main_context_ref (subscriber.context);
3159 /* see if we've already have this rule */
3160 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3161 if (signal_data != NULL)
3163 g_array_append_val (signal_data->subscribers, subscriber);
3168 signal_data = g_new0 (SignalData, 1);
3169 signal_data->rule = rule;
3170 signal_data->sender = g_strdup (sender);
3171 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3172 signal_data->interface_name = g_strdup (interface_name);
3173 signal_data->member = g_strdup (member);
3174 signal_data->object_path = g_strdup (object_path);
3175 signal_data->arg0 = g_strdup (arg0);
3176 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3177 g_array_append_val (signal_data->subscribers, subscriber);
3179 g_hash_table_insert (connection->map_rule_to_signal_data,
3183 /* Add the match rule to the bus...
3185 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3186 * always send such messages to us.
3188 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3190 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3191 add_match_rule (connection, signal_data->rule);
3194 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3195 signal_data->sender_unique_name);
3196 if (signal_data_array == NULL)
3198 signal_data_array = g_ptr_array_new ();
3199 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3200 g_strdup (signal_data->sender_unique_name),
3203 g_ptr_array_add (signal_data_array, signal_data);
3206 g_hash_table_insert (connection->map_id_to_signal_data,
3207 GUINT_TO_POINTER (subscriber.id),
3210 CONNECTION_UNLOCK (connection);
3212 return subscriber.id;
3215 /* ---------------------------------------------------------------------------------------------------- */
3217 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3219 unsubscribe_id_internal (GDBusConnection *connection,
3220 guint subscription_id,
3221 GArray *out_removed_subscribers)
3223 SignalData *signal_data;
3224 GPtrArray *signal_data_array;
3227 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3228 GUINT_TO_POINTER (subscription_id));
3229 if (signal_data == NULL)
3231 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3235 for (n = 0; n < signal_data->subscribers->len; n++)
3237 SignalSubscriber *subscriber;
3239 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3240 if (subscriber->id != subscription_id)
3243 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3244 GUINT_TO_POINTER (subscription_id)));
3245 g_array_append_val (out_removed_subscribers, *subscriber);
3246 g_array_remove_index (signal_data->subscribers, n);
3248 if (signal_data->subscribers->len == 0)
3250 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3252 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3253 signal_data->sender_unique_name);
3254 g_warn_if_fail (signal_data_array != NULL);
3255 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3257 if (signal_data_array->len == 0)
3259 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3260 signal_data->sender_unique_name));
3263 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3264 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3266 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3267 if (!connection->closed && !connection->finalizing)
3268 remove_match_rule (connection, signal_data->rule);
3270 signal_data_free (signal_data);
3276 g_assert_not_reached ();
3283 * g_dbus_connection_signal_unsubscribe:
3284 * @connection: A #GDBusConnection.
3285 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3287 * Unsubscribes from signals.
3292 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3293 guint subscription_id)
3295 GArray *subscribers;
3298 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3300 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3302 CONNECTION_LOCK (connection);
3303 unsubscribe_id_internal (connection,
3306 CONNECTION_UNLOCK (connection);
3309 g_assert (subscribers->len == 0 || subscribers->len == 1);
3311 /* call GDestroyNotify without lock held */
3312 for (n = 0; n < subscribers->len; n++)
3314 SignalSubscriber *subscriber;
3315 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3316 call_destroy_notify (subscriber->context,
3317 subscriber->user_data_free_func,
3318 subscriber->user_data);
3319 if (subscriber->context != NULL)
3320 g_main_context_unref (subscriber->context);
3323 g_array_free (subscribers, TRUE);
3326 /* ---------------------------------------------------------------------------------------------------- */
3330 guint subscription_id;
3331 GDBusSignalCallback callback;
3333 GDBusMessage *message;
3334 GDBusConnection *connection;
3335 const gchar *sender;
3337 const gchar *interface;
3338 const gchar *member;
3341 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3345 emit_signal_instance_in_idle_cb (gpointer data)
3347 SignalInstance *signal_instance = data;
3348 GVariant *parameters;
3349 gboolean has_subscription;
3351 parameters = g_dbus_message_get_body (signal_instance->message);
3352 if (parameters == NULL)
3354 parameters = g_variant_new ("()");
3355 g_variant_ref_sink (parameters);
3359 g_variant_ref_sink (parameters);
3363 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3364 signal_instance->subscription_id,
3365 signal_instance->sender,
3366 signal_instance->path,
3367 signal_instance->interface,
3368 signal_instance->member,
3369 g_variant_print (parameters, TRUE));
3372 /* Careful here, don't do the callback if we no longer has the subscription */
3373 CONNECTION_LOCK (signal_instance->connection);
3374 has_subscription = FALSE;
3375 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3376 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3377 has_subscription = TRUE;
3378 CONNECTION_UNLOCK (signal_instance->connection);
3380 if (has_subscription)
3381 signal_instance->callback (signal_instance->connection,
3382 signal_instance->sender,
3383 signal_instance->path,
3384 signal_instance->interface,
3385 signal_instance->member,
3387 signal_instance->user_data);
3389 if (parameters != NULL)
3390 g_variant_unref (parameters);
3396 signal_instance_free (SignalInstance *signal_instance)
3398 g_object_unref (signal_instance->message);
3399 g_object_unref (signal_instance->connection);
3400 g_free (signal_instance);
3403 /* called in message handler thread WITH lock held */
3405 schedule_callbacks (GDBusConnection *connection,
3406 GPtrArray *signal_data_array,
3407 GDBusMessage *message,
3408 const gchar *sender)
3411 const gchar *interface;
3412 const gchar *member;
3421 interface = g_dbus_message_get_interface (message);
3422 member = g_dbus_message_get_member (message);
3423 path = g_dbus_message_get_path (message);
3424 arg0 = g_dbus_message_get_arg0 (message);
3427 g_print ("In schedule_callbacks:\n"
3429 " interface = `%s'\n"
3440 /* TODO: if this is slow, then we can change signal_data_array into
3441 * map_object_path_to_signal_data_array or something.
3443 for (n = 0; n < signal_data_array->len; n++)
3445 SignalData *signal_data = signal_data_array->pdata[n];
3447 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3450 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3453 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3456 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3459 for (m = 0; m < signal_data->subscribers->len; m++)
3461 SignalSubscriber *subscriber;
3462 GSource *idle_source;
3463 SignalInstance *signal_instance;
3465 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3467 signal_instance = g_new0 (SignalInstance, 1);
3468 signal_instance->subscription_id = subscriber->id;
3469 signal_instance->callback = subscriber->callback;
3470 signal_instance->user_data = subscriber->user_data;
3471 signal_instance->message = g_object_ref (message);
3472 signal_instance->connection = g_object_ref (connection);
3473 signal_instance->sender = sender;
3474 signal_instance->path = path;
3475 signal_instance->interface = interface;
3476 signal_instance->member = member;
3478 idle_source = g_idle_source_new ();
3479 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3480 g_source_set_callback (idle_source,
3481 emit_signal_instance_in_idle_cb,
3483 (GDestroyNotify) signal_instance_free);
3484 g_source_attach (idle_source, subscriber->context);
3485 g_source_unref (idle_source);
3490 /* called in message handler thread with lock held */
3492 distribute_signals (GDBusConnection *connection,
3493 GDBusMessage *message)
3495 GPtrArray *signal_data_array;
3496 const gchar *sender;
3498 sender = g_dbus_message_get_sender (message);
3500 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3502 _g_dbus_debug_print_lock ();
3503 g_print ("========================================================================\n"
3504 "GDBus-debug:Signal:\n"
3505 " <<<< RECEIVED SIGNAL %s.%s\n"
3507 " sent by name %s\n",
3508 g_dbus_message_get_interface (message),
3509 g_dbus_message_get_member (message),
3510 g_dbus_message_get_path (message),
3511 sender != NULL ? sender : "(none)");
3512 _g_dbus_debug_print_unlock ();
3515 /* collect subscribers that match on sender */
3518 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3519 if (signal_data_array != NULL)
3520 schedule_callbacks (connection, signal_data_array, message, sender);
3523 /* collect subscribers not matching on sender */
3524 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3525 if (signal_data_array != NULL)
3526 schedule_callbacks (connection, signal_data_array, message, sender);
3529 /* ---------------------------------------------------------------------------------------------------- */
3531 /* only called from finalize(), removes all subscriptions */
3533 purge_all_signal_subscriptions (GDBusConnection *connection)
3535 GHashTableIter iter;
3538 GArray *subscribers;
3541 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3542 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3543 while (g_hash_table_iter_next (&iter, &key, NULL))
3545 guint subscription_id = GPOINTER_TO_UINT (key);
3546 g_array_append_val (ids, subscription_id);
3549 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3550 for (n = 0; n < ids->len; n++)
3552 guint subscription_id = g_array_index (ids, guint, n);
3553 unsubscribe_id_internal (connection,
3557 g_array_free (ids, TRUE);
3559 /* call GDestroyNotify without lock held */
3560 for (n = 0; n < subscribers->len; n++)
3562 SignalSubscriber *subscriber;
3563 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3564 call_destroy_notify (subscriber->context,
3565 subscriber->user_data_free_func,
3566 subscriber->user_data);
3567 if (subscriber->context != NULL)
3568 g_main_context_unref (subscriber->context);
3571 g_array_free (subscribers, TRUE);
3574 /* ---------------------------------------------------------------------------------------------------- */
3576 static GDBusInterfaceVTable *
3577 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3579 /* Don't waste memory by copying padding - remember to update this
3580 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3582 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3586 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3591 /* ---------------------------------------------------------------------------------------------------- */
3593 static GDBusSubtreeVTable *
3594 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3596 /* Don't waste memory by copying padding - remember to update this
3597 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3599 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3603 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3608 /* ---------------------------------------------------------------------------------------------------- */
3610 struct ExportedObject
3613 GDBusConnection *connection;
3615 /* maps gchar* -> ExportedInterface* */
3616 GHashTable *map_if_name_to_ei;
3619 /* only called with lock held */
3621 exported_object_free (ExportedObject *eo)
3623 g_free (eo->object_path);
3624 g_hash_table_unref (eo->map_if_name_to_ei);
3633 gchar *interface_name;
3634 GDBusInterfaceVTable *vtable;
3635 GDBusInterfaceInfo *interface_info;
3637 GMainContext *context;
3639 GDestroyNotify user_data_free_func;
3640 } ExportedInterface;
3642 /* called with lock held */
3644 exported_interface_free (ExportedInterface *ei)
3646 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3648 call_destroy_notify (ei->context,
3649 ei->user_data_free_func,
3652 if (ei->context != NULL)
3653 g_main_context_unref (ei->context);
3655 g_free (ei->interface_name);
3656 _g_dbus_interface_vtable_free (ei->vtable);
3660 /* ---------------------------------------------------------------------------------------------------- */
3662 /* Convenience function to check if @registration_id (if not zero) or
3663 * @subtree_registration_id (if not zero) has been unregistered. If
3664 * so, returns %TRUE.
3666 * Caller must *not* hold lock.
3669 has_object_been_unregistered (GDBusConnection *connection,
3670 guint registration_id,
3671 guint subtree_registration_id)
3675 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3679 CONNECTION_LOCK (connection);
3680 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3681 GUINT_TO_POINTER (registration_id)) == NULL)
3685 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3686 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3690 CONNECTION_UNLOCK (connection);
3695 /* ---------------------------------------------------------------------------------------------------- */
3699 GDBusConnection *connection;
3700 GDBusMessage *message;
3702 const gchar *property_name;
3703 const GDBusInterfaceVTable *vtable;
3704 GDBusInterfaceInfo *interface_info;
3705 const GDBusPropertyInfo *property_info;
3706 guint registration_id;
3707 guint subtree_registration_id;
3711 property_data_free (PropertyData *data)
3713 g_object_unref (data->connection);
3714 g_object_unref (data->message);
3718 /* called in thread where object was registered - no locks held */
3720 invoke_get_property_in_idle_cb (gpointer _data)
3722 PropertyData *data = _data;
3725 GDBusMessage *reply;
3727 if (has_object_been_unregistered (data->connection,
3728 data->registration_id,
3729 data->subtree_registration_id))
3731 reply = g_dbus_message_new_method_error (data->message,
3732 "org.freedesktop.DBus.Error.UnknownMethod",
3733 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3734 g_dbus_message_get_path (data->message));
3735 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3736 g_object_unref (reply);
3741 value = data->vtable->get_property (data->connection,
3742 g_dbus_message_get_sender (data->message),
3743 g_dbus_message_get_path (data->message),
3744 data->interface_info->name,
3745 data->property_name,
3752 g_assert_no_error (error);
3754 if (g_variant_is_floating (value))
3755 g_variant_ref_sink (value);
3756 reply = g_dbus_message_new_method_reply (data->message);
3757 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3758 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3759 g_variant_unref (value);
3760 g_object_unref (reply);
3764 gchar *dbus_error_name;
3765 g_assert (error != NULL);
3766 dbus_error_name = g_dbus_error_encode_gerror (error);
3767 reply = g_dbus_message_new_method_error_literal (data->message,
3770 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3771 g_free (dbus_error_name);
3772 g_error_free (error);
3773 g_object_unref (reply);
3780 /* called in thread where object was registered - no locks held */
3782 invoke_set_property_in_idle_cb (gpointer _data)
3784 PropertyData *data = _data;
3786 GDBusMessage *reply;
3792 g_variant_get (g_dbus_message_get_body (data->message),
3798 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3799 * of the given value is wrong
3801 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3803 reply = g_dbus_message_new_method_error (data->message,
3804 "org.freedesktop.DBus.Error.InvalidArgs",
3805 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3806 data->property_info->name,
3807 data->property_info->signature,
3808 g_variant_get_type_string (value));
3812 if (!data->vtable->set_property (data->connection,
3813 g_dbus_message_get_sender (data->message),
3814 g_dbus_message_get_path (data->message),
3815 data->interface_info->name,
3816 data->property_name,
3821 gchar *dbus_error_name;
3822 g_assert (error != NULL);
3823 dbus_error_name = g_dbus_error_encode_gerror (error);
3824 reply = g_dbus_message_new_method_error_literal (data->message,
3827 g_free (dbus_error_name);
3828 g_error_free (error);
3832 reply = g_dbus_message_new_method_reply (data->message);
3836 g_assert (reply != NULL);
3837 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3838 g_object_unref (reply);
3839 g_variant_unref (value);
3844 /* called with lock held */
3846 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3847 GDBusMessage *message,
3848 guint registration_id,
3849 guint subtree_registration_id,
3851 GDBusInterfaceInfo *interface_info,
3852 const GDBusInterfaceVTable *vtable,
3853 GMainContext *main_context,
3857 const char *interface_name;
3858 const char *property_name;
3859 const GDBusPropertyInfo *property_info;
3860 GSource *idle_source;
3861 PropertyData *property_data;
3862 GDBusMessage *reply;
3867 g_variant_get (g_dbus_message_get_body (message),
3872 g_variant_get (g_dbus_message_get_body (message),
3881 if (vtable == NULL || vtable->get_property == NULL)
3886 if (vtable == NULL || vtable->set_property == NULL)
3890 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3892 property_info = NULL;
3894 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3895 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3896 if (property_info == NULL)
3898 reply = g_dbus_message_new_method_error (message,
3899 "org.freedesktop.DBus.Error.InvalidArgs",
3900 _("No such property `%s'"),
3902 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3903 g_object_unref (reply);
3908 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3910 reply = g_dbus_message_new_method_error (message,
3911 "org.freedesktop.DBus.Error.InvalidArgs",
3912 _("Property `%s' is not readable"),
3914 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3915 g_object_unref (reply);
3919 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3921 reply = g_dbus_message_new_method_error (message,
3922 "org.freedesktop.DBus.Error.InvalidArgs",
3923 _("Property `%s' is not writable"),
3925 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3926 g_object_unref (reply);
3931 /* ok, got the property info - call user code in an idle handler */
3932 property_data = g_new0 (PropertyData, 1);
3933 property_data->connection = g_object_ref (connection);
3934 property_data->message = g_object_ref (message);
3935 property_data->user_data = user_data;
3936 property_data->property_name = property_name;
3937 property_data->vtable = vtable;
3938 property_data->interface_info = interface_info;
3939 property_data->property_info = property_info;
3940 property_data->registration_id = registration_id;
3941 property_data->subtree_registration_id = subtree_registration_id;
3943 idle_source = g_idle_source_new ();
3944 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3945 g_source_set_callback (idle_source,
3946 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3948 (GDestroyNotify) property_data_free);
3949 g_source_attach (idle_source, main_context);
3950 g_source_unref (idle_source);
3958 /* called with lock held */
3960 handle_getset_property (GDBusConnection *connection,
3962 GDBusMessage *message,
3965 ExportedInterface *ei;
3967 const char *interface_name;
3968 const char *property_name;
3973 g_variant_get (g_dbus_message_get_body (message),
3978 g_variant_get (g_dbus_message_get_body (message),
3984 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
3985 * no such interface registered
3987 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
3990 GDBusMessage *reply;
3991 reply = g_dbus_message_new_method_error (message,
3992 "org.freedesktop.DBus.Error.InvalidArgs",
3993 _("No such interface `%s'"),
3995 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3996 g_object_unref (reply);
4001 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4014 /* ---------------------------------------------------------------------------------------------------- */
4018 GDBusConnection *connection;
4019 GDBusMessage *message;
4021 const GDBusInterfaceVTable *vtable;
4022 GDBusInterfaceInfo *interface_info;
4023 guint registration_id;
4024 guint subtree_registration_id;
4025 } PropertyGetAllData;
4028 property_get_all_data_free (PropertyData *data)
4030 g_object_unref (data->connection);
4031 g_object_unref (data->message);
4035 /* called in thread where object was registered - no locks held */
4037 invoke_get_all_properties_in_idle_cb (gpointer _data)
4039 PropertyGetAllData *data = _data;
4040 GVariantBuilder builder;
4042 GDBusMessage *reply;
4045 if (has_object_been_unregistered (data->connection,
4046 data->registration_id,
4047 data->subtree_registration_id))
4049 reply = g_dbus_message_new_method_error (data->message,
4050 "org.freedesktop.DBus.Error.UnknownMethod",
4051 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4052 g_dbus_message_get_path (data->message));
4053 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4054 g_object_unref (reply);
4060 /* TODO: Right now we never fail this call - we just omit values if
4061 * a get_property() call is failing.
4063 * We could fail the whole call if just a single get_property() call
4064 * returns an error. We need clarification in the D-Bus spec about this.
4066 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4067 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4068 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4070 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4073 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4076 value = data->vtable->get_property (data->connection,
4077 g_dbus_message_get_sender (data->message),
4078 g_dbus_message_get_path (data->message),
4079 data->interface_info->name,
4080 property_info->name,
4087 if (g_variant_is_floating (value))
4088 g_variant_ref_sink (value);
4089 g_variant_builder_add (&builder,
4091 property_info->name,
4093 g_variant_unref (value);
4095 g_variant_builder_close (&builder);
4097 reply = g_dbus_message_new_method_reply (data->message);
4098 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4099 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4100 g_object_unref (reply);
4106 /* called with lock held */
4108 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4109 GDBusMessage *message,
4110 guint registration_id,
4111 guint subtree_registration_id,
4112 GDBusInterfaceInfo *interface_info,
4113 const GDBusInterfaceVTable *vtable,
4114 GMainContext *main_context,
4118 const char *interface_name;
4119 GSource *idle_source;
4120 PropertyGetAllData *property_get_all_data;
4124 g_variant_get (g_dbus_message_get_body (message),
4128 if (vtable == NULL || vtable->get_property == NULL)
4131 /* ok, got the property info - call user in an idle handler */
4132 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4133 property_get_all_data->connection = g_object_ref (connection);
4134 property_get_all_data->message = g_object_ref (message);
4135 property_get_all_data->user_data = user_data;
4136 property_get_all_data->vtable = vtable;
4137 property_get_all_data->interface_info = interface_info;
4138 property_get_all_data->registration_id = registration_id;
4139 property_get_all_data->subtree_registration_id = subtree_registration_id;
4141 idle_source = g_idle_source_new ();
4142 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4143 g_source_set_callback (idle_source,
4144 invoke_get_all_properties_in_idle_cb,
4145 property_get_all_data,
4146 (GDestroyNotify) property_get_all_data_free);
4147 g_source_attach (idle_source, main_context);
4148 g_source_unref (idle_source);
4156 /* called with lock held */
4158 handle_get_all_properties (GDBusConnection *connection,
4160 GDBusMessage *message)
4162 ExportedInterface *ei;
4164 const char *interface_name;
4168 g_variant_get (g_dbus_message_get_body (message),
4172 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4173 * no such interface registered
4175 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4178 GDBusMessage *reply;
4179 reply = g_dbus_message_new_method_error (message,
4180 "org.freedesktop.DBus.Error.InvalidArgs",
4181 _("No such interface"),
4183 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4184 g_object_unref (reply);
4189 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4201 /* ---------------------------------------------------------------------------------------------------- */
4203 static const gchar introspect_header[] =
4204 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4205 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4206 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4209 static const gchar introspect_tail[] =
4212 static const gchar introspect_standard_interfaces[] =
4213 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4214 " <method name=\"Get\">\n"
4215 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4216 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4217 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4219 " <method name=\"GetAll\">\n"
4220 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4221 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4223 " <method name=\"Set\">\n"
4224 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4225 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4226 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4228 " <signal name=\"PropertiesChanged\">\n"
4229 " <arg type=\"s\" name=\"interface_name\"/>\n"
4230 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4231 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4234 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4235 " <method name=\"Introspect\">\n"
4236 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4239 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4240 " <method name=\"Ping\"/>\n"
4241 " <method name=\"GetMachineId\">\n"
4242 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4247 introspect_append_header (GString *s)
4249 g_string_append (s, introspect_header);
4253 introspect_append_standard_interfaces (GString *s)
4255 g_string_append (s, introspect_standard_interfaces);
4259 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4261 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4267 begin = object_path + path_len;
4268 end = strchr (begin, '/');
4270 s = g_strndup (begin, end - begin);
4272 s = g_strdup (begin);
4274 if (g_hash_table_lookup (set, s) == NULL)
4275 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4281 /* TODO: we want a nicer public interface for this */
4283 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4288 GHashTableIter hash_iter;
4289 const gchar *object_path;
4295 CONNECTION_ENSURE_LOCK (connection);
4297 path_len = strlen (path);
4301 set = g_hash_table_new (g_str_hash, g_str_equal);
4303 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4304 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4305 maybe_add_path (path, path_len, object_path, set);
4307 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4308 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4309 maybe_add_path (path, path_len, object_path, set);
4311 p = g_ptr_array_new ();
4312 keys = g_hash_table_get_keys (set);
4313 for (l = keys; l != NULL; l = l->next)
4314 g_ptr_array_add (p, l->data);
4315 g_hash_table_unref (set);
4318 g_ptr_array_add (p, NULL);
4319 ret = (gchar **) g_ptr_array_free (p, FALSE);
4324 g_dbus_connection_list_registered (GDBusConnection *connection,
4328 CONNECTION_LOCK (connection);
4329 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4330 CONNECTION_UNLOCK (connection);
4334 /* called in message handler thread with lock held */
4336 handle_introspect (GDBusConnection *connection,
4338 GDBusMessage *message)
4342 GDBusMessage *reply;
4343 GHashTableIter hash_iter;
4344 ExportedInterface *ei;
4347 /* first the header with the standard interfaces */
4348 s = g_string_sized_new (sizeof (introspect_header) +
4349 sizeof (introspect_standard_interfaces) +
4350 sizeof (introspect_tail));
4351 introspect_append_header (s);
4352 introspect_append_standard_interfaces (s);
4354 /* then include the registered interfaces */
4355 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4356 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4357 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4359 /* finally include nodes registered below us */
4360 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4361 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4362 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4363 g_strfreev (registered);
4364 g_string_append (s, introspect_tail);
4366 reply = g_dbus_message_new_method_reply (message);
4367 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4368 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4369 g_object_unref (reply);
4370 g_string_free (s, TRUE);
4375 /* called in thread where object was registered - no locks held */
4377 call_in_idle_cb (gpointer user_data)
4379 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4380 GDBusInterfaceVTable *vtable;
4381 guint registration_id;
4382 guint subtree_registration_id;
4384 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4385 g_assert (vtable != NULL && vtable->method_call != NULL);
4387 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4388 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4390 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4392 subtree_registration_id))
4394 GDBusMessage *reply;
4395 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4396 "org.freedesktop.DBus.Error.UnknownMethod",
4397 _("No such interface `%s' on object at path %s"),
4398 g_dbus_method_invocation_get_interface_name (invocation),
4399 g_dbus_method_invocation_get_object_path (invocation));
4400 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4401 g_object_unref (reply);
4405 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4406 g_dbus_method_invocation_get_sender (invocation),
4407 g_dbus_method_invocation_get_object_path (invocation),
4408 g_dbus_method_invocation_get_interface_name (invocation),
4409 g_dbus_method_invocation_get_method_name (invocation),
4410 g_dbus_method_invocation_get_parameters (invocation),
4411 g_object_ref (invocation),
4412 g_dbus_method_invocation_get_user_data (invocation));
4418 /* called in message handler thread with lock held */
4420 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4421 GDBusMessage *message,
4422 guint registration_id,
4423 guint subtree_registration_id,
4424 GDBusInterfaceInfo *interface_info,
4425 const GDBusInterfaceVTable *vtable,
4426 GMainContext *main_context,
4429 GDBusMethodInvocation *invocation;
4430 const GDBusMethodInfo *method_info;
4431 GDBusMessage *reply;
4432 GVariant *parameters;
4433 GSource *idle_source;
4435 GVariantType *in_type;
4439 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4440 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4442 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4443 * error to the caller
4445 if (method_info == NULL)
4447 reply = g_dbus_message_new_method_error (message,
4448 "org.freedesktop.DBus.Error.UnknownMethod",
4449 _("No such method `%s'"),
4450 g_dbus_message_get_member (message));
4451 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4452 g_object_unref (reply);
4457 parameters = g_dbus_message_get_body (message);
4458 if (parameters == NULL)
4460 parameters = g_variant_new ("()");
4461 g_variant_ref_sink (parameters);
4465 g_variant_ref (parameters);
4468 /* Check that the incoming args are of the right type - if they are not, return
4469 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4471 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4472 if (!g_variant_is_of_type (parameters, in_type))
4476 type_string = g_variant_type_dup_string (in_type);
4478 reply = g_dbus_message_new_method_error (message,
4479 "org.freedesktop.DBus.Error.InvalidArgs",
4480 _("Type of message, `%s', does not match expected type `%s'"),
4481 g_variant_get_type_string (parameters),
4483 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4484 g_variant_type_free (in_type);
4485 g_variant_unref (parameters);
4486 g_object_unref (reply);
4487 g_free (type_string);
4491 g_variant_type_free (in_type);
4493 /* schedule the call in idle */
4494 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4495 g_dbus_message_get_path (message),
4496 g_dbus_message_get_interface (message),
4497 g_dbus_message_get_member (message),
4503 g_variant_unref (parameters);
4505 /* TODO: would be nicer with a real MethodData like we already
4506 * have PropertyData and PropertyGetAllData... */
4507 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4508 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4509 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4511 idle_source = g_idle_source_new ();
4512 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4513 g_source_set_callback (idle_source,
4517 g_source_attach (idle_source, main_context);
4518 g_source_unref (idle_source);
4526 /* ---------------------------------------------------------------------------------------------------- */
4528 /* called in message handler thread with lock held */
4530 obj_message_func (GDBusConnection *connection,
4532 GDBusMessage *message)
4534 const gchar *interface_name;
4535 const gchar *member;
4536 const gchar *signature;
4541 interface_name = g_dbus_message_get_interface (message);
4542 member = g_dbus_message_get_member (message);
4543 signature = g_dbus_message_get_signature (message);
4545 /* see if we have an interface for handling this call */
4546 if (interface_name != NULL)
4548 ExportedInterface *ei;
4549 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4552 /* we do - invoke the handler in idle in the right thread */
4554 /* handle no vtable or handler being present */
4555 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4558 handled = validate_and_maybe_schedule_method_call (connection,
4570 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4571 g_strcmp0 (member, "Introspect") == 0 &&
4572 g_strcmp0 (signature, "") == 0)
4574 handled = handle_introspect (connection, eo, message);
4577 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4578 g_strcmp0 (member, "Get") == 0 &&
4579 g_strcmp0 (signature, "ss") == 0)
4581 handled = handle_getset_property (connection, eo, message, TRUE);
4584 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4585 g_strcmp0 (member, "Set") == 0 &&
4586 g_strcmp0 (signature, "ssv") == 0)
4588 handled = handle_getset_property (connection, eo, message, FALSE);
4591 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4592 g_strcmp0 (member, "GetAll") == 0 &&
4593 g_strcmp0 (signature, "s") == 0)
4595 handled = handle_get_all_properties (connection, eo, message);
4604 * g_dbus_connection_register_object:
4605 * @connection: A #GDBusConnection.
4606 * @object_path: The object path to register at.
4607 * @interface_info: Introspection data for the interface.
4608 * @vtable: A #GDBusInterfaceVTable to call into or %NULL.
4609 * @user_data: Data to pass to functions in @vtable.
4610 * @user_data_free_func: Function to call when the object path is unregistered.
4611 * @error: Return location for error or %NULL.
4613 * Registers callbacks for exported objects at @object_path with the
4614 * D-Bus interface that is described in @interface_info.
4616 * Calls to functions in @vtable (and @user_data_free_func) will
4617 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4618 * loop</link> of the thread you are calling this method from.
4620 * Note that all #GVariant values passed to functions in @vtable will match
4621 * the signature given in @interface_info - if a remote caller passes
4622 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4623 * is returned to the remote caller.
4625 * Additionally, if the remote caller attempts to invoke methods or
4626 * access properties not mentioned in @interface_info the
4627 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4628 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4629 * are returned to the caller.
4631 * It is considered a programming error if the
4632 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4633 * #GVariant of incorrect type.
4635 * If an existing callback is already registered at @object_path and
4636 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4638 * GDBus automatically implements the standard D-Bus interfaces
4639 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4640 * and org.freedesktop.Peer, so you don't have to implement those for
4641 * the objects you export. You <emphasis>can</emphasis> implement
4642 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4643 * and setting of properties asynchronously.
4645 * Note that the reference count on @interface_info will be
4646 * incremented by 1 (unless allocated statically, e.g. if the
4647 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4648 * as the object is exported. Also note that @vtable will be copied.
4650 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4652 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4653 * that can be used with g_dbus_connection_unregister_object() .
4658 g_dbus_connection_register_object (GDBusConnection *connection,
4659 const gchar *object_path,
4660 GDBusInterfaceInfo *interface_info,
4661 const GDBusInterfaceVTable *vtable,
4663 GDestroyNotify user_data_free_func,
4667 ExportedInterface *ei;
4670 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4671 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4672 g_return_val_if_fail (interface_info != NULL, 0);
4673 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4674 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4678 CONNECTION_LOCK (connection);
4680 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4683 eo = g_new0 (ExportedObject, 1);
4684 eo->object_path = g_strdup (object_path);
4685 eo->connection = connection;
4686 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4689 (GDestroyNotify) exported_interface_free);
4690 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4693 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4699 _("An object is already exported for the interface %s at %s"),
4700 interface_info->name,
4705 ei = g_new0 (ExportedInterface, 1);
4706 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4708 ei->user_data = user_data;
4709 ei->user_data_free_func = user_data_free_func;
4710 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4711 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4712 ei->interface_name = g_strdup (interface_info->name);
4713 ei->context = g_main_context_get_thread_default ();
4714 if (ei->context != NULL)
4715 g_main_context_ref (ei->context);
4717 g_hash_table_insert (eo->map_if_name_to_ei,
4718 (gpointer) ei->interface_name,
4720 g_hash_table_insert (connection->map_id_to_ei,
4721 GUINT_TO_POINTER (ei->id),
4727 CONNECTION_UNLOCK (connection);
4733 * g_dbus_connection_unregister_object:
4734 * @connection: A #GDBusConnection.
4735 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4737 * Unregisters an object.
4739 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4744 g_dbus_connection_unregister_object (GDBusConnection *connection,
4745 guint registration_id)
4747 ExportedInterface *ei;
4751 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4755 CONNECTION_LOCK (connection);
4757 ei = g_hash_table_lookup (connection->map_id_to_ei,
4758 GUINT_TO_POINTER (registration_id));
4764 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4765 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4766 /* unregister object path if we have no more exported interfaces */
4767 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4768 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4774 CONNECTION_UNLOCK (connection);
4779 /* ---------------------------------------------------------------------------------------------------- */
4782 * g_dbus_connection_emit_signal:
4783 * @connection: A #GDBusConnection.
4784 * @destination_bus_name: The unique bus name for the destination for the signal or %NULL to emit to all listeners.
4785 * @object_path: Path of remote object.
4786 * @interface_name: D-Bus interface to emit a signal on.
4787 * @signal_name: The name of the signal to emit.
4788 * @parameters: A #GVariant tuple with parameters for the signal or %NULL if not passing parameters.
4789 * @error: Return location for error or %NULL.
4793 * If the parameters GVariant is floating, it is consumed.
4795 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4797 * Returns: %TRUE unless @error is set.
4802 g_dbus_connection_emit_signal (GDBusConnection *connection,
4803 const gchar *destination_bus_name,
4804 const gchar *object_path,
4805 const gchar *interface_name,
4806 const gchar *signal_name,
4807 GVariant *parameters,
4810 GDBusMessage *message;
4816 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4817 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4818 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4819 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4820 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4821 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4823 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4825 _g_dbus_debug_print_lock ();
4826 g_print ("========================================================================\n"
4827 "GDBus-debug:Emission:\n"
4828 " >>>> SIGNAL EMISSION %s.%s()\n"
4830 " destination %s\n",
4831 interface_name, signal_name,
4833 destination_bus_name != NULL ? destination_bus_name : "(none)");
4834 _g_dbus_debug_print_unlock ();
4837 message = g_dbus_message_new_signal (object_path,
4841 if (destination_bus_name != NULL)
4842 g_dbus_message_set_header (message,
4843 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4844 g_variant_new_string (destination_bus_name));
4846 if (parameters != NULL)
4847 g_dbus_message_set_body (message, parameters);
4849 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4850 g_object_unref (message);
4856 add_call_flags (GDBusMessage *message,
4857 GDBusCallFlags flags)
4859 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4860 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4864 decode_method_reply (GDBusMessage *reply,
4865 const gchar *method_name,
4866 const GVariantType *reply_type,
4872 switch (g_dbus_message_get_message_type (reply))
4874 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4875 result = g_dbus_message_get_body (reply);
4878 result = g_variant_new ("()");
4879 g_variant_ref_sink (result);
4883 g_variant_ref (result);
4886 if (!g_variant_is_of_type (result, reply_type))
4888 gchar *type_string = g_variant_type_dup_string (reply_type);
4892 G_IO_ERROR_INVALID_ARGUMENT,
4893 _("Method `%s' returned type `%s', but expected `%s'"),
4894 method_name, g_variant_get_type_string (result), type_string);
4896 g_variant_unref (result);
4897 g_free (type_string);
4902 case G_DBUS_MESSAGE_TYPE_ERROR:
4903 g_dbus_message_to_gerror (reply, error);
4907 g_assert_not_reached ();
4917 GSimpleAsyncResult *simple;
4918 GVariantType *reply_type;
4919 gchar *method_name; /* for error message */
4924 g_dbus_connection_call_done (GObject *source,
4925 GAsyncResult *result,
4928 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4929 CallState *state = user_data;
4931 GDBusMessage *reply;
4935 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4939 if (G_UNLIKELY (_g_dbus_debug_call ()))
4941 _g_dbus_debug_print_lock ();
4942 g_print ("========================================================================\n"
4943 "GDBus-debug:Call:\n"
4944 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4950 g_print ("SUCCESS\n");
4954 g_print ("FAILED: %s\n",
4957 _g_dbus_debug_print_unlock ();
4963 value = decode_method_reply (reply, state->method_name,
4964 state->reply_type, &error);
4965 g_object_unref (reply);
4971 g_simple_async_result_take_error (state->simple, error);
4973 g_simple_async_result_set_op_res_gpointer (state->simple, value,
4974 (GDestroyNotify) g_variant_unref);
4976 g_simple_async_result_complete (state->simple);
4977 g_variant_type_free (state->reply_type);
4978 g_object_unref (state->simple);
4979 g_free (state->method_name);
4981 g_slice_free (CallState, state);
4985 * g_dbus_connection_call:
4986 * @connection: A #GDBusConnection.
4987 * @bus_name: A unique or well-known bus name or %NULL if @connection is not a message bus connection.
4988 * @object_path: Path of remote object.
4989 * @interface_name: D-Bus interface to invoke method on.
4990 * @method_name: The name of the method to invoke.
4991 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
4992 * @reply_type: The expected type of the reply, or %NULL.
4993 * @flags: Flags from the #GDBusCallFlags enumeration.
4994 * @timeout_msec: The timeout in milliseconds, -1 to use the default
4995 * timeout or %G_MAXINT for no timeout.
4996 * @cancellable: A #GCancellable or %NULL.
4997 * @callback: A #GAsyncReadyCallback to call when the request is satisfied or %NULL if you don't
4998 * care about the result of the method invocation.
4999 * @user_data: The data to pass to @callback.
5001 * Asynchronously invokes the @method_name method on the
5002 * @interface_name D-Bus interface on the remote object at
5003 * @object_path owned by @bus_name.
5005 * If @connection is closed then the operation will fail with
5006 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5007 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5008 * not compatible with the D-Bus protocol, the operation fails with
5009 * %G_IO_ERROR_INVALID_ARGUMENT.
5011 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5012 * error will be raised if it does not match. Said another way, if you give a @reply_type
5013 * then any non-%NULL return value will be of this type.
5015 * If the @parameters #GVariant is floating, it is consumed. This allows
5016 * convenient 'inline' use of g_variant_new(), e.g.:
5018 * g_dbus_connection_call (connection,
5019 * "org.freedesktop.StringThings",
5020 * "/org/freedesktop/StringThings",
5021 * "org.freedesktop.StringThings",
5023 * g_variant_new ("(ss)",
5027 * G_DBUS_CALL_FLAGS_NONE,
5030 * (GAsyncReadyCallback) two_strings_done,
5034 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5035 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5036 * of the thread you are calling this method from. You can then call
5037 * g_dbus_connection_call_finish() to get the result of the operation.
5038 * See g_dbus_connection_call_sync() for the synchronous version of this
5044 g_dbus_connection_call (GDBusConnection *connection,
5045 const gchar *bus_name,
5046 const gchar *object_path,
5047 const gchar *interface_name,
5048 const gchar *method_name,
5049 GVariant *parameters,
5050 const GVariantType *reply_type,
5051 GDBusCallFlags flags,
5053 GCancellable *cancellable,
5054 GAsyncReadyCallback callback,
5057 GDBusMessage *message;
5060 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5061 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5062 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5063 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5064 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5065 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5066 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5068 state = g_slice_new (CallState);
5069 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5070 callback, user_data,
5071 g_dbus_connection_call);
5072 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5074 if (reply_type == NULL)
5075 reply_type = G_VARIANT_TYPE_ANY;
5077 state->reply_type = g_variant_type_copy (reply_type);
5079 message = g_dbus_message_new_method_call (bus_name,
5083 add_call_flags (message, flags);
5084 if (parameters != NULL)
5085 g_dbus_message_set_body (message, parameters);
5087 g_dbus_connection_send_message_with_reply (connection,
5089 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5093 g_dbus_connection_call_done,
5096 if (G_UNLIKELY (_g_dbus_debug_call ()))
5098 _g_dbus_debug_print_lock ();
5099 g_print ("========================================================================\n"
5100 "GDBus-debug:Call:\n"
5101 " >>>> ASYNC %s.%s()\n"
5103 " owned by name %s (serial %d)\n",
5107 bus_name != NULL ? bus_name : "(none)",
5109 _g_dbus_debug_print_unlock ();
5112 if (message != NULL)
5113 g_object_unref (message);
5117 * g_dbus_connection_call_finish:
5118 * @connection: A #GDBusConnection.
5119 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5120 * @error: Return location for error or %NULL.
5122 * Finishes an operation started with g_dbus_connection_call().
5124 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5125 * return values. Free with g_variant_unref().
5130 g_dbus_connection_call_finish (GDBusConnection *connection,
5134 GSimpleAsyncResult *simple;
5136 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5137 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5138 g_dbus_connection_call), NULL);
5139 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5141 simple = G_SIMPLE_ASYNC_RESULT (res);
5143 if (g_simple_async_result_propagate_error (simple, error))
5146 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
5149 /* ---------------------------------------------------------------------------------------------------- */
5152 * g_dbus_connection_call_sync:
5153 * @connection: A #GDBusConnection.
5154 * @bus_name: A unique or well-known bus name.
5155 * @object_path: Path of remote object.
5156 * @interface_name: D-Bus interface to invoke method on.
5157 * @method_name: The name of the method to invoke.
5158 * @parameters: A #GVariant tuple with parameters for the method or %NULL if not passing parameters.
5159 * @reply_type: The expected type of the reply, or %NULL.
5160 * @flags: Flags from the #GDBusCallFlags enumeration.
5161 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5162 * timeout or %G_MAXINT for no timeout.
5163 * @cancellable: A #GCancellable or %NULL.
5164 * @error: Return location for error or %NULL.
5166 * Synchronously invokes the @method_name method on the
5167 * @interface_name D-Bus interface on the remote object at
5168 * @object_path owned by @bus_name.
5170 * If @connection is closed then the operation will fail with
5171 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5172 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5173 * contains a value not compatible with the D-Bus protocol, the operation
5174 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5176 * If @reply_type is non-%NULL then the reply will be checked for having
5177 * this type and an error will be raised if it does not match. Said
5178 * another way, if you give a @reply_type then any non-%NULL return
5179 * value will be of this type.
5181 * If the @parameters #GVariant is floating, it is consumed.
5182 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5184 * g_dbus_connection_call_sync (connection,
5185 * "org.freedesktop.StringThings",
5186 * "/org/freedesktop/StringThings",
5187 * "org.freedesktop.StringThings",
5189 * g_variant_new ("(ss)",
5193 * G_DBUS_CALL_FLAGS_NONE,
5199 * The calling thread is blocked until a reply is received. See
5200 * g_dbus_connection_call() for the asynchronous version of
5203 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5204 * return values. Free with g_variant_unref().
5209 g_dbus_connection_call_sync (GDBusConnection *connection,
5210 const gchar *bus_name,
5211 const gchar *object_path,
5212 const gchar *interface_name,
5213 const gchar *method_name,
5214 GVariant *parameters,
5215 const GVariantType *reply_type,
5216 GDBusCallFlags flags,
5218 GCancellable *cancellable,
5221 GDBusMessage *message;
5222 GDBusMessage *reply;
5224 GError *local_error;
5230 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5231 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5232 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5233 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5234 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5235 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5236 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5238 if (reply_type == NULL)
5239 reply_type = G_VARIANT_TYPE_ANY;
5241 message = g_dbus_message_new_method_call (bus_name,
5245 add_call_flags (message, flags);
5246 if (parameters != NULL)
5247 g_dbus_message_set_body (message, parameters);
5249 if (G_UNLIKELY (_g_dbus_debug_call ()))
5251 _g_dbus_debug_print_lock ();
5252 g_print ("========================================================================\n"
5253 "GDBus-debug:Call:\n"
5254 " >>>> SYNC %s.%s()\n"
5256 " owned by name %s\n",
5260 bus_name != NULL ? bus_name : "(none)");
5261 _g_dbus_debug_print_unlock ();
5265 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5267 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5269 NULL, /* volatile guint32 *out_serial */
5273 if (G_UNLIKELY (_g_dbus_debug_call ()))
5275 _g_dbus_debug_print_lock ();
5276 g_print ("========================================================================\n"
5277 "GDBus-debug:Call:\n"
5278 " <<<< SYNC COMPLETE %s.%s()\n"
5284 g_print ("SUCCESS\n");
5288 g_print ("FAILED: %s\n",
5289 local_error->message);
5291 _g_dbus_debug_print_unlock ();
5297 *error = local_error;
5299 g_error_free (local_error);
5303 result = decode_method_reply (reply, method_name, reply_type, error);
5306 if (message != NULL)
5307 g_object_unref (message);
5309 g_object_unref (reply);
5314 /* ---------------------------------------------------------------------------------------------------- */
5316 struct ExportedSubtree
5320 GDBusConnection *connection;
5321 GDBusSubtreeVTable *vtable;
5322 GDBusSubtreeFlags flags;
5324 GMainContext *context;
5326 GDestroyNotify user_data_free_func;
5330 exported_subtree_free (ExportedSubtree *es)
5332 call_destroy_notify (es->context,
5333 es->user_data_free_func,
5336 if (es->context != NULL)
5337 g_main_context_unref (es->context);
5339 _g_dbus_subtree_vtable_free (es->vtable);
5340 g_free (es->object_path);
5344 /* called without lock held */
5346 handle_subtree_introspect (GDBusConnection *connection,
5347 ExportedSubtree *es,
5348 GDBusMessage *message)
5352 GDBusMessage *reply;
5355 const gchar *sender;
5356 const gchar *requested_object_path;
5357 const gchar *requested_node;
5358 GDBusInterfaceInfo **interfaces;
5360 gchar **subnode_paths;
5364 requested_object_path = g_dbus_message_get_path (message);
5365 sender = g_dbus_message_get_sender (message);
5366 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5368 s = g_string_new (NULL);
5369 introspect_append_header (s);
5371 /* Strictly we don't need the children in dynamic mode, but we avoid the
5372 * conditionals to preserve code clarity
5374 children = es->vtable->enumerate (es->connection,
5381 requested_node = strrchr (requested_object_path, '/') + 1;
5383 /* Assert existence of object if we are not dynamic */
5384 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5385 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5390 requested_node = NULL;
5393 interfaces = es->vtable->introspect (es->connection,
5398 if (interfaces != NULL)
5400 introspect_append_standard_interfaces (s);
5402 for (n = 0; interfaces[n] != NULL; n++)
5404 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5405 g_dbus_interface_info_unref (interfaces[n]);
5407 g_free (interfaces);
5410 /* then include <node> entries from the Subtree for the root */
5413 for (n = 0; children != NULL && children[n] != NULL; n++)
5414 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5417 /* finally include nodes registered below us */
5418 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5419 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5420 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5421 g_strfreev (subnode_paths);
5423 g_string_append (s, "</node>\n");
5425 reply = g_dbus_message_new_method_reply (message);
5426 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5427 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5428 g_object_unref (reply);
5433 g_string_free (s, TRUE);
5434 g_strfreev (children);
5438 /* called without lock held */
5440 handle_subtree_method_invocation (GDBusConnection *connection,
5441 ExportedSubtree *es,
5442 GDBusMessage *message)
5445 const gchar *sender;
5446 const gchar *interface_name;
5447 const gchar *member;
5448 const gchar *signature;
5449 const gchar *requested_object_path;
5450 const gchar *requested_node;
5452 GDBusInterfaceInfo *interface_info;
5453 const GDBusInterfaceVTable *interface_vtable;
5454 gpointer interface_user_data;
5456 GDBusInterfaceInfo **interfaces;
5457 gboolean is_property_get;
5458 gboolean is_property_set;
5459 gboolean is_property_get_all;
5464 requested_object_path = g_dbus_message_get_path (message);
5465 sender = g_dbus_message_get_sender (message);
5466 interface_name = g_dbus_message_get_interface (message);
5467 member = g_dbus_message_get_member (message);
5468 signature = g_dbus_message_get_signature (message);
5469 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5471 is_property_get = FALSE;
5472 is_property_set = FALSE;
5473 is_property_get_all = FALSE;
5474 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5476 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5477 is_property_get = TRUE;
5478 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5479 is_property_set = TRUE;
5480 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5481 is_property_get_all = TRUE;
5486 requested_node = strrchr (requested_object_path, '/') + 1;
5488 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5490 /* We don't want to dispatch to unenumerated
5491 * nodes, so ensure that the child exists.
5496 children = es->vtable->enumerate (es->connection,
5501 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5502 g_strfreev (children);
5510 requested_node = NULL;
5513 /* get introspection data for the node */
5514 interfaces = es->vtable->introspect (es->connection,
5516 requested_object_path,
5520 if (interfaces == NULL)
5523 interface_info = NULL;
5524 for (n = 0; interfaces[n] != NULL; n++)
5526 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5527 interface_info = interfaces[n];
5530 /* dispatch the call if the user wants to handle it */
5531 if (interface_info != NULL)
5533 /* figure out where to dispatch the method call */
5534 interface_user_data = NULL;
5535 interface_vtable = es->vtable->dispatch (es->connection,
5540 &interface_user_data,
5542 if (interface_vtable == NULL)
5545 CONNECTION_LOCK (connection);
5546 handled = validate_and_maybe_schedule_method_call (es->connection,
5553 interface_user_data);
5554 CONNECTION_UNLOCK (connection);
5556 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5557 else if (is_property_get || is_property_set || is_property_get_all)
5559 if (is_property_get)
5560 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5561 else if (is_property_set)
5562 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5563 else if (is_property_get_all)
5564 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5566 g_assert_not_reached ();
5568 /* see if the object supports this interface at all */
5569 for (n = 0; interfaces[n] != NULL; n++)
5571 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5572 interface_info = interfaces[n];
5575 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5576 * claims it won't support the interface
5578 if (interface_info == NULL)
5580 GDBusMessage *reply;
5581 reply = g_dbus_message_new_method_error (message,
5582 "org.freedesktop.DBus.Error.InvalidArgs",
5583 _("No such interface `%s'"),
5585 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5586 g_object_unref (reply);
5591 /* figure out where to dispatch the property get/set/getall calls */
5592 interface_user_data = NULL;
5593 interface_vtable = es->vtable->dispatch (es->connection,
5598 &interface_user_data,
5600 if (interface_vtable == NULL)
5602 g_warning ("The subtree introspection function indicates that '%s' "
5603 "is a valid interface name, but calling the dispatch "
5604 "function on that interface gave us NULL", interface_name);
5608 if (is_property_get || is_property_set)
5610 CONNECTION_LOCK (connection);
5611 handled = validate_and_maybe_schedule_property_getset (es->connection,
5619 interface_user_data);
5620 CONNECTION_UNLOCK (connection);
5622 else if (is_property_get_all)
5624 CONNECTION_LOCK (connection);
5625 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5632 interface_user_data);
5633 CONNECTION_UNLOCK (connection);
5638 if (interfaces != NULL)
5640 for (n = 0; interfaces[n] != NULL; n++)
5641 g_dbus_interface_info_unref (interfaces[n]);
5642 g_free (interfaces);
5650 GDBusMessage *message;
5651 ExportedSubtree *es;
5652 } SubtreeDeferredData;
5655 subtree_deferred_data_free (SubtreeDeferredData *data)
5657 g_object_unref (data->message);
5661 /* called without lock held in the thread where the caller registered the subtree */
5663 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5665 SubtreeDeferredData *data = _data;
5670 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5671 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5672 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5673 handled = handle_subtree_introspect (data->es->connection,
5677 handled = handle_subtree_method_invocation (data->es->connection,
5683 CONNECTION_LOCK (data->es->connection);
5684 handled = handle_generic_unlocked (data->es->connection, data->message);
5685 CONNECTION_UNLOCK (data->es->connection);
5688 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5691 GDBusMessage *reply;
5692 reply = g_dbus_message_new_method_error (data->message,
5693 "org.freedesktop.DBus.Error.UnknownMethod",
5694 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5695 g_dbus_message_get_member (data->message),
5696 g_dbus_message_get_interface (data->message),
5697 g_dbus_message_get_signature (data->message));
5698 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5699 g_object_unref (reply);
5705 /* called in message handler thread with lock held */
5707 subtree_message_func (GDBusConnection *connection,
5708 ExportedSubtree *es,
5709 GDBusMessage *message)
5711 GSource *idle_source;
5712 SubtreeDeferredData *data;
5714 data = g_new0 (SubtreeDeferredData, 1);
5715 data->message = g_object_ref (message);
5718 /* defer this call to an idle handler in the right thread */
5719 idle_source = g_idle_source_new ();
5720 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5721 g_source_set_callback (idle_source,
5722 process_subtree_vtable_message_in_idle_cb,
5724 (GDestroyNotify) subtree_deferred_data_free);
5725 g_source_attach (idle_source, es->context);
5726 g_source_unref (idle_source);
5728 /* since we own the entire subtree, handlers for objects not in the subtree have been
5729 * tried already by libdbus-1 - so we just need to ensure that we're always going
5730 * to reply to the message
5736 * g_dbus_connection_register_subtree:
5737 * @connection: A #GDBusConnection.
5738 * @object_path: The object path to register the subtree at.
5739 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5740 * @flags: Flags used to fine tune the behavior of the subtree.
5741 * @user_data: Data to pass to functions in @vtable.
5742 * @user_data_free_func: Function to call when the subtree is unregistered.
5743 * @error: Return location for error or %NULL.
5745 * Registers a whole subtree of <quote>dynamic</quote> objects.
5747 * The @enumerate and @introspection functions in @vtable are used to
5748 * convey, to remote callers, what nodes exist in the subtree rooted
5751 * When handling remote calls into any node in the subtree, first the
5752 * @enumerate function is used to check if the node exists. If the node exists
5753 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5754 * the @introspection function is used to check if the node supports the
5755 * requested method. If so, the @dispatch function is used to determine
5756 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5757 * #gpointer will be used to call into the interface vtable for processing
5760 * All calls into user-provided code will be invoked in the <link
5761 * linkend="g-main-context-push-thread-default">thread-default main
5762 * loop</link> of the thread you are calling this method from.
5764 * If an existing subtree is already registered at @object_path or
5765 * then @error is set to #G_IO_ERROR_EXISTS.
5767 * Note that it is valid to register regular objects (using
5768 * g_dbus_connection_register_object()) in a subtree registered with
5769 * g_dbus_connection_register_subtree() - if so, the subtree handler
5770 * is tried as the last resort. One way to think about a subtree
5771 * handler is to consider it a <quote>fallback handler</quote>
5772 * for object paths not registered via g_dbus_connection_register_object()
5773 * or other bindings.
5775 * Note that @vtable will be copied so you cannot change it after
5778 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5780 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5781 * that can be used with g_dbus_connection_unregister_subtree() .
5786 g_dbus_connection_register_subtree (GDBusConnection *connection,
5787 const gchar *object_path,
5788 const GDBusSubtreeVTable *vtable,
5789 GDBusSubtreeFlags flags,
5791 GDestroyNotify user_data_free_func,
5795 ExportedSubtree *es;
5797 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5798 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5799 g_return_val_if_fail (vtable != NULL, 0);
5800 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5804 CONNECTION_LOCK (connection);
5806 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5812 _("A subtree is already exported for %s"),
5817 es = g_new0 (ExportedSubtree, 1);
5818 es->object_path = g_strdup (object_path);
5819 es->connection = connection;
5821 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5823 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5824 es->user_data = user_data;
5825 es->user_data_free_func = user_data_free_func;
5826 es->context = g_main_context_get_thread_default ();
5827 if (es->context != NULL)
5828 g_main_context_ref (es->context);
5830 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5831 g_hash_table_insert (connection->map_id_to_es,
5832 GUINT_TO_POINTER (es->id),
5838 CONNECTION_UNLOCK (connection);
5843 /* ---------------------------------------------------------------------------------------------------- */
5846 * g_dbus_connection_unregister_subtree:
5847 * @connection: A #GDBusConnection.
5848 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5850 * Unregisters a subtree.
5852 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5857 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5858 guint registration_id)
5860 ExportedSubtree *es;
5863 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5867 CONNECTION_LOCK (connection);
5869 es = g_hash_table_lookup (connection->map_id_to_es,
5870 GUINT_TO_POINTER (registration_id));
5874 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5875 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5880 CONNECTION_UNLOCK (connection);
5885 /* ---------------------------------------------------------------------------------------------------- */
5887 /* must be called with lock held */
5889 handle_generic_ping_unlocked (GDBusConnection *connection,
5890 const gchar *object_path,
5891 GDBusMessage *message)
5893 GDBusMessage *reply;
5894 reply = g_dbus_message_new_method_reply (message);
5895 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5896 g_object_unref (reply);
5899 /* must be called with lock held */
5901 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5902 const gchar *object_path,
5903 GDBusMessage *message)
5905 GDBusMessage *reply;
5908 if (connection->machine_id == NULL)
5913 connection->machine_id = _g_dbus_get_machine_id (&error);
5914 if (connection->machine_id == NULL)
5916 reply = g_dbus_message_new_method_error_literal (message,
5917 "org.freedesktop.DBus.Error.Failed",
5919 g_error_free (error);
5925 reply = g_dbus_message_new_method_reply (message);
5926 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5928 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5929 g_object_unref (reply);
5932 /* must be called with lock held */
5934 handle_generic_introspect_unlocked (GDBusConnection *connection,
5935 const gchar *object_path,
5936 GDBusMessage *message)
5941 GDBusMessage *reply;
5943 /* first the header */
5944 s = g_string_new (NULL);
5945 introspect_append_header (s);
5947 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
5948 for (n = 0; registered != NULL && registered[n] != NULL; n++)
5949 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
5950 g_strfreev (registered);
5951 g_string_append (s, "</node>\n");
5953 reply = g_dbus_message_new_method_reply (message);
5954 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5955 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5956 g_object_unref (reply);
5957 g_string_free (s, TRUE);
5960 /* must be called with lock held */
5962 handle_generic_unlocked (GDBusConnection *connection,
5963 GDBusMessage *message)
5966 const gchar *interface_name;
5967 const gchar *member;
5968 const gchar *signature;
5971 CONNECTION_ENSURE_LOCK (connection);
5975 interface_name = g_dbus_message_get_interface (message);
5976 member = g_dbus_message_get_member (message);
5977 signature = g_dbus_message_get_signature (message);
5978 path = g_dbus_message_get_path (message);
5980 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5981 g_strcmp0 (member, "Introspect") == 0 &&
5982 g_strcmp0 (signature, "") == 0)
5984 handle_generic_introspect_unlocked (connection, path, message);
5987 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5988 g_strcmp0 (member, "Ping") == 0 &&
5989 g_strcmp0 (signature, "") == 0)
5991 handle_generic_ping_unlocked (connection, path, message);
5994 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
5995 g_strcmp0 (member, "GetMachineId") == 0 &&
5996 g_strcmp0 (signature, "") == 0)
5998 handle_generic_get_machine_id_unlocked (connection, path, message);
6005 /* ---------------------------------------------------------------------------------------------------- */
6007 /* called in message handler thread with lock held */
6009 distribute_method_call (GDBusConnection *connection,
6010 GDBusMessage *message)
6012 GDBusMessage *reply;
6014 ExportedSubtree *es;
6015 const gchar *object_path;
6016 const gchar *interface_name;
6017 const gchar *member;
6018 const gchar *signature;
6020 gchar *subtree_path;
6023 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6025 interface_name = g_dbus_message_get_interface (message);
6026 member = g_dbus_message_get_member (message);
6027 signature = g_dbus_message_get_signature (message);
6028 path = g_dbus_message_get_path (message);
6029 subtree_path = g_strdup (path);
6030 needle = strrchr (subtree_path, '/');
6031 if (needle != NULL && needle != subtree_path)
6037 g_free (subtree_path);
6038 subtree_path = NULL;
6042 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6044 _g_dbus_debug_print_lock ();
6045 g_print ("========================================================================\n"
6046 "GDBus-debug:Incoming:\n"
6047 " <<<< METHOD INVOCATION %s.%s()\n"
6049 " invoked by name %s\n"
6051 interface_name, member,
6053 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6054 g_dbus_message_get_serial (message));
6055 _g_dbus_debug_print_unlock ();
6059 g_debug ("interface = `%s'", interface_name);
6060 g_debug ("member = `%s'", member);
6061 g_debug ("signature = `%s'", signature);
6062 g_debug ("path = `%s'", path);
6063 g_debug ("subtree_path = `%s'", subtree_path != NULL ? subtree_path : "N/A");
6066 object_path = g_dbus_message_get_path (message);
6067 g_assert (object_path != NULL);
6069 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6072 if (obj_message_func (connection, eo, message))
6076 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6079 if (subtree_message_func (connection, es, message))
6083 if (subtree_path != NULL)
6085 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6088 if (subtree_message_func (connection, es, message))
6093 if (handle_generic_unlocked (connection, message))
6096 /* if we end up here, the message has not been not handled - so return an error saying this */
6097 reply = g_dbus_message_new_method_error (message,
6098 "org.freedesktop.DBus.Error.UnknownMethod",
6099 _("No such interface `%s' on object at path %s"),
6102 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6103 g_object_unref (reply);
6106 g_free (subtree_path);
6109 /* ---------------------------------------------------------------------------------------------------- */
6111 static GDBusConnection **
6112 message_bus_get_singleton (GBusType bus_type,
6115 GDBusConnection **ret;
6116 const gchar *starter_bus;
6122 case G_BUS_TYPE_SESSION:
6123 ret = &the_session_bus;
6126 case G_BUS_TYPE_SYSTEM:
6127 ret = &the_system_bus;
6130 case G_BUS_TYPE_STARTER:
6131 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6132 if (g_strcmp0 (starter_bus, "session") == 0)
6134 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6137 else if (g_strcmp0 (starter_bus, "system") == 0)
6139 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6144 if (starter_bus != NULL)
6148 G_IO_ERROR_INVALID_ARGUMENT,
6149 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6150 " - unknown value `%s'"),
6155 g_set_error_literal (error,
6157 G_IO_ERROR_INVALID_ARGUMENT,
6158 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6159 "variable is not set"));
6165 g_assert_not_reached ();
6173 static GDBusConnection *
6174 get_uninitialized_connection (GBusType bus_type,
6175 GCancellable *cancellable,
6178 GDBusConnection **singleton;
6179 GDBusConnection *ret;
6183 G_LOCK (message_bus_lock);
6184 singleton = message_bus_get_singleton (bus_type, error);
6185 if (singleton == NULL)
6188 if (*singleton == NULL)
6191 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6192 if (address == NULL)
6194 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6196 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6197 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6198 "exit-on-close", TRUE,
6204 ret = g_object_ref (*singleton);
6207 g_assert (ret != NULL);
6210 G_UNLOCK (message_bus_lock);
6216 * @bus_type: A #GBusType.
6217 * @cancellable: A #GCancellable or %NULL.
6218 * @error: Return location for error or %NULL.
6220 * Synchronously connects to the message bus specified by @bus_type.
6221 * Note that the returned object may shared with other callers,
6222 * e.g. if two separate parts of a process calls this function with
6223 * the same @bus_type, they will share the same object.
6225 * This is a synchronous failable function. See g_bus_get() and
6226 * g_bus_get_finish() for the asynchronous version.
6228 * The returned object is a singleton, that is, shared with other
6229 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6230 * event that you need a private message bus connection, use
6231 * g_dbus_address_get_for_bus_sync() and
6232 * g_dbus_connection_new_for_address().
6234 * Note that the returned #GDBusConnection object will (usually) have
6235 * the #GDBusConnection:exit-on-close property set to %TRUE.
6237 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6242 g_bus_get_sync (GBusType bus_type,
6243 GCancellable *cancellable,
6246 GDBusConnection *connection;
6248 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6250 connection = get_uninitialized_connection (bus_type, cancellable, error);
6251 if (connection == NULL)
6254 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6256 g_object_unref (connection);
6265 bus_get_async_initable_cb (GObject *source_object,
6269 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6273 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6277 g_assert (error != NULL);
6278 g_simple_async_result_take_error (simple, error);
6279 g_object_unref (source_object);
6283 g_simple_async_result_set_op_res_gpointer (simple,
6287 g_simple_async_result_complete_in_idle (simple);
6288 g_object_unref (simple);
6293 * @bus_type: A #GBusType.
6294 * @cancellable: A #GCancellable or %NULL.
6295 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6296 * @user_data: The data to pass to @callback.
6298 * Asynchronously connects to the message bus specified by @bus_type.
6300 * When the operation is finished, @callback will be invoked. You can
6301 * then call g_bus_get_finish() to get the result of the operation.
6303 * This is a asynchronous failable function. See g_bus_get_sync() for
6304 * the synchronous version.
6309 g_bus_get (GBusType bus_type,
6310 GCancellable *cancellable,
6311 GAsyncReadyCallback callback,
6314 GDBusConnection *connection;
6315 GSimpleAsyncResult *simple;
6318 simple = g_simple_async_result_new (NULL,
6324 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6325 if (connection == NULL)
6327 g_assert (error != NULL);
6328 g_simple_async_result_take_error (simple, error);
6329 g_simple_async_result_complete_in_idle (simple);
6330 g_object_unref (simple);
6334 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6337 bus_get_async_initable_cb,
6344 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6345 * @error: Return location for error or %NULL.
6347 * Finishes an operation started with g_bus_get().
6349 * The returned object is a singleton, that is, shared with other
6350 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6351 * event that you need a private message bus connection, use
6352 * g_dbus_address_get_for_bus() and
6353 * g_dbus_connection_new_for_address().
6355 * Note that the returned #GDBusConnection object will (usually) have
6356 * the #GDBusConnection:exit-on-close property set to %TRUE.
6358 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6363 g_bus_get_finish (GAsyncResult *res,
6366 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6368 GDBusConnection *ret;
6370 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6372 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6376 if (g_simple_async_result_propagate_error (simple, error))
6379 object = g_simple_async_result_get_op_res_gpointer (simple);
6380 g_assert (object != NULL);
6381 ret = g_object_ref (G_DBUS_CONNECTION (object));
6387 /* ---------------------------------------------------------------------------------------------------- */