1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily 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 "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
153 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
155 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
157 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
160 /* ---------------------------------------------------------------------------------------------------- */
162 typedef struct _GDBusConnectionClass GDBusConnectionClass;
165 * GDBusConnectionClass:
166 * @closed: Signal class handler for the #GDBusConnection::closed signal.
168 * Class structure for #GDBusConnection.
172 struct _GDBusConnectionClass
175 GObjectClass parent_class;
179 void (*closed) (GDBusConnection *connection,
180 gboolean remote_peer_vanished,
184 G_LOCK_DEFINE_STATIC (message_bus_lock);
186 static GDBusConnection *the_session_bus = NULL;
187 static GDBusConnection *the_system_bus = NULL;
189 /* ---------------------------------------------------------------------------------------------------- */
193 GDestroyNotify callback;
195 GMainContext *context;
196 } CallDestroyNotifyData;
199 call_destroy_notify_data_in_idle (gpointer user_data)
201 CallDestroyNotifyData *data = user_data;
202 data->callback (data->user_data);
207 call_destroy_notify_data_free (CallDestroyNotifyData *data)
209 if (data->context != NULL)
210 g_main_context_unref (data->context);
215 * call_destroy_notify: <internal>
216 * @context: A #GMainContext or %NULL.
217 * @callback: A #GDestroyNotify or %NULL.
218 * @user_data: Data to pass to @callback.
220 * Schedules @callback to run in @context.
223 call_destroy_notify (GMainContext *context,
224 GDestroyNotify callback,
227 if (callback == NULL)
230 if (context == g_main_context_get_thread_default ())
232 callback (user_data);
236 GSource *idle_source;
237 CallDestroyNotifyData *data;
239 data = g_new0 (CallDestroyNotifyData, 1);
240 data->callback = callback;
241 data->user_data = user_data;
242 data->context = context;
243 if (data->context != NULL)
244 g_main_context_ref (data->context);
246 idle_source = g_idle_source_new ();
247 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
248 g_source_set_callback (idle_source,
249 call_destroy_notify_data_in_idle,
251 (GDestroyNotify) call_destroy_notify_data_free);
252 g_source_attach (idle_source, data->context);
253 g_source_unref (idle_source);
260 /* ---------------------------------------------------------------------------------------------------- */
263 _g_strv_has_string (const gchar* const *haystack,
268 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
270 if (g_strcmp0 (haystack[n], needle) == 0)
276 /* ---------------------------------------------------------------------------------------------------- */
279 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
281 // TODO: for some reason this doesn't work on Windows
282 #define CONNECTION_ENSURE_LOCK(obj) do { \
283 if (G_UNLIKELY (g_mutex_trylock((obj)->lock))) \
285 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
286 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
291 #define CONNECTION_LOCK(obj) do { \
292 g_mutex_lock ((obj)->lock); \
295 #define CONNECTION_UNLOCK(obj) do { \
296 g_mutex_unlock ((obj)->lock); \
302 * The #GDBusConnection structure contains only private data and
303 * should only be accessed using the provided API.
307 struct _GDBusConnection
310 GObject parent_instance;
312 /* ------------------------------------------------------------------------ */
313 /* -- General object state ------------------------------------------------ */
314 /* ------------------------------------------------------------------------ */
316 /* object-wide lock */
319 /* A lock used in the init() method of the GInitable interface - see comments
320 * in initable_init() for why a separate lock is needed
324 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
325 * someone calls org.freedesktop.DBus.GetMachineId()
329 /* The underlying stream used for communication */
332 /* The object used for authentication (if any) */
335 /* Set to TRUE if the connection has been closed */
338 /* Last serial used */
341 /* The object used to send/receive message */
344 /* If connected to a message bus, this contains the unique name assigned to
345 * us by the bus (e.g. ":1.42")
347 gchar *bus_unique_name;
349 /* The GUID returned by the other side if we authenticed as a client or
350 * the GUID to use if authenticating as a server
354 /* set to TRUE exactly when initable_init() has finished running */
355 gboolean is_initialized;
357 /* If the connection could not be established during initable_init(), this GError will set */
358 GError *initialization_error;
360 /* The result of g_main_context_get_thread_default() when the object
361 * was created (the GObject _init() function) - this is used for delivery
362 * of the :closed GObject signal.
364 GMainContext *main_context_at_construction;
366 /* construct properties */
368 GDBusConnectionFlags flags;
370 /* Map used for managing method replies */
371 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
373 /* Maps used for managing signal subscription */
374 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
375 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
376 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
378 /* Maps used for managing exported objects and subtrees */
379 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
380 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
381 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
382 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
384 /* Structure used for message filters */
387 /* Whether to exit on close */
388 gboolean exit_on_close;
390 /* Capabilities negotiated during authentication */
391 GDBusCapabilityFlags capabilities;
393 GDBusAuthObserver *authentication_observer;
394 GCredentials *credentials;
396 /* set to TRUE when finalizing */
400 typedef struct ExportedObject ExportedObject;
401 static void exported_object_free (ExportedObject *eo);
403 typedef struct ExportedSubtree ExportedSubtree;
404 static void exported_subtree_free (ExportedSubtree *es);
422 PROP_CAPABILITY_FLAGS,
423 PROP_AUTHENTICATION_OBSERVER,
426 static void distribute_signals (GDBusConnection *connection,
427 GDBusMessage *message);
429 static void distribute_method_call (GDBusConnection *connection,
430 GDBusMessage *message);
432 static gboolean handle_generic_unlocked (GDBusConnection *connection,
433 GDBusMessage *message);
436 static void purge_all_signal_subscriptions (GDBusConnection *connection);
437 static void purge_all_filters (GDBusConnection *connection);
439 #define _G_ENSURE_LOCK(name) do { \
440 if (G_UNLIKELY (G_TRYLOCK(name))) \
442 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
443 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
447 static guint signals[LAST_SIGNAL] = { 0 };
449 static void initable_iface_init (GInitableIface *initable_iface);
450 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
452 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
453 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
454 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
457 static GHashTable *alive_connections = NULL;
460 g_dbus_connection_dispose (GObject *object)
462 GDBusConnection *connection = G_DBUS_CONNECTION (object);
464 G_LOCK (message_bus_lock);
465 if (connection == the_session_bus)
467 the_session_bus = NULL;
469 else if (connection == the_system_bus)
471 the_system_bus = NULL;
473 CONNECTION_LOCK (connection);
474 if (connection->worker != NULL)
476 _g_dbus_worker_stop (connection->worker);
477 connection->worker = NULL;
478 if (alive_connections != NULL)
479 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
483 if (alive_connections != NULL)
484 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
486 CONNECTION_UNLOCK (connection);
487 G_UNLOCK (message_bus_lock);
489 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
490 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
494 g_dbus_connection_finalize (GObject *object)
496 GDBusConnection *connection = G_DBUS_CONNECTION (object);
498 connection->finalizing = TRUE;
500 purge_all_signal_subscriptions (connection);
502 purge_all_filters (connection);
503 g_ptr_array_unref (connection->filters);
505 if (connection->authentication_observer != NULL)
506 g_object_unref (connection->authentication_observer);
508 if (connection->auth != NULL)
509 g_object_unref (connection->auth);
511 if (connection->credentials)
512 g_object_unref (connection->credentials);
514 if (connection->stream != NULL)
516 /* We don't really care if closing the stream succeeds or not */
517 g_io_stream_close_async (connection->stream,
519 NULL, /* GCancellable */
520 NULL, /* GAsyncReadyCallback */
521 NULL); /* userdata */
522 g_object_unref (connection->stream);
523 connection->stream = NULL;
526 g_free (connection->address);
528 g_free (connection->guid);
529 g_free (connection->bus_unique_name);
531 if (connection->initialization_error != NULL)
532 g_error_free (connection->initialization_error);
534 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
536 g_hash_table_unref (connection->map_rule_to_signal_data);
537 g_hash_table_unref (connection->map_id_to_signal_data);
538 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
540 g_hash_table_unref (connection->map_id_to_ei);
541 g_hash_table_unref (connection->map_object_path_to_eo);
542 g_hash_table_unref (connection->map_id_to_es);
543 g_hash_table_unref (connection->map_object_path_to_es);
545 if (connection->main_context_at_construction != NULL)
546 g_main_context_unref (connection->main_context_at_construction);
548 g_free (connection->machine_id);
550 g_mutex_free (connection->init_lock);
551 g_mutex_free (connection->lock);
553 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
557 g_dbus_connection_get_property (GObject *object,
562 GDBusConnection *connection = G_DBUS_CONNECTION (object);
567 g_value_set_object (value, g_dbus_connection_get_stream (connection));
571 g_value_set_string (value, g_dbus_connection_get_guid (connection));
574 case PROP_UNIQUE_NAME:
575 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
579 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
582 case PROP_EXIT_ON_CLOSE:
583 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
586 case PROP_CAPABILITY_FLAGS:
587 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
591 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
597 g_dbus_connection_set_property (GObject *object,
602 GDBusConnection *connection = G_DBUS_CONNECTION (object);
607 connection->stream = g_value_dup_object (value);
611 connection->guid = g_value_dup_string (value);
615 connection->address = g_value_dup_string (value);
619 connection->flags = g_value_get_flags (value);
622 case PROP_EXIT_ON_CLOSE:
623 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
626 case PROP_AUTHENTICATION_OBSERVER:
627 connection->authentication_observer = g_value_dup_object (value);
631 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
637 g_dbus_connection_real_closed (GDBusConnection *connection,
638 gboolean remote_peer_vanished,
641 if (remote_peer_vanished && connection->exit_on_close && connection->is_initialized)
645 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
648 g_quark_to_string (error->domain), error->code);
652 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
659 g_dbus_connection_class_init (GDBusConnectionClass *klass)
661 GObjectClass *gobject_class;
663 gobject_class = G_OBJECT_CLASS (klass);
665 gobject_class->finalize = g_dbus_connection_finalize;
666 gobject_class->dispose = g_dbus_connection_dispose;
667 gobject_class->set_property = g_dbus_connection_set_property;
668 gobject_class->get_property = g_dbus_connection_get_property;
670 klass->closed = g_dbus_connection_real_closed;
673 * GDBusConnection:stream:
675 * The underlying #GIOStream used for I/O.
677 * If this is passed on construction and is a #GSocketConnection,
678 * then the corresponding #GSocket will be put into non-blocking mode.
682 g_object_class_install_property (gobject_class,
684 g_param_spec_object ("stream",
686 P_("The underlying streams used for I/O"),
690 G_PARAM_CONSTRUCT_ONLY |
691 G_PARAM_STATIC_NAME |
692 G_PARAM_STATIC_BLURB |
693 G_PARAM_STATIC_NICK));
696 * GDBusConnection:address:
698 * A D-Bus address specifying potential endpoints that can be used
699 * when establishing the connection.
703 g_object_class_install_property (gobject_class,
705 g_param_spec_string ("address",
707 P_("D-Bus address specifying potential socket endpoints"),
710 G_PARAM_CONSTRUCT_ONLY |
711 G_PARAM_STATIC_NAME |
712 G_PARAM_STATIC_BLURB |
713 G_PARAM_STATIC_NICK));
716 * GDBusConnection:flags:
718 * Flags from the #GDBusConnectionFlags enumeration.
722 g_object_class_install_property (gobject_class,
724 g_param_spec_flags ("flags",
727 G_TYPE_DBUS_CONNECTION_FLAGS,
728 G_DBUS_CONNECTION_FLAGS_NONE,
730 G_PARAM_CONSTRUCT_ONLY |
731 G_PARAM_STATIC_NAME |
732 G_PARAM_STATIC_BLURB |
733 G_PARAM_STATIC_NICK));
736 * GDBusConnection:guid:
738 * The GUID of the peer performing the role of server when
741 * If you are constructing a #GDBusConnection and pass
742 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
743 * #GDBusConnection:flags property then you MUST also set this
744 * property to a valid guid.
746 * If you are constructing a #GDBusConnection and pass
747 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
748 * #GDBusConnection:flags property you will be able to read the GUID
749 * of the other peer here after the connection has been successfully
754 g_object_class_install_property (gobject_class,
756 g_param_spec_string ("guid",
758 P_("GUID of the server peer"),
762 G_PARAM_CONSTRUCT_ONLY |
763 G_PARAM_STATIC_NAME |
764 G_PARAM_STATIC_BLURB |
765 G_PARAM_STATIC_NICK));
768 * GDBusConnection:unique-name:
770 * The unique name as assigned by the message bus or %NULL if the
771 * connection is not open or not a message bus connection.
775 g_object_class_install_property (gobject_class,
777 g_param_spec_string ("unique-name",
779 P_("Unique name of bus connection"),
782 G_PARAM_STATIC_NAME |
783 G_PARAM_STATIC_BLURB |
784 G_PARAM_STATIC_NICK));
787 * GDBusConnection:closed:
789 * A boolean specifying whether the connection has been closed.
793 g_object_class_install_property (gobject_class,
795 g_param_spec_boolean ("closed",
797 P_("Whether the connection is closed"),
800 G_PARAM_STATIC_NAME |
801 G_PARAM_STATIC_BLURB |
802 G_PARAM_STATIC_NICK));
805 * GDBusConnection:exit-on-close:
807 * A boolean specifying whether the process will be terminated (by
808 * calling <literal>raise(SIGTERM)</literal>) if the connection
809 * is closed by the remote peer.
813 g_object_class_install_property (gobject_class,
815 g_param_spec_boolean ("exit-on-close",
817 P_("Whether the process is terminated when the connection is closed"),
821 G_PARAM_STATIC_NAME |
822 G_PARAM_STATIC_BLURB |
823 G_PARAM_STATIC_NICK));
826 * GDBusConnection:capabilities:
828 * Flags from the #GDBusCapabilityFlags enumeration
829 * representing connection features negotiated with the other peer.
833 g_object_class_install_property (gobject_class,
834 PROP_CAPABILITY_FLAGS,
835 g_param_spec_flags ("capabilities",
838 G_TYPE_DBUS_CAPABILITY_FLAGS,
839 G_DBUS_CAPABILITY_FLAGS_NONE,
841 G_PARAM_STATIC_NAME |
842 G_PARAM_STATIC_BLURB |
843 G_PARAM_STATIC_NICK));
846 * GDBusConnection:authentication-observer:
848 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
852 g_object_class_install_property (gobject_class,
853 PROP_AUTHENTICATION_OBSERVER,
854 g_param_spec_object ("authentication-observer",
855 P_("Authentication Observer"),
856 P_("Object used to assist in the authentication process"),
857 G_TYPE_DBUS_AUTH_OBSERVER,
859 G_PARAM_CONSTRUCT_ONLY |
860 G_PARAM_STATIC_NAME |
861 G_PARAM_STATIC_BLURB |
862 G_PARAM_STATIC_NICK));
865 * GDBusConnection::closed:
866 * @connection: The #GDBusConnection emitting the signal.
867 * @remote_peer_vanished: %TRUE if @connection is closed because the
868 * remote peer closed its end of the connection.
869 * @error: A #GError with more details about the event or %NULL.
871 * Emitted when the connection is closed.
873 * The cause of this event can be
876 * If g_dbus_connection_close() is called. In this case
877 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
880 * If the remote peer closes the connection. In this case
881 * @remote_peer_vanished is set to %TRUE and @error is set.
884 * If the remote peer sends invalid or malformed data. In this
885 * case @remote_peer_vanished is set to %FALSE and @error
890 * Upon receiving this signal, you should give up your reference to
891 * @connection. You are guaranteed that this signal is emitted only
896 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
897 G_TYPE_DBUS_CONNECTION,
899 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
910 g_dbus_connection_init (GDBusConnection *connection)
912 connection->lock = g_mutex_new ();
913 connection->init_lock = g_mutex_new ();
915 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
917 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
919 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
921 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
924 (GDestroyNotify) g_ptr_array_unref);
926 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
929 (GDestroyNotify) exported_object_free);
931 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
934 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
937 (GDestroyNotify) exported_subtree_free);
939 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
942 connection->main_context_at_construction = g_main_context_get_thread_default ();
943 if (connection->main_context_at_construction != NULL)
944 g_main_context_ref (connection->main_context_at_construction);
946 connection->filters = g_ptr_array_new ();
950 * g_dbus_connection_get_stream:
951 * @connection: a #GDBusConnection
953 * Gets the underlying stream used for IO.
955 * Returns: (transfer none): the stream used for IO
960 g_dbus_connection_get_stream (GDBusConnection *connection)
962 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
963 return connection->stream;
967 * g_dbus_connection_start_message_processing:
968 * @connection: A #GDBusConnection.
970 * If @connection was created with
971 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
972 * starts processing messages. Does nothing on if @connection wasn't
973 * created with this flag or if the method has already been called.
978 g_dbus_connection_start_message_processing (GDBusConnection *connection)
980 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
981 _g_dbus_worker_unfreeze (connection->worker);
985 * g_dbus_connection_is_closed:
986 * @connection: A #GDBusConnection.
988 * Gets whether @connection is closed.
990 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
995 g_dbus_connection_is_closed (GDBusConnection *connection)
997 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
998 return connection->closed;
1002 * g_dbus_connection_get_capabilities:
1003 * @connection: A #GDBusConnection.
1005 * Gets the capabilities negotiated with the remote peer
1007 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1011 GDBusCapabilityFlags
1012 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1014 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1015 return connection->capabilities;
1018 /* ---------------------------------------------------------------------------------------------------- */
1021 flush_in_thread_func (GSimpleAsyncResult *res,
1023 GCancellable *cancellable)
1028 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1031 g_simple_async_result_take_error (res, error);
1035 * g_dbus_connection_flush:
1036 * @connection: A #GDBusConnection.
1037 * @cancellable: A #GCancellable or %NULL.
1038 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1039 * satisfied or %NULL if you don't care about the result.
1040 * @user_data: The data to pass to @callback.
1042 * Asynchronously flushes @connection, that is, writes all queued
1043 * outgoing message to the transport and then flushes the transport
1044 * (using g_output_stream_flush_async()). This is useful in programs
1045 * that wants to emit a D-Bus signal and then exit
1046 * immediately. Without flushing the connection, there is no guarantee
1047 * that the message has been sent to the networking buffers in the OS
1050 * This is an asynchronous method. When the operation is finished,
1051 * @callback will be invoked in the <link
1052 * linkend="g-main-context-push-thread-default">thread-default main
1053 * loop</link> of the thread you are calling this method from. You can
1054 * then call g_dbus_connection_flush_finish() to get the result of the
1055 * operation. See g_dbus_connection_flush_sync() for the synchronous
1061 g_dbus_connection_flush (GDBusConnection *connection,
1062 GCancellable *cancellable,
1063 GAsyncReadyCallback callback,
1066 GSimpleAsyncResult *simple;
1068 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1070 simple = g_simple_async_result_new (G_OBJECT (connection),
1073 g_dbus_connection_flush);
1074 g_simple_async_result_run_in_thread (simple,
1075 flush_in_thread_func,
1078 g_object_unref (simple);
1082 * g_dbus_connection_flush_finish:
1083 * @connection: A #GDBusConnection.
1084 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1085 * @error: Return location for error or %NULL.
1087 * Finishes an operation started with g_dbus_connection_flush().
1089 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1094 g_dbus_connection_flush_finish (GDBusConnection *connection,
1098 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1103 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1104 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1105 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1107 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1109 if (g_simple_async_result_propagate_error (simple, error))
1119 * g_dbus_connection_flush_sync:
1120 * @connection: A #GDBusConnection.
1121 * @cancellable: A #GCancellable or %NULL.
1122 * @error: Return location for error or %NULL.
1124 * Synchronously flushes @connection. The calling thread is blocked
1125 * until this is done. See g_dbus_connection_flush() for the
1126 * asynchronous version of this method and more details about what it
1129 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1134 g_dbus_connection_flush_sync (GDBusConnection *connection,
1135 GCancellable *cancellable,
1140 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1141 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1145 if (connection->closed)
1147 g_set_error_literal (error,
1150 _("The connection is closed"));
1154 ret = _g_dbus_worker_flush_sync (connection->worker,
1162 /* ---------------------------------------------------------------------------------------------------- */
1166 GDBusConnection *connection;
1168 gboolean remote_peer_vanished;
1172 emit_closed_data_free (EmitClosedData *data)
1174 g_object_unref (data->connection);
1175 if (data->error != NULL)
1176 g_error_free (data->error);
1181 emit_closed_in_idle (gpointer user_data)
1183 EmitClosedData *data = user_data;
1186 g_object_notify (G_OBJECT (data->connection), "closed");
1187 g_signal_emit (data->connection,
1188 signals[CLOSED_SIGNAL],
1190 data->remote_peer_vanished,
1196 /* Can be called from any thread, must hold lock */
1198 set_closed_unlocked (GDBusConnection *connection,
1199 gboolean remote_peer_vanished,
1202 GSource *idle_source;
1203 EmitClosedData *data;
1205 CONNECTION_ENSURE_LOCK (connection);
1207 g_assert (!connection->closed);
1209 connection->closed = TRUE;
1211 data = g_new0 (EmitClosedData, 1);
1212 data->connection = g_object_ref (connection);
1213 data->remote_peer_vanished = remote_peer_vanished;
1214 data->error = error != NULL ? g_error_copy (error) : NULL;
1216 idle_source = g_idle_source_new ();
1217 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1218 g_source_set_callback (idle_source,
1219 emit_closed_in_idle,
1221 (GDestroyNotify) emit_closed_data_free);
1222 g_source_attach (idle_source, connection->main_context_at_construction);
1223 g_source_unref (idle_source);
1226 /* ---------------------------------------------------------------------------------------------------- */
1229 close_in_thread_func (GSimpleAsyncResult *res,
1231 GCancellable *cancellable)
1236 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1239 g_simple_async_result_take_error (res, error);
1243 * g_dbus_connection_close:
1244 * @connection: A #GDBusConnection.
1245 * @cancellable: A #GCancellable or %NULL.
1246 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1247 * satisfied or %NULL if you don't care about the result.
1248 * @user_data: The data to pass to @callback.
1250 * Closes @connection. Note that this never causes the process to
1251 * exit (this might only happen if the other end of a shared message
1252 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1254 * Once the connection is closed, operations such as sending a message
1255 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1256 * will not automatically flush the connection so queued messages may
1257 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1259 * If @connection is already closed, this method fails with
1260 * %G_IO_ERROR_CLOSED.
1262 * When @connection has been closed, the #GDBusConnection::closed
1263 * signal is emitted in the <link
1264 * linkend="g-main-context-push-thread-default">thread-default main
1265 * loop</link> of the thread that @connection was constructed in.
1267 * This is an asynchronous method. When the operation is finished,
1268 * @callback will be invoked in the <link
1269 * linkend="g-main-context-push-thread-default">thread-default main
1270 * loop</link> of the thread you are calling this method from. You can
1271 * then call g_dbus_connection_close_finish() to get the result of the
1272 * operation. See g_dbus_connection_close_sync() for the synchronous
1278 g_dbus_connection_close (GDBusConnection *connection,
1279 GCancellable *cancellable,
1280 GAsyncReadyCallback callback,
1283 GSimpleAsyncResult *simple;
1285 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1287 simple = g_simple_async_result_new (G_OBJECT (connection),
1290 g_dbus_connection_close);
1291 g_simple_async_result_run_in_thread (simple,
1292 close_in_thread_func,
1295 g_object_unref (simple);
1299 * g_dbus_connection_close_finish:
1300 * @connection: A #GDBusConnection.
1301 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1302 * @error: Return location for error or %NULL.
1304 * Finishes an operation started with g_dbus_connection_close().
1306 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1311 g_dbus_connection_close_finish (GDBusConnection *connection,
1315 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1320 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1321 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1322 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1324 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1326 if (g_simple_async_result_propagate_error (simple, error))
1336 * g_dbus_connection_close_sync:
1337 * @connection: A #GDBusConnection.
1338 * @cancellable: A #GCancellable or %NULL.
1339 * @error: Return location for error or %NULL.
1341 * Synchronously closees @connection. The calling thread is blocked
1342 * until this is done. See g_dbus_connection_close() for the
1343 * asynchronous version of this method and more details about what it
1346 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1351 g_dbus_connection_close_sync (GDBusConnection *connection,
1352 GCancellable *cancellable,
1357 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1358 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1362 CONNECTION_LOCK (connection);
1363 if (!connection->closed)
1365 ret = g_io_stream_close (connection->stream,
1369 set_closed_unlocked (connection, FALSE, NULL);
1373 g_set_error_literal (error,
1376 _("The connection is closed"));
1378 CONNECTION_UNLOCK (connection);
1383 /* ---------------------------------------------------------------------------------------------------- */
1386 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1387 GDBusMessage *message,
1388 GDBusSendMessageFlags flags,
1389 volatile guint32 *out_serial,
1394 guint32 serial_to_use;
1397 CONNECTION_ENSURE_LOCK (connection);
1399 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1400 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1402 /* TODO: check all necessary headers are present */
1407 if (out_serial != NULL)
1410 if (connection->closed)
1412 g_set_error_literal (error,
1415 _("The connection is closed"));
1419 blob = g_dbus_message_to_blob (message,
1421 connection->capabilities,
1426 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1427 serial_to_use = g_dbus_message_get_serial (message);
1429 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1434 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1437 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1440 g_assert_not_reached ();
1445 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1446 blob_size, serial_to_use, connection);
1447 g_printerr ("----\n");
1448 hexdump (blob, blob_size);
1449 g_printerr ("----\n");
1452 /* TODO: use connection->auth to encode the blob */
1454 if (out_serial != NULL)
1455 *out_serial = serial_to_use;
1457 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1458 g_dbus_message_set_serial (message, serial_to_use);
1460 g_dbus_message_lock (message);
1461 _g_dbus_worker_send_message (connection->worker,
1465 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1476 * g_dbus_connection_send_message:
1477 * @connection: A #GDBusConnection.
1478 * @message: A #GDBusMessage
1479 * @flags: Flags affecting how the message is sent.
1480 * @out_serial: (out) (allow-none): Return location for serial number assigned
1481 * to @message when sending it or %NULL.
1482 * @error: Return location for error or %NULL.
1484 * Asynchronously sends @message to the peer represented by @connection.
1486 * Unless @flags contain the
1487 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1488 * will be assigned by @connection and set on @message via
1489 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1490 * serial number used will be written to this location prior to
1491 * submitting the message to the underlying transport.
1493 * If @connection is closed then the operation will fail with
1494 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1495 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1497 * See <xref linkend="gdbus-server"/> and <xref
1498 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1499 * low-level API to send and receive UNIX file descriptors.
1501 * Note that @message must be unlocked, unless @flags contain the
1502 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1504 * Returns: %TRUE if the message was well-formed and queued for
1505 * transmission, %FALSE if @error is set.
1510 g_dbus_connection_send_message (GDBusConnection *connection,
1511 GDBusMessage *message,
1512 GDBusSendMessageFlags flags,
1513 volatile guint32 *out_serial,
1518 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1519 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1520 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1521 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1523 CONNECTION_LOCK (connection);
1524 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1525 CONNECTION_UNLOCK (connection);
1529 /* ---------------------------------------------------------------------------------------------------- */
1533 volatile gint ref_count;
1534 GDBusConnection *connection;
1536 GSimpleAsyncResult *simple;
1538 GMainContext *main_context;
1540 GCancellable *cancellable;
1542 gulong cancellable_handler_id;
1544 GSource *timeout_source;
1549 static SendMessageData *
1550 send_message_data_ref (SendMessageData *data)
1552 g_atomic_int_inc (&data->ref_count);
1557 send_message_data_unref (SendMessageData *data)
1559 if (g_atomic_int_dec_and_test (&data->ref_count))
1561 g_assert (data->timeout_source == NULL);
1562 g_assert (data->simple == NULL);
1563 g_assert (data->cancellable_handler_id == 0);
1564 g_object_unref (data->connection);
1565 if (data->cancellable != NULL)
1566 g_object_unref (data->cancellable);
1567 if (data->main_context != NULL)
1568 g_main_context_unref (data->main_context);
1573 /* ---------------------------------------------------------------------------------------------------- */
1575 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1577 send_message_with_reply_deliver (SendMessageData *data)
1579 CONNECTION_ENSURE_LOCK (data->connection);
1581 g_assert (!data->delivered);
1583 data->delivered = TRUE;
1585 g_simple_async_result_complete_in_idle (data->simple);
1586 g_object_unref (data->simple);
1587 data->simple = NULL;
1589 if (data->timeout_source != NULL)
1591 g_source_destroy (data->timeout_source);
1592 data->timeout_source = NULL;
1594 if (data->cancellable_handler_id > 0)
1596 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1597 data->cancellable_handler_id = 0;
1600 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1601 GUINT_TO_POINTER (data->serial)));
1603 send_message_data_unref (data);
1606 /* ---------------------------------------------------------------------------------------------------- */
1608 /* must hold lock */
1610 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1611 GDBusMessage *reply)
1613 if (data->delivered)
1616 g_simple_async_result_set_op_res_gpointer (data->simple,
1617 g_object_ref (reply),
1620 send_message_with_reply_deliver (data);
1626 /* ---------------------------------------------------------------------------------------------------- */
1629 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1631 SendMessageData *data = user_data;
1633 CONNECTION_LOCK (data->connection);
1634 if (data->delivered)
1637 g_simple_async_result_set_error (data->simple,
1639 G_IO_ERROR_CANCELLED,
1640 _("Operation was cancelled"));
1642 send_message_with_reply_deliver (data);
1645 CONNECTION_UNLOCK (data->connection);
1649 /* Can be called from any thread with or without lock held */
1651 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1654 SendMessageData *data = user_data;
1655 GSource *idle_source;
1657 /* postpone cancellation to idle handler since we may be called directly
1658 * via g_cancellable_connect() (e.g. holding lock)
1660 idle_source = g_idle_source_new ();
1661 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1662 g_source_set_callback (idle_source,
1663 send_message_with_reply_cancelled_idle_cb,
1664 send_message_data_ref (data),
1665 (GDestroyNotify) send_message_data_unref);
1666 g_source_attach (idle_source, data->main_context);
1667 g_source_unref (idle_source);
1670 /* ---------------------------------------------------------------------------------------------------- */
1673 send_message_with_reply_timeout_cb (gpointer user_data)
1675 SendMessageData *data = user_data;
1677 CONNECTION_LOCK (data->connection);
1678 if (data->delivered)
1681 g_simple_async_result_set_error (data->simple,
1683 G_IO_ERROR_TIMED_OUT,
1684 _("Timeout was reached"));
1686 send_message_with_reply_deliver (data);
1689 CONNECTION_UNLOCK (data->connection);
1694 /* ---------------------------------------------------------------------------------------------------- */
1697 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1698 GDBusMessage *message,
1699 GDBusSendMessageFlags flags,
1701 volatile guint32 *out_serial,
1702 GCancellable *cancellable,
1703 GAsyncReadyCallback callback,
1706 GSimpleAsyncResult *simple;
1707 SendMessageData *data;
1709 volatile guint32 serial;
1713 if (out_serial == NULL)
1714 out_serial = &serial;
1716 if (timeout_msec == -1)
1717 timeout_msec = 25 * 1000;
1719 simple = g_simple_async_result_new (G_OBJECT (connection),
1722 g_dbus_connection_send_message_with_reply);
1724 if (g_cancellable_is_cancelled (cancellable))
1726 g_simple_async_result_set_error (simple,
1728 G_IO_ERROR_CANCELLED,
1729 _("Operation was cancelled"));
1730 g_simple_async_result_complete_in_idle (simple);
1731 g_object_unref (simple);
1735 if (connection->closed)
1737 g_simple_async_result_set_error (simple,
1740 _("The connection is closed"));
1741 g_simple_async_result_complete_in_idle (simple);
1742 g_object_unref (simple);
1747 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1749 g_simple_async_result_take_error (simple, error);
1750 g_simple_async_result_complete_in_idle (simple);
1751 g_object_unref (simple);
1755 data = g_new0 (SendMessageData, 1);
1756 data->ref_count = 1;
1757 data->connection = g_object_ref (connection);
1758 data->simple = simple;
1759 data->serial = *out_serial;
1760 data->main_context = g_main_context_get_thread_default ();
1761 if (data->main_context != NULL)
1762 g_main_context_ref (data->main_context);
1764 if (cancellable != NULL)
1766 data->cancellable = g_object_ref (cancellable);
1767 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1768 G_CALLBACK (send_message_with_reply_cancelled_cb),
1769 send_message_data_ref (data),
1770 (GDestroyNotify) send_message_data_unref);
1771 g_object_set_data_full (G_OBJECT (simple),
1773 g_object_ref (cancellable),
1774 (GDestroyNotify) g_object_unref);
1777 if (timeout_msec != G_MAXINT)
1779 data->timeout_source = g_timeout_source_new (timeout_msec);
1780 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1781 g_source_set_callback (data->timeout_source,
1782 send_message_with_reply_timeout_cb,
1783 send_message_data_ref (data),
1784 (GDestroyNotify) send_message_data_unref);
1785 g_source_attach (data->timeout_source, data->main_context);
1786 g_source_unref (data->timeout_source);
1789 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1790 GUINT_TO_POINTER (*out_serial),
1798 * g_dbus_connection_send_message_with_reply:
1799 * @connection: A #GDBusConnection.
1800 * @message: A #GDBusMessage.
1801 * @flags: Flags affecting how the message is sent.
1802 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1803 * timeout or %G_MAXINT for no timeout.
1804 * @out_serial: (out) (allow-none): Return location for serial number assigned
1805 * to @message when sending it or %NULL.
1806 * @cancellable: A #GCancellable or %NULL.
1807 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1808 * satisfied or %NULL if you don't care about the result.
1809 * @user_data: The data to pass to @callback.
1811 * Asynchronously sends @message to the peer represented by @connection.
1813 * Unless @flags contain the
1814 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1815 * will be assigned by @connection and set on @message via
1816 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1817 * serial number used will be written to this location prior to
1818 * submitting the message to the underlying transport.
1820 * If @connection is closed then the operation will fail with
1821 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1822 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1823 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1825 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1826 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1827 * of the thread you are calling this method from. You can then call
1828 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1829 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1831 * Note that @message must be unlocked, unless @flags contain the
1832 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1834 * See <xref linkend="gdbus-server"/> and <xref
1835 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1836 * low-level API to send and receive UNIX file descriptors.
1841 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1842 GDBusMessage *message,
1843 GDBusSendMessageFlags flags,
1845 volatile guint32 *out_serial,
1846 GCancellable *cancellable,
1847 GAsyncReadyCallback callback,
1850 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1851 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1852 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1853 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1855 CONNECTION_LOCK (connection);
1856 g_dbus_connection_send_message_with_reply_unlocked (connection,
1864 CONNECTION_UNLOCK (connection);
1868 * g_dbus_connection_send_message_with_reply_finish:
1869 * @connection: a #GDBusConnection
1870 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1871 * @error: Return location for error or %NULL.
1873 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1875 * Note that @error is only set if a local in-process error
1876 * occured. That is to say that the returned #GDBusMessage object may
1877 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1878 * g_dbus_message_to_gerror() to transcode this to a #GError.
1880 * See <xref linkend="gdbus-server"/> and <xref
1881 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1882 * low-level API to send and receive UNIX file descriptors.
1884 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
1889 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1893 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1894 GDBusMessage *reply;
1895 GCancellable *cancellable;
1897 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1898 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1902 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1904 if (g_simple_async_result_propagate_error (simple, error))
1907 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1908 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1909 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1911 g_object_unref (reply);
1913 g_set_error_literal (error,
1915 G_IO_ERROR_CANCELLED,
1916 _("Operation was cancelled"));
1922 /* ---------------------------------------------------------------------------------------------------- */
1927 GMainContext *context;
1929 } SendMessageSyncData;
1932 send_message_with_reply_sync_cb (GDBusConnection *connection,
1936 SendMessageSyncData *data = user_data;
1937 data->res = g_object_ref (res);
1938 g_main_loop_quit (data->loop);
1942 * g_dbus_connection_send_message_with_reply_sync:
1943 * @connection: A #GDBusConnection.
1944 * @message: A #GDBusMessage.
1945 * @flags: Flags affecting how the message is sent.
1946 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1947 * timeout or %G_MAXINT for no timeout.
1948 * @out_serial: (out) (allow-none): Return location for serial number assigned
1949 * to @message when sending it or %NULL.
1950 * @cancellable: A #GCancellable or %NULL.
1951 * @error: Return location for error or %NULL.
1953 * Synchronously sends @message to the peer represented by @connection
1954 * and blocks the calling thread until a reply is received or the
1955 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1956 * for the asynchronous version of this method.
1958 * Unless @flags contain the
1959 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1960 * will be assigned by @connection and set on @message via
1961 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1962 * serial number used will be written to this location prior to
1963 * submitting the message to the underlying transport.
1965 * If @connection is closed then the operation will fail with
1966 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1967 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1968 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1970 * Note that @error is only set if a local in-process error
1971 * occured. That is to say that the returned #GDBusMessage object may
1972 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1973 * g_dbus_message_to_gerror() to transcode this to a #GError.
1975 * See <xref linkend="gdbus-server"/> and <xref
1976 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1977 * low-level API to send and receive UNIX file descriptors.
1979 * Note that @message must be unlocked, unless @flags contain the
1980 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1982 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
1987 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1988 GDBusMessage *message,
1989 GDBusSendMessageFlags flags,
1991 volatile guint32 *out_serial,
1992 GCancellable *cancellable,
1995 SendMessageSyncData *data;
1996 GDBusMessage *reply;
1998 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1999 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2000 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2001 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2002 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2004 data = g_new0 (SendMessageSyncData, 1);
2005 data->context = g_main_context_new ();
2006 data->loop = g_main_loop_new (data->context, FALSE);
2008 g_main_context_push_thread_default (data->context);
2010 g_dbus_connection_send_message_with_reply (connection,
2016 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2018 g_main_loop_run (data->loop);
2019 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2023 g_main_context_pop_thread_default (data->context);
2025 g_main_context_unref (data->context);
2026 g_main_loop_unref (data->loop);
2027 g_object_unref (data->res);
2033 /* ---------------------------------------------------------------------------------------------------- */
2037 GDBusMessageFilterFunction func;
2044 GDBusMessageFilterFunction filter_function;
2046 GDestroyNotify user_data_free_func;
2049 /* Called in worker's thread - we must not block */
2051 on_worker_message_received (GDBusWorker *worker,
2052 GDBusMessage *message,
2055 GDBusConnection *connection;
2056 FilterCallback *filters;
2061 G_LOCK (message_bus_lock);
2062 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2065 G_UNLOCK (message_bus_lock);
2068 connection = G_DBUS_CONNECTION (user_data);
2069 g_object_ref (connection);
2070 G_UNLOCK (message_bus_lock);
2072 //g_debug ("in on_worker_message_received");
2074 g_object_ref (message);
2075 g_dbus_message_lock (message);
2077 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2079 /* First collect the set of callback functions */
2080 CONNECTION_LOCK (connection);
2081 num_filters = connection->filters->len;
2082 filters = g_new0 (FilterCallback, num_filters);
2083 for (n = 0; n < num_filters; n++)
2085 FilterData *data = connection->filters->pdata[n];
2086 filters[n].func = data->filter_function;
2087 filters[n].user_data = data->user_data;
2089 CONNECTION_UNLOCK (connection);
2091 /* then call the filters in order (without holding the lock) */
2092 for (n = 0; n < num_filters; n++)
2094 message = filters[n].func (connection,
2097 filters[n].user_data);
2098 if (message == NULL)
2100 g_dbus_message_lock (message);
2103 /* Standard dispatch unless the filter ate the message - no need to
2104 * do anything if the message was altered
2106 if (message != NULL)
2108 GDBusMessageType message_type;
2110 message_type = g_dbus_message_get_message_type (message);
2111 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2113 guint32 reply_serial;
2114 SendMessageData *send_message_data;
2116 reply_serial = g_dbus_message_get_reply_serial (message);
2117 CONNECTION_LOCK (connection);
2118 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2119 GUINT_TO_POINTER (reply_serial));
2120 if (send_message_data != NULL)
2122 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2123 send_message_data_deliver_reply_unlocked (send_message_data, message);
2127 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2129 CONNECTION_UNLOCK (connection);
2131 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2133 CONNECTION_LOCK (connection);
2134 distribute_signals (connection, message);
2135 CONNECTION_UNLOCK (connection);
2137 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2139 CONNECTION_LOCK (connection);
2140 distribute_method_call (connection, message);
2141 CONNECTION_UNLOCK (connection);
2145 if (message != NULL)
2146 g_object_unref (message);
2147 g_object_unref (connection);
2151 /* Called in worker's thread */
2152 static GDBusMessage *
2153 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2154 GDBusMessage *message,
2157 GDBusConnection *connection;
2158 FilterCallback *filters;
2163 G_LOCK (message_bus_lock);
2164 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2167 G_UNLOCK (message_bus_lock);
2170 connection = G_DBUS_CONNECTION (user_data);
2171 g_object_ref (connection);
2172 G_UNLOCK (message_bus_lock);
2174 //g_debug ("in on_worker_message_about_to_be_sent");
2176 /* First collect the set of callback functions */
2177 CONNECTION_LOCK (connection);
2178 num_filters = connection->filters->len;
2179 filters = g_new0 (FilterCallback, num_filters);
2180 for (n = 0; n < num_filters; n++)
2182 FilterData *data = connection->filters->pdata[n];
2183 filters[n].func = data->filter_function;
2184 filters[n].user_data = data->user_data;
2186 CONNECTION_UNLOCK (connection);
2188 /* then call the filters in order (without holding the lock) */
2189 for (n = 0; n < num_filters; n++)
2191 g_dbus_message_lock (message);
2192 message = filters[n].func (connection,
2195 filters[n].user_data);
2196 if (message == NULL)
2200 g_object_unref (connection);
2206 /* Called in worker's thread - we must not block */
2208 on_worker_closed (GDBusWorker *worker,
2209 gboolean remote_peer_vanished,
2213 GDBusConnection *connection;
2216 G_LOCK (message_bus_lock);
2217 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2220 G_UNLOCK (message_bus_lock);
2223 connection = G_DBUS_CONNECTION (user_data);
2224 g_object_ref (connection);
2225 G_UNLOCK (message_bus_lock);
2227 //g_debug ("in on_worker_closed: %s", error->message);
2229 CONNECTION_LOCK (connection);
2230 if (!connection->closed)
2231 set_closed_unlocked (connection, remote_peer_vanished, error);
2232 CONNECTION_UNLOCK (connection);
2234 g_object_unref (connection);
2237 /* ---------------------------------------------------------------------------------------------------- */
2239 /* Determines the biggest set of capabilities we can support on this connection */
2240 static GDBusCapabilityFlags
2241 get_offered_capabilities_max (GDBusConnection *connection)
2243 GDBusCapabilityFlags ret;
2244 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2246 if (G_IS_UNIX_CONNECTION (connection->stream))
2247 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2253 initable_init (GInitable *initable,
2254 GCancellable *cancellable,
2257 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2260 /* This method needs to be idempotent to work with the singleton
2261 * pattern. See the docs for g_initable_init(). We implement this by
2264 * Unfortunately we can't use the main lock since the on_worker_*()
2265 * callbacks above needs the lock during initialization (for message
2266 * bus connections we do a synchronous Hello() call on the bus).
2268 g_mutex_lock (connection->init_lock);
2272 /* First, handle the case where the connection already has an
2273 * initialization error set.
2275 if (connection->initialization_error != NULL)
2278 /* Also make this a no-op if we're already initialized fine */
2279 if (connection->is_initialized)
2285 g_assert (connection->initialization_error == NULL && !connection->is_initialized);
2287 /* The user can pass multiple (but mutally exclusive) construct
2290 * - stream (of type GIOStream)
2291 * - address (of type gchar*)
2293 * At the end of the day we end up with a non-NULL GIOStream
2294 * object in connection->stream.
2296 if (connection->address != NULL)
2298 g_assert (connection->stream == NULL);
2300 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2301 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2303 g_set_error_literal (error,
2305 G_IO_ERROR_INVALID_ARGUMENT,
2306 _("Unsupported flags encountered when constructing a client-side connection"));
2310 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2311 NULL, /* TODO: out_guid */
2313 &connection->initialization_error);
2314 if (connection->stream == NULL)
2317 else if (connection->stream != NULL)
2323 g_assert_not_reached ();
2326 /* Authenticate the connection */
2327 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2329 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2330 g_assert (connection->guid != NULL);
2331 connection->auth = _g_dbus_auth_new (connection->stream);
2332 if (!_g_dbus_auth_run_server (connection->auth,
2333 connection->authentication_observer,
2335 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2336 get_offered_capabilities_max (connection),
2337 &connection->capabilities,
2338 &connection->credentials,
2340 &connection->initialization_error))
2343 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2345 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2346 g_assert (connection->guid == NULL);
2347 connection->auth = _g_dbus_auth_new (connection->stream);
2348 connection->guid = _g_dbus_auth_run_client (connection->auth,
2349 get_offered_capabilities_max (connection),
2350 &connection->capabilities,
2352 &connection->initialization_error);
2353 if (connection->guid == NULL)
2357 if (connection->authentication_observer != NULL)
2359 g_object_unref (connection->authentication_observer);
2360 connection->authentication_observer = NULL;
2363 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2365 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2368 /* We want all IO operations to be non-blocking since they happen in
2369 * the worker thread which is shared by _all_ connections.
2371 if (G_IS_SOCKET_CONNECTION (connection->stream))
2373 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2377 G_LOCK (message_bus_lock);
2378 if (alive_connections == NULL)
2379 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2380 g_hash_table_insert (alive_connections, connection, connection);
2381 G_UNLOCK (message_bus_lock);
2383 connection->worker = _g_dbus_worker_new (connection->stream,
2384 connection->capabilities,
2385 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2386 on_worker_message_received,
2387 on_worker_message_about_to_be_sent,
2391 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2392 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2394 GVariant *hello_result;
2396 /* we could lift this restriction by adding code in gdbusprivate.c */
2397 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2399 g_set_error_literal (&connection->initialization_error,
2402 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2406 hello_result = g_dbus_connection_call_sync (connection,
2407 "org.freedesktop.DBus", /* name */
2408 "/org/freedesktop/DBus", /* path */
2409 "org.freedesktop.DBus", /* interface */
2411 NULL, /* parameters */
2412 G_VARIANT_TYPE ("(s)"),
2413 G_DBUS_CALL_FLAGS_NONE,
2415 NULL, /* TODO: cancellable */
2416 &connection->initialization_error);
2417 if (hello_result == NULL)
2420 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2421 g_variant_unref (hello_result);
2422 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2425 connection->is_initialized = TRUE;
2431 g_assert (connection->initialization_error != NULL);
2432 g_propagate_error (error, g_error_copy (connection->initialization_error));
2435 g_mutex_unlock (connection->init_lock);
2441 initable_iface_init (GInitableIface *initable_iface)
2443 initable_iface->init = initable_init;
2446 /* ---------------------------------------------------------------------------------------------------- */
2449 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2454 /* ---------------------------------------------------------------------------------------------------- */
2457 * g_dbus_connection_new:
2458 * @stream: A #GIOStream.
2459 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2460 * @flags: Flags describing how to make the connection.
2461 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2462 * @cancellable: A #GCancellable or %NULL.
2463 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2464 * @user_data: The data to pass to @callback.
2466 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2467 * with the end represented by @stream.
2469 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2470 * will be put into non-blocking mode.
2472 * If @observer is not %NULL it may be used to control the
2473 * authentication process.
2475 * When the operation is finished, @callback will be invoked. You can
2476 * then call g_dbus_connection_new_finish() to get the result of the
2479 * This is a asynchronous failable constructor. See
2480 * g_dbus_connection_new_sync() for the synchronous
2486 g_dbus_connection_new (GIOStream *stream,
2488 GDBusConnectionFlags flags,
2489 GDBusAuthObserver *observer,
2490 GCancellable *cancellable,
2491 GAsyncReadyCallback callback,
2494 g_return_if_fail (G_IS_IO_STREAM (stream));
2495 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2503 "authentication-observer", observer,
2508 * g_dbus_connection_new_finish:
2509 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2510 * @error: Return location for error or %NULL.
2512 * Finishes an operation started with g_dbus_connection_new().
2514 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2519 g_dbus_connection_new_finish (GAsyncResult *res,
2523 GObject *source_object;
2525 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2526 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2528 source_object = g_async_result_get_source_object (res);
2529 g_assert (source_object != NULL);
2530 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2533 g_object_unref (source_object);
2535 return G_DBUS_CONNECTION (object);
2541 * g_dbus_connection_new_sync:
2542 * @stream: A #GIOStream.
2543 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2544 * @flags: Flags describing how to make the connection.
2545 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2546 * @cancellable: A #GCancellable or %NULL.
2547 * @error: Return location for error or %NULL.
2549 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2550 * with the end represented by @stream.
2552 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2553 * will be put into non-blocking mode.
2555 * If @observer is not %NULL it may be used to control the
2556 * authentication process.
2558 * This is a synchronous failable constructor. See
2559 * g_dbus_connection_new() for the asynchronous version.
2561 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2566 g_dbus_connection_new_sync (GIOStream *stream,
2568 GDBusConnectionFlags flags,
2569 GDBusAuthObserver *observer,
2570 GCancellable *cancellable,
2573 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2574 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2575 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2581 "authentication-observer", observer,
2585 /* ---------------------------------------------------------------------------------------------------- */
2588 * g_dbus_connection_new_for_address:
2589 * @address: A D-Bus address.
2590 * @flags: Flags describing how to make the connection.
2591 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2592 * @cancellable: A #GCancellable or %NULL.
2593 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2594 * @user_data: The data to pass to @callback.
2596 * Asynchronously connects and sets up a D-Bus client connection for
2597 * exchanging D-Bus messages with an endpoint specified by @address
2598 * which must be in the D-Bus address format.
2600 * This constructor can only be used to initiate client-side
2601 * connections - use g_dbus_connection_new() if you need to act as the
2602 * server. In particular, @flags cannot contain the
2603 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2604 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2606 * When the operation is finished, @callback will be invoked. You can
2607 * then call g_dbus_connection_new_finish() to get the result of the
2610 * If @observer is not %NULL it may be used to control the
2611 * authentication process.
2613 * This is a asynchronous failable constructor. See
2614 * g_dbus_connection_new_for_address_sync() for the synchronous
2620 g_dbus_connection_new_for_address (const gchar *address,
2621 GDBusConnectionFlags flags,
2622 GDBusAuthObserver *observer,
2623 GCancellable *cancellable,
2624 GAsyncReadyCallback callback,
2627 g_return_if_fail (address != NULL);
2628 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2635 "authentication-observer", observer,
2640 * g_dbus_connection_new_for_address_finish:
2641 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2642 * @error: Return location for error or %NULL.
2644 * Finishes an operation started with g_dbus_connection_new_for_address().
2646 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2651 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2655 GObject *source_object;
2657 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2658 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2660 source_object = g_async_result_get_source_object (res);
2661 g_assert (source_object != NULL);
2662 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2665 g_object_unref (source_object);
2667 return G_DBUS_CONNECTION (object);
2673 * g_dbus_connection_new_for_address_sync:
2674 * @address: A D-Bus address.
2675 * @flags: Flags describing how to make the connection.
2676 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2677 * @cancellable: A #GCancellable or %NULL.
2678 * @error: Return location for error or %NULL.
2680 * Synchronously connects and sets up a D-Bus client connection for
2681 * exchanging D-Bus messages with an endpoint specified by @address
2682 * which must be in the D-Bus address format.
2684 * This constructor can only be used to initiate client-side
2685 * connections - use g_dbus_connection_new_sync() if you need to act
2686 * as the server. In particular, @flags cannot contain the
2687 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2688 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2690 * This is a synchronous failable constructor. See
2691 * g_dbus_connection_new_for_address() for the asynchronous version.
2693 * If @observer is not %NULL it may be used to control the
2694 * authentication process.
2696 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2701 g_dbus_connection_new_for_address_sync (const gchar *address,
2702 GDBusConnectionFlags flags,
2703 GDBusAuthObserver *observer,
2704 GCancellable *cancellable,
2707 g_return_val_if_fail (address != NULL, NULL);
2708 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2709 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2714 "authentication-observer", observer,
2718 /* ---------------------------------------------------------------------------------------------------- */
2721 * g_dbus_connection_set_exit_on_close:
2722 * @connection: A #GDBusConnection.
2723 * @exit_on_close: Whether the process should be terminated
2724 * when @connection is closed by the remote peer.
2726 * Sets whether the process should be terminated when @connection is
2727 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2730 * Note that this function should be used with care. Most modern UNIX
2731 * desktops tie the notion of a user session the session bus, and expect
2732 * all of a users applications to quit when their bus connection goes away.
2733 * If you are setting @exit_on_close to %FALSE for the shared session
2734 * bus connection, you should make sure that your application exits
2735 * when the user session ends.
2740 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2741 gboolean exit_on_close)
2743 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2744 connection->exit_on_close = exit_on_close;
2748 * g_dbus_connection_get_exit_on_close:
2749 * @connection: A #GDBusConnection.
2751 * Gets whether the process is terminated when @connection is
2752 * closed by the remote peer. See
2753 * #GDBusConnection:exit-on-close for more details.
2755 * Returns: Whether the process is terminated when @connection is
2756 * closed by the remote peer.
2761 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2763 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2764 return connection->exit_on_close;
2768 * g_dbus_connection_get_guid:
2769 * @connection: A #GDBusConnection.
2771 * The GUID of the peer performing the role of server when
2772 * authenticating. See #GDBusConnection:guid for more details.
2774 * Returns: The GUID. Do not free this string, it is owned by
2780 g_dbus_connection_get_guid (GDBusConnection *connection)
2782 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2783 return connection->guid;
2787 * g_dbus_connection_get_unique_name:
2788 * @connection: A #GDBusConnection.
2790 * Gets the unique name of @connection as assigned by the message
2791 * bus. This can also be used to figure out if @connection is a
2792 * message bus connection.
2794 * Returns: The unique name or %NULL if @connection is not a message
2795 * bus connection. Do not free this string, it is owned by
2801 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2803 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2804 return connection->bus_unique_name;
2808 * g_dbus_connection_get_peer_credentials:
2809 * @connection: A #GDBusConnection.
2811 * Gets the credentials of the authenticated peer. This will always
2812 * return %NULL unless @connection acted as a server
2813 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2814 * when set up and the client passed credentials as part of the
2815 * authentication process.
2817 * In a message bus setup, the message bus is always the server and
2818 * each application is a client. So this method will always return
2819 * %NULL for message bus clients.
2821 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
2822 * this object, it is owned by @connection.
2827 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2829 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2830 return connection->credentials;
2833 /* ---------------------------------------------------------------------------------------------------- */
2835 static guint _global_filter_id = 1;
2838 * g_dbus_connection_add_filter:
2839 * @connection: A #GDBusConnection.
2840 * @filter_function: A filter function.
2841 * @user_data: User data to pass to @filter_function.
2842 * @user_data_free_func: Function to free @user_data with when filter
2843 * is removed or %NULL.
2845 * Adds a message filter. Filters are handlers that are run on all
2846 * incoming and outgoing messages, prior to standard dispatch. Filters
2847 * are run in the order that they were added. The same handler can be
2848 * added as a filter more than once, in which case it will be run more
2849 * than once. Filters added during a filter callback won't be run on
2850 * the message being processed. Filter functions are allowed to modify
2851 * and even drop messages.
2853 * Note that filters are run in a dedicated message handling thread so
2854 * they can't block and, generally, can't do anything but signal a
2855 * worker thread. Also note that filters are rarely needed - use API
2856 * such as g_dbus_connection_send_message_with_reply(),
2857 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
2859 * If a filter consumes an incoming message the message is not
2860 * dispatched anywhere else - not even the standard dispatch machinery
2861 * (that API such as g_dbus_connection_signal_subscribe() and
2862 * g_dbus_connection_send_message_with_reply() relies on) will see the
2863 * message. Similary, if a filter consumes an outgoing message, the
2864 * message will not be sent to the other peer.
2866 * Returns: A filter identifier that can be used with
2867 * g_dbus_connection_remove_filter().
2872 g_dbus_connection_add_filter (GDBusConnection *connection,
2873 GDBusMessageFilterFunction filter_function,
2875 GDestroyNotify user_data_free_func)
2879 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2880 g_return_val_if_fail (filter_function != NULL, 0);
2882 CONNECTION_LOCK (connection);
2883 data = g_new0 (FilterData, 1);
2884 data->id = _global_filter_id++; /* TODO: overflow etc. */
2885 data->filter_function = filter_function;
2886 data->user_data = user_data;
2887 data->user_data_free_func = user_data_free_func;
2888 g_ptr_array_add (connection->filters, data);
2889 CONNECTION_UNLOCK (connection);
2894 /* only called from finalize(), removes all filters */
2896 purge_all_filters (GDBusConnection *connection)
2899 for (n = 0; n < connection->filters->len; n++)
2901 FilterData *data = connection->filters->pdata[n];
2902 if (data->user_data_free_func != NULL)
2903 data->user_data_free_func (data->user_data);
2909 * g_dbus_connection_remove_filter:
2910 * @connection: a #GDBusConnection
2911 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2918 g_dbus_connection_remove_filter (GDBusConnection *connection,
2922 FilterData *to_destroy;
2924 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2926 CONNECTION_LOCK (connection);
2928 for (n = 0; n < connection->filters->len; n++)
2930 FilterData *data = connection->filters->pdata[n];
2931 if (data->id == filter_id)
2933 g_ptr_array_remove_index (connection->filters, n);
2938 CONNECTION_UNLOCK (connection);
2940 /* do free without holding lock */
2941 if (to_destroy != NULL)
2943 if (to_destroy->user_data_free_func != NULL)
2944 to_destroy->user_data_free_func (to_destroy->user_data);
2945 g_free (to_destroy);
2949 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2953 /* ---------------------------------------------------------------------------------------------------- */
2959 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2960 gchar *interface_name;
2964 GArray *subscribers;
2969 GDBusSignalCallback callback;
2971 GDestroyNotify user_data_free_func;
2973 GMainContext *context;
2977 signal_data_free (SignalData *signal_data)
2979 g_free (signal_data->rule);
2980 g_free (signal_data->sender);
2981 g_free (signal_data->sender_unique_name);
2982 g_free (signal_data->interface_name);
2983 g_free (signal_data->member);
2984 g_free (signal_data->object_path);
2985 g_free (signal_data->arg0);
2986 g_array_free (signal_data->subscribers, TRUE);
2987 g_free (signal_data);
2991 args_to_rule (const gchar *sender,
2992 const gchar *interface_name,
2993 const gchar *member,
2994 const gchar *object_path,
3000 rule = g_string_new ("type='signal'");
3002 g_string_prepend_c (rule, '-');
3004 g_string_append_printf (rule, ",sender='%s'", sender);
3005 if (interface_name != NULL)
3006 g_string_append_printf (rule, ",interface='%s'", interface_name);
3008 g_string_append_printf (rule, ",member='%s'", member);
3009 if (object_path != NULL)
3010 g_string_append_printf (rule, ",path='%s'", object_path);
3012 g_string_append_printf (rule, ",arg0='%s'", arg0);
3014 return g_string_free (rule, FALSE);
3017 static guint _global_subscriber_id = 1;
3018 static guint _global_registration_id = 1;
3019 static guint _global_subtree_registration_id = 1;
3021 /* ---------------------------------------------------------------------------------------------------- */
3023 /* must hold lock when calling */
3025 add_match_rule (GDBusConnection *connection,
3026 const gchar *match_rule)
3029 GDBusMessage *message;
3031 if (match_rule[0] == '-')
3034 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3035 "/org/freedesktop/DBus", /* path */
3036 "org.freedesktop.DBus", /* interface */
3038 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3040 if (!g_dbus_connection_send_message_unlocked (connection,
3042 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3046 g_critical ("Error while sending AddMatch() message: %s", error->message);
3047 g_error_free (error);
3049 g_object_unref (message);
3052 /* ---------------------------------------------------------------------------------------------------- */
3054 /* must hold lock when calling */
3056 remove_match_rule (GDBusConnection *connection,
3057 const gchar *match_rule)
3060 GDBusMessage *message;
3062 if (match_rule[0] == '-')
3065 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3066 "/org/freedesktop/DBus", /* path */
3067 "org.freedesktop.DBus", /* interface */
3069 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3072 if (!g_dbus_connection_send_message_unlocked (connection,
3074 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3078 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3079 g_error_free (error);
3081 g_object_unref (message);
3084 /* ---------------------------------------------------------------------------------------------------- */
3087 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3089 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3090 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3091 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3092 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3093 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3096 /* ---------------------------------------------------------------------------------------------------- */
3099 * g_dbus_connection_signal_subscribe:
3100 * @connection: A #GDBusConnection.
3101 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3102 * or %NULL to listen from all senders.
3103 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3104 * match on all interfaces.
3105 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3106 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3107 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3108 * to match on all kinds of arguments.
3109 * @flags: Flags describing how to subscribe to the signal (currently unused).
3110 * @callback: Callback to invoke when there is a signal matching the requested data.
3111 * @user_data: User data to pass to @callback.
3112 * @user_data_free_func: (allow-none): Function to free @user_data with when
3113 * subscription is removed or %NULL.
3115 * Subscribes to signals on @connection and invokes @callback with a
3116 * whenever the signal is received. Note that @callback
3117 * will be invoked in the <link
3118 * linkend="g-main-context-push-thread-default">thread-default main
3119 * loop</link> of the thread you are calling this method from.
3121 * If @connection is not a message bus connection, @sender must be
3124 * If @sender is a well-known name note that @callback is invoked with
3125 * the unique name for the owner of @sender, not the well-known name
3126 * as one would expect. This is because the message bus rewrites the
3127 * name. As such, to avoid certain race conditions, users should be
3128 * tracking the name owner of the well-known name and use that when
3129 * processing the received signal.
3131 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3136 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3137 const gchar *sender,
3138 const gchar *interface_name,
3139 const gchar *member,
3140 const gchar *object_path,
3142 GDBusSignalFlags flags,
3143 GDBusSignalCallback callback,
3145 GDestroyNotify user_data_free_func)
3148 SignalData *signal_data;
3149 SignalSubscriber subscriber;
3150 GPtrArray *signal_data_array;
3151 const gchar *sender_unique_name;
3153 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3154 * an OOM condition. We might want to change that but that would involve making
3155 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3156 * handle that. And there's really no sensible way of handling this short of retrying
3157 * to add the match rule... and then there's the little thing that, hey, maybe there's
3158 * a reason the bus in an OOM condition.
3160 * Doable, but not really sure it's worth it...
3163 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3164 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3165 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3166 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3167 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3168 g_return_val_if_fail (callback != NULL, 0);
3170 CONNECTION_LOCK (connection);
3172 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3173 * with a '-' character to prefix the rule (which will otherwise be
3176 * This allows us to hash the rule and do our lifecycle tracking in
3177 * the usual way, but the '-' prevents the match rule from ever
3178 * actually being send to the bus (either for add or remove).
3180 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3181 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3183 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3184 sender_unique_name = sender;
3186 sender_unique_name = "";
3188 subscriber.callback = callback;
3189 subscriber.user_data = user_data;
3190 subscriber.user_data_free_func = user_data_free_func;
3191 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3192 subscriber.context = g_main_context_get_thread_default ();
3193 if (subscriber.context != NULL)
3194 g_main_context_ref (subscriber.context);
3196 /* see if we've already have this rule */
3197 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3198 if (signal_data != NULL)
3200 g_array_append_val (signal_data->subscribers, subscriber);
3205 signal_data = g_new0 (SignalData, 1);
3206 signal_data->rule = rule;
3207 signal_data->sender = g_strdup (sender);
3208 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3209 signal_data->interface_name = g_strdup (interface_name);
3210 signal_data->member = g_strdup (member);
3211 signal_data->object_path = g_strdup (object_path);
3212 signal_data->arg0 = g_strdup (arg0);
3213 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3214 g_array_append_val (signal_data->subscribers, subscriber);
3216 g_hash_table_insert (connection->map_rule_to_signal_data,
3220 /* Add the match rule to the bus...
3222 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3223 * always send such messages to us.
3225 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3227 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3228 add_match_rule (connection, signal_data->rule);
3231 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3232 signal_data->sender_unique_name);
3233 if (signal_data_array == NULL)
3235 signal_data_array = g_ptr_array_new ();
3236 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3237 g_strdup (signal_data->sender_unique_name),
3240 g_ptr_array_add (signal_data_array, signal_data);
3243 g_hash_table_insert (connection->map_id_to_signal_data,
3244 GUINT_TO_POINTER (subscriber.id),
3247 CONNECTION_UNLOCK (connection);
3249 return subscriber.id;
3252 /* ---------------------------------------------------------------------------------------------------- */
3254 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3256 unsubscribe_id_internal (GDBusConnection *connection,
3257 guint subscription_id,
3258 GArray *out_removed_subscribers)
3260 SignalData *signal_data;
3261 GPtrArray *signal_data_array;
3264 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3265 GUINT_TO_POINTER (subscription_id));
3266 if (signal_data == NULL)
3268 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3272 for (n = 0; n < signal_data->subscribers->len; n++)
3274 SignalSubscriber *subscriber;
3276 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3277 if (subscriber->id != subscription_id)
3280 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3281 GUINT_TO_POINTER (subscription_id)));
3282 g_array_append_val (out_removed_subscribers, *subscriber);
3283 g_array_remove_index (signal_data->subscribers, n);
3285 if (signal_data->subscribers->len == 0)
3287 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3289 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3290 signal_data->sender_unique_name);
3291 g_warn_if_fail (signal_data_array != NULL);
3292 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3294 if (signal_data_array->len == 0)
3296 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3297 signal_data->sender_unique_name));
3300 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3301 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3303 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3304 if (!connection->closed && !connection->finalizing)
3305 remove_match_rule (connection, signal_data->rule);
3307 signal_data_free (signal_data);
3313 g_assert_not_reached ();
3320 * g_dbus_connection_signal_unsubscribe:
3321 * @connection: A #GDBusConnection.
3322 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3324 * Unsubscribes from signals.
3329 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3330 guint subscription_id)
3332 GArray *subscribers;
3335 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3337 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3339 CONNECTION_LOCK (connection);
3340 unsubscribe_id_internal (connection,
3343 CONNECTION_UNLOCK (connection);
3346 g_assert (subscribers->len == 0 || subscribers->len == 1);
3348 /* call GDestroyNotify without lock held */
3349 for (n = 0; n < subscribers->len; n++)
3351 SignalSubscriber *subscriber;
3352 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3353 call_destroy_notify (subscriber->context,
3354 subscriber->user_data_free_func,
3355 subscriber->user_data);
3356 if (subscriber->context != NULL)
3357 g_main_context_unref (subscriber->context);
3360 g_array_free (subscribers, TRUE);
3363 /* ---------------------------------------------------------------------------------------------------- */
3367 guint subscription_id;
3368 GDBusSignalCallback callback;
3370 GDBusMessage *message;
3371 GDBusConnection *connection;
3372 const gchar *sender;
3374 const gchar *interface;
3375 const gchar *member;
3378 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3382 emit_signal_instance_in_idle_cb (gpointer data)
3384 SignalInstance *signal_instance = data;
3385 GVariant *parameters;
3386 gboolean has_subscription;
3388 parameters = g_dbus_message_get_body (signal_instance->message);
3389 if (parameters == NULL)
3391 parameters = g_variant_new ("()");
3392 g_variant_ref_sink (parameters);
3396 g_variant_ref_sink (parameters);
3400 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3401 signal_instance->subscription_id,
3402 signal_instance->sender,
3403 signal_instance->path,
3404 signal_instance->interface,
3405 signal_instance->member,
3406 g_variant_print (parameters, TRUE));
3409 /* Careful here, don't do the callback if we no longer has the subscription */
3410 CONNECTION_LOCK (signal_instance->connection);
3411 has_subscription = FALSE;
3412 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3413 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3414 has_subscription = TRUE;
3415 CONNECTION_UNLOCK (signal_instance->connection);
3417 if (has_subscription)
3418 signal_instance->callback (signal_instance->connection,
3419 signal_instance->sender,
3420 signal_instance->path,
3421 signal_instance->interface,
3422 signal_instance->member,
3424 signal_instance->user_data);
3426 g_variant_unref (parameters);
3432 signal_instance_free (SignalInstance *signal_instance)
3434 g_object_unref (signal_instance->message);
3435 g_object_unref (signal_instance->connection);
3436 g_free (signal_instance);
3439 /* called in message handler thread WITH lock held */
3441 schedule_callbacks (GDBusConnection *connection,
3442 GPtrArray *signal_data_array,
3443 GDBusMessage *message,
3444 const gchar *sender)
3447 const gchar *interface;
3448 const gchar *member;
3457 interface = g_dbus_message_get_interface (message);
3458 member = g_dbus_message_get_member (message);
3459 path = g_dbus_message_get_path (message);
3460 arg0 = g_dbus_message_get_arg0 (message);
3463 g_print ("In schedule_callbacks:\n"
3465 " interface = `%s'\n"
3476 /* TODO: if this is slow, then we can change signal_data_array into
3477 * map_object_path_to_signal_data_array or something.
3479 for (n = 0; n < signal_data_array->len; n++)
3481 SignalData *signal_data = signal_data_array->pdata[n];
3483 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3486 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3489 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3492 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3495 for (m = 0; m < signal_data->subscribers->len; m++)
3497 SignalSubscriber *subscriber;
3498 GSource *idle_source;
3499 SignalInstance *signal_instance;
3501 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3503 signal_instance = g_new0 (SignalInstance, 1);
3504 signal_instance->subscription_id = subscriber->id;
3505 signal_instance->callback = subscriber->callback;
3506 signal_instance->user_data = subscriber->user_data;
3507 signal_instance->message = g_object_ref (message);
3508 signal_instance->connection = g_object_ref (connection);
3509 signal_instance->sender = sender;
3510 signal_instance->path = path;
3511 signal_instance->interface = interface;
3512 signal_instance->member = member;
3514 idle_source = g_idle_source_new ();
3515 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3516 g_source_set_callback (idle_source,
3517 emit_signal_instance_in_idle_cb,
3519 (GDestroyNotify) signal_instance_free);
3520 g_source_attach (idle_source, subscriber->context);
3521 g_source_unref (idle_source);
3526 /* called in message handler thread with lock held */
3528 distribute_signals (GDBusConnection *connection,
3529 GDBusMessage *message)
3531 GPtrArray *signal_data_array;
3532 const gchar *sender;
3534 sender = g_dbus_message_get_sender (message);
3536 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3538 _g_dbus_debug_print_lock ();
3539 g_print ("========================================================================\n"
3540 "GDBus-debug:Signal:\n"
3541 " <<<< RECEIVED SIGNAL %s.%s\n"
3543 " sent by name %s\n",
3544 g_dbus_message_get_interface (message),
3545 g_dbus_message_get_member (message),
3546 g_dbus_message_get_path (message),
3547 sender != NULL ? sender : "(none)");
3548 _g_dbus_debug_print_unlock ();
3551 /* collect subscribers that match on sender */
3554 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3555 if (signal_data_array != NULL)
3556 schedule_callbacks (connection, signal_data_array, message, sender);
3559 /* collect subscribers not matching on sender */
3560 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3561 if (signal_data_array != NULL)
3562 schedule_callbacks (connection, signal_data_array, message, sender);
3565 /* ---------------------------------------------------------------------------------------------------- */
3567 /* only called from finalize(), removes all subscriptions */
3569 purge_all_signal_subscriptions (GDBusConnection *connection)
3571 GHashTableIter iter;
3574 GArray *subscribers;
3577 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3578 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3579 while (g_hash_table_iter_next (&iter, &key, NULL))
3581 guint subscription_id = GPOINTER_TO_UINT (key);
3582 g_array_append_val (ids, subscription_id);
3585 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3586 for (n = 0; n < ids->len; n++)
3588 guint subscription_id = g_array_index (ids, guint, n);
3589 unsubscribe_id_internal (connection,
3593 g_array_free (ids, TRUE);
3595 /* call GDestroyNotify without lock held */
3596 for (n = 0; n < subscribers->len; n++)
3598 SignalSubscriber *subscriber;
3599 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3600 call_destroy_notify (subscriber->context,
3601 subscriber->user_data_free_func,
3602 subscriber->user_data);
3603 if (subscriber->context != NULL)
3604 g_main_context_unref (subscriber->context);
3607 g_array_free (subscribers, TRUE);
3610 /* ---------------------------------------------------------------------------------------------------- */
3612 static GDBusInterfaceVTable *
3613 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3615 /* Don't waste memory by copying padding - remember to update this
3616 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3618 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3622 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3627 /* ---------------------------------------------------------------------------------------------------- */
3629 static GDBusSubtreeVTable *
3630 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3632 /* Don't waste memory by copying padding - remember to update this
3633 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3635 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3639 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3644 /* ---------------------------------------------------------------------------------------------------- */
3646 struct ExportedObject
3649 GDBusConnection *connection;
3651 /* maps gchar* -> ExportedInterface* */
3652 GHashTable *map_if_name_to_ei;
3655 /* only called with lock held */
3657 exported_object_free (ExportedObject *eo)
3659 g_free (eo->object_path);
3660 g_hash_table_unref (eo->map_if_name_to_ei);
3669 gchar *interface_name;
3670 GDBusInterfaceVTable *vtable;
3671 GDBusInterfaceInfo *interface_info;
3673 GMainContext *context;
3675 GDestroyNotify user_data_free_func;
3676 } ExportedInterface;
3678 /* called with lock held */
3680 exported_interface_free (ExportedInterface *ei)
3682 g_dbus_interface_info_cache_release (ei->interface_info);
3683 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3685 call_destroy_notify (ei->context,
3686 ei->user_data_free_func,
3689 if (ei->context != NULL)
3690 g_main_context_unref (ei->context);
3692 g_free (ei->interface_name);
3693 _g_dbus_interface_vtable_free (ei->vtable);
3697 /* ---------------------------------------------------------------------------------------------------- */
3699 /* Convenience function to check if @registration_id (if not zero) or
3700 * @subtree_registration_id (if not zero) has been unregistered. If
3701 * so, returns %TRUE.
3703 * Caller must *not* hold lock.
3706 has_object_been_unregistered (GDBusConnection *connection,
3707 guint registration_id,
3708 guint subtree_registration_id)
3712 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3716 CONNECTION_LOCK (connection);
3717 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3718 GUINT_TO_POINTER (registration_id)) == NULL)
3722 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3723 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3727 CONNECTION_UNLOCK (connection);
3732 /* ---------------------------------------------------------------------------------------------------- */
3736 GDBusConnection *connection;
3737 GDBusMessage *message;
3739 const gchar *property_name;
3740 const GDBusInterfaceVTable *vtable;
3741 GDBusInterfaceInfo *interface_info;
3742 const GDBusPropertyInfo *property_info;
3743 guint registration_id;
3744 guint subtree_registration_id;
3748 property_data_free (PropertyData *data)
3750 g_object_unref (data->connection);
3751 g_object_unref (data->message);
3755 /* called in thread where object was registered - no locks held */
3757 invoke_get_property_in_idle_cb (gpointer _data)
3759 PropertyData *data = _data;
3762 GDBusMessage *reply;
3764 if (has_object_been_unregistered (data->connection,
3765 data->registration_id,
3766 data->subtree_registration_id))
3768 reply = g_dbus_message_new_method_error (data->message,
3769 "org.freedesktop.DBus.Error.UnknownMethod",
3770 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3771 g_dbus_message_get_path (data->message));
3772 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3773 g_object_unref (reply);
3778 value = data->vtable->get_property (data->connection,
3779 g_dbus_message_get_sender (data->message),
3780 g_dbus_message_get_path (data->message),
3781 data->interface_info->name,
3782 data->property_name,
3789 g_assert_no_error (error);
3791 g_variant_take_ref (value);
3792 reply = g_dbus_message_new_method_reply (data->message);
3793 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3794 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3795 g_variant_unref (value);
3796 g_object_unref (reply);
3800 gchar *dbus_error_name;
3801 g_assert (error != NULL);
3802 dbus_error_name = g_dbus_error_encode_gerror (error);
3803 reply = g_dbus_message_new_method_error_literal (data->message,
3806 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3807 g_free (dbus_error_name);
3808 g_error_free (error);
3809 g_object_unref (reply);
3816 /* called in thread where object was registered - no locks held */
3818 invoke_set_property_in_idle_cb (gpointer _data)
3820 PropertyData *data = _data;
3822 GDBusMessage *reply;
3828 g_variant_get (g_dbus_message_get_body (data->message),
3834 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3835 * of the given value is wrong
3837 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3839 reply = g_dbus_message_new_method_error (data->message,
3840 "org.freedesktop.DBus.Error.InvalidArgs",
3841 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3842 data->property_info->name,
3843 data->property_info->signature,
3844 g_variant_get_type_string (value));
3848 if (!data->vtable->set_property (data->connection,
3849 g_dbus_message_get_sender (data->message),
3850 g_dbus_message_get_path (data->message),
3851 data->interface_info->name,
3852 data->property_name,
3857 gchar *dbus_error_name;
3858 g_assert (error != NULL);
3859 dbus_error_name = g_dbus_error_encode_gerror (error);
3860 reply = g_dbus_message_new_method_error_literal (data->message,
3863 g_free (dbus_error_name);
3864 g_error_free (error);
3868 reply = g_dbus_message_new_method_reply (data->message);
3872 g_assert (reply != NULL);
3873 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3874 g_object_unref (reply);
3875 g_variant_unref (value);
3880 /* called with lock held */
3882 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3883 GDBusMessage *message,
3884 guint registration_id,
3885 guint subtree_registration_id,
3887 GDBusInterfaceInfo *interface_info,
3888 const GDBusInterfaceVTable *vtable,
3889 GMainContext *main_context,
3893 const char *interface_name;
3894 const char *property_name;
3895 const GDBusPropertyInfo *property_info;
3896 GSource *idle_source;
3897 PropertyData *property_data;
3898 GDBusMessage *reply;
3903 g_variant_get (g_dbus_message_get_body (message),
3908 g_variant_get (g_dbus_message_get_body (message),
3917 if (vtable == NULL || vtable->get_property == NULL)
3922 if (vtable == NULL || vtable->set_property == NULL)
3926 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3928 property_info = NULL;
3930 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3931 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3932 if (property_info == NULL)
3934 reply = g_dbus_message_new_method_error (message,
3935 "org.freedesktop.DBus.Error.InvalidArgs",
3936 _("No such property `%s'"),
3938 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3939 g_object_unref (reply);
3944 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3946 reply = g_dbus_message_new_method_error (message,
3947 "org.freedesktop.DBus.Error.InvalidArgs",
3948 _("Property `%s' is not readable"),
3950 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3951 g_object_unref (reply);
3955 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3957 reply = g_dbus_message_new_method_error (message,
3958 "org.freedesktop.DBus.Error.InvalidArgs",
3959 _("Property `%s' is not writable"),
3961 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3962 g_object_unref (reply);
3967 /* ok, got the property info - call user code in an idle handler */
3968 property_data = g_new0 (PropertyData, 1);
3969 property_data->connection = g_object_ref (connection);
3970 property_data->message = g_object_ref (message);
3971 property_data->user_data = user_data;
3972 property_data->property_name = property_name;
3973 property_data->vtable = vtable;
3974 property_data->interface_info = interface_info;
3975 property_data->property_info = property_info;
3976 property_data->registration_id = registration_id;
3977 property_data->subtree_registration_id = subtree_registration_id;
3979 idle_source = g_idle_source_new ();
3980 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3981 g_source_set_callback (idle_source,
3982 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3984 (GDestroyNotify) property_data_free);
3985 g_source_attach (idle_source, main_context);
3986 g_source_unref (idle_source);
3994 /* called with lock held */
3996 handle_getset_property (GDBusConnection *connection,
3998 GDBusMessage *message,
4001 ExportedInterface *ei;
4003 const char *interface_name;
4004 const char *property_name;
4009 g_variant_get (g_dbus_message_get_body (message),
4014 g_variant_get (g_dbus_message_get_body (message),
4020 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4021 * no such interface registered
4023 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4026 GDBusMessage *reply;
4027 reply = g_dbus_message_new_method_error (message,
4028 "org.freedesktop.DBus.Error.InvalidArgs",
4029 _("No such interface `%s'"),
4031 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4032 g_object_unref (reply);
4037 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4050 /* ---------------------------------------------------------------------------------------------------- */
4054 GDBusConnection *connection;
4055 GDBusMessage *message;
4057 const GDBusInterfaceVTable *vtable;
4058 GDBusInterfaceInfo *interface_info;
4059 guint registration_id;
4060 guint subtree_registration_id;
4061 } PropertyGetAllData;
4064 property_get_all_data_free (PropertyData *data)
4066 g_object_unref (data->connection);
4067 g_object_unref (data->message);
4071 /* called in thread where object was registered - no locks held */
4073 invoke_get_all_properties_in_idle_cb (gpointer _data)
4075 PropertyGetAllData *data = _data;
4076 GVariantBuilder builder;
4077 GDBusMessage *reply;
4080 if (has_object_been_unregistered (data->connection,
4081 data->registration_id,
4082 data->subtree_registration_id))
4084 reply = g_dbus_message_new_method_error (data->message,
4085 "org.freedesktop.DBus.Error.UnknownMethod",
4086 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4087 g_dbus_message_get_path (data->message));
4088 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4089 g_object_unref (reply);
4093 /* TODO: Right now we never fail this call - we just omit values if
4094 * a get_property() call is failing.
4096 * We could fail the whole call if just a single get_property() call
4097 * returns an error. We need clarification in the D-Bus spec about this.
4099 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4100 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4101 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4103 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4106 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4109 value = data->vtable->get_property (data->connection,
4110 g_dbus_message_get_sender (data->message),
4111 g_dbus_message_get_path (data->message),
4112 data->interface_info->name,
4113 property_info->name,
4120 g_variant_take_ref (value);
4121 g_variant_builder_add (&builder,
4123 property_info->name,
4125 g_variant_unref (value);
4127 g_variant_builder_close (&builder);
4129 reply = g_dbus_message_new_method_reply (data->message);
4130 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4131 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4132 g_object_unref (reply);
4138 /* called with lock held */
4140 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4141 GDBusMessage *message,
4142 guint registration_id,
4143 guint subtree_registration_id,
4144 GDBusInterfaceInfo *interface_info,
4145 const GDBusInterfaceVTable *vtable,
4146 GMainContext *main_context,
4150 const char *interface_name;
4151 GSource *idle_source;
4152 PropertyGetAllData *property_get_all_data;
4156 g_variant_get (g_dbus_message_get_body (message),
4160 if (vtable == NULL || vtable->get_property == NULL)
4163 /* ok, got the property info - call user in an idle handler */
4164 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4165 property_get_all_data->connection = g_object_ref (connection);
4166 property_get_all_data->message = g_object_ref (message);
4167 property_get_all_data->user_data = user_data;
4168 property_get_all_data->vtable = vtable;
4169 property_get_all_data->interface_info = interface_info;
4170 property_get_all_data->registration_id = registration_id;
4171 property_get_all_data->subtree_registration_id = subtree_registration_id;
4173 idle_source = g_idle_source_new ();
4174 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4175 g_source_set_callback (idle_source,
4176 invoke_get_all_properties_in_idle_cb,
4177 property_get_all_data,
4178 (GDestroyNotify) property_get_all_data_free);
4179 g_source_attach (idle_source, main_context);
4180 g_source_unref (idle_source);
4188 /* called with lock held */
4190 handle_get_all_properties (GDBusConnection *connection,
4192 GDBusMessage *message)
4194 ExportedInterface *ei;
4196 const char *interface_name;
4200 g_variant_get (g_dbus_message_get_body (message),
4204 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4205 * no such interface registered
4207 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4210 GDBusMessage *reply;
4211 reply = g_dbus_message_new_method_error (message,
4212 "org.freedesktop.DBus.Error.InvalidArgs",
4213 _("No such interface"),
4215 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4216 g_object_unref (reply);
4221 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4233 /* ---------------------------------------------------------------------------------------------------- */
4235 static const gchar introspect_header[] =
4236 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4237 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4238 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4241 static const gchar introspect_tail[] =
4244 static const gchar introspect_properties_interface[] =
4245 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4246 " <method name=\"Get\">\n"
4247 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4248 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4249 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4251 " <method name=\"GetAll\">\n"
4252 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4253 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4255 " <method name=\"Set\">\n"
4256 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4257 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4258 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4260 " <signal name=\"PropertiesChanged\">\n"
4261 " <arg type=\"s\" name=\"interface_name\"/>\n"
4262 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4263 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4267 static const gchar introspect_introspectable_interface[] =
4268 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4269 " <method name=\"Introspect\">\n"
4270 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4273 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4274 " <method name=\"Ping\"/>\n"
4275 " <method name=\"GetMachineId\">\n"
4276 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4281 introspect_append_header (GString *s)
4283 g_string_append (s, introspect_header);
4287 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4289 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4295 begin = object_path + path_len;
4296 end = strchr (begin, '/');
4298 s = g_strndup (begin, end - begin);
4300 s = g_strdup (begin);
4302 if (g_hash_table_lookup (set, s) == NULL)
4303 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4309 /* TODO: we want a nicer public interface for this */
4311 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4316 GHashTableIter hash_iter;
4317 const gchar *object_path;
4323 CONNECTION_ENSURE_LOCK (connection);
4325 path_len = strlen (path);
4329 set = g_hash_table_new (g_str_hash, g_str_equal);
4331 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4332 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4333 maybe_add_path (path, path_len, object_path, set);
4335 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4336 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4337 maybe_add_path (path, path_len, object_path, set);
4339 p = g_ptr_array_new ();
4340 keys = g_hash_table_get_keys (set);
4341 for (l = keys; l != NULL; l = l->next)
4342 g_ptr_array_add (p, l->data);
4343 g_hash_table_unref (set);
4346 g_ptr_array_add (p, NULL);
4347 ret = (gchar **) g_ptr_array_free (p, FALSE);
4352 g_dbus_connection_list_registered (GDBusConnection *connection,
4356 CONNECTION_LOCK (connection);
4357 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4358 CONNECTION_UNLOCK (connection);
4362 /* called in message handler thread with lock held */
4364 handle_introspect (GDBusConnection *connection,
4366 GDBusMessage *message)
4370 GDBusMessage *reply;
4371 GHashTableIter hash_iter;
4372 ExportedInterface *ei;
4375 /* first the header with the standard interfaces */
4376 s = g_string_sized_new (sizeof (introspect_header) +
4377 sizeof (introspect_properties_interface) +
4378 sizeof (introspect_introspectable_interface) +
4379 sizeof (introspect_tail));
4380 introspect_append_header (s);
4381 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4382 "org.freedesktop.DBus.Properties"))
4383 g_string_append (s, introspect_properties_interface);
4385 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4386 "org.freedesktop.DBus.Introspectable"))
4387 g_string_append (s, introspect_introspectable_interface);
4389 /* then include the registered interfaces */
4390 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4391 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4392 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4394 /* finally include nodes registered below us */
4395 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4396 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4397 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4398 g_strfreev (registered);
4399 g_string_append (s, introspect_tail);
4401 reply = g_dbus_message_new_method_reply (message);
4402 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4403 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4404 g_object_unref (reply);
4405 g_string_free (s, TRUE);
4410 /* called in thread where object was registered - no locks held */
4412 call_in_idle_cb (gpointer user_data)
4414 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4415 GDBusInterfaceVTable *vtable;
4416 guint registration_id;
4417 guint subtree_registration_id;
4419 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4420 g_assert (vtable != NULL && vtable->method_call != NULL);
4422 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4423 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4425 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4427 subtree_registration_id))
4429 GDBusMessage *reply;
4430 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4431 "org.freedesktop.DBus.Error.UnknownMethod",
4432 _("No such interface `%s' on object at path %s"),
4433 g_dbus_method_invocation_get_interface_name (invocation),
4434 g_dbus_method_invocation_get_object_path (invocation));
4435 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4436 g_object_unref (reply);
4440 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4441 g_dbus_method_invocation_get_sender (invocation),
4442 g_dbus_method_invocation_get_object_path (invocation),
4443 g_dbus_method_invocation_get_interface_name (invocation),
4444 g_dbus_method_invocation_get_method_name (invocation),
4445 g_dbus_method_invocation_get_parameters (invocation),
4446 g_object_ref (invocation),
4447 g_dbus_method_invocation_get_user_data (invocation));
4453 /* called in message handler thread with lock held */
4455 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4456 GDBusMessage *message,
4457 guint registration_id,
4458 guint subtree_registration_id,
4459 GDBusInterfaceInfo *interface_info,
4460 const GDBusInterfaceVTable *vtable,
4461 GMainContext *main_context,
4464 GDBusMethodInvocation *invocation;
4465 const GDBusMethodInfo *method_info;
4466 GDBusMessage *reply;
4467 GVariant *parameters;
4468 GSource *idle_source;
4470 GVariantType *in_type;
4474 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4475 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4477 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4478 * error to the caller
4480 if (method_info == NULL)
4482 reply = g_dbus_message_new_method_error (message,
4483 "org.freedesktop.DBus.Error.UnknownMethod",
4484 _("No such method `%s'"),
4485 g_dbus_message_get_member (message));
4486 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4487 g_object_unref (reply);
4492 parameters = g_dbus_message_get_body (message);
4493 if (parameters == NULL)
4495 parameters = g_variant_new ("()");
4496 g_variant_ref_sink (parameters);
4500 g_variant_ref (parameters);
4503 /* Check that the incoming args are of the right type - if they are not, return
4504 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4506 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4507 if (!g_variant_is_of_type (parameters, in_type))
4511 type_string = g_variant_type_dup_string (in_type);
4513 reply = g_dbus_message_new_method_error (message,
4514 "org.freedesktop.DBus.Error.InvalidArgs",
4515 _("Type of message, `%s', does not match expected type `%s'"),
4516 g_variant_get_type_string (parameters),
4518 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4519 g_variant_type_free (in_type);
4520 g_variant_unref (parameters);
4521 g_object_unref (reply);
4522 g_free (type_string);
4526 g_variant_type_free (in_type);
4528 /* schedule the call in idle */
4529 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4530 g_dbus_message_get_path (message),
4531 g_dbus_message_get_interface (message),
4532 g_dbus_message_get_member (message),
4538 g_variant_unref (parameters);
4540 /* TODO: would be nicer with a real MethodData like we already
4541 * have PropertyData and PropertyGetAllData... */
4542 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4543 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4544 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4546 idle_source = g_idle_source_new ();
4547 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4548 g_source_set_callback (idle_source,
4552 g_source_attach (idle_source, main_context);
4553 g_source_unref (idle_source);
4561 /* ---------------------------------------------------------------------------------------------------- */
4563 /* called in message handler thread with lock held */
4565 obj_message_func (GDBusConnection *connection,
4567 GDBusMessage *message)
4569 const gchar *interface_name;
4570 const gchar *member;
4571 const gchar *signature;
4576 interface_name = g_dbus_message_get_interface (message);
4577 member = g_dbus_message_get_member (message);
4578 signature = g_dbus_message_get_signature (message);
4580 /* see if we have an interface for handling this call */
4581 if (interface_name != NULL)
4583 ExportedInterface *ei;
4584 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4587 /* we do - invoke the handler in idle in the right thread */
4589 /* handle no vtable or handler being present */
4590 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4593 handled = validate_and_maybe_schedule_method_call (connection,
4605 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4606 g_strcmp0 (member, "Introspect") == 0 &&
4607 g_strcmp0 (signature, "") == 0)
4609 handled = handle_introspect (connection, eo, message);
4612 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4613 g_strcmp0 (member, "Get") == 0 &&
4614 g_strcmp0 (signature, "ss") == 0)
4616 handled = handle_getset_property (connection, eo, message, TRUE);
4619 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4620 g_strcmp0 (member, "Set") == 0 &&
4621 g_strcmp0 (signature, "ssv") == 0)
4623 handled = handle_getset_property (connection, eo, message, FALSE);
4626 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4627 g_strcmp0 (member, "GetAll") == 0 &&
4628 g_strcmp0 (signature, "s") == 0)
4630 handled = handle_get_all_properties (connection, eo, message);
4639 * g_dbus_connection_register_object:
4640 * @connection: A #GDBusConnection.
4641 * @object_path: The object path to register at.
4642 * @interface_info: Introspection data for the interface.
4643 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4644 * @user_data: (allow-none): Data to pass to functions in @vtable.
4645 * @user_data_free_func: Function to call when the object path is unregistered.
4646 * @error: Return location for error or %NULL.
4648 * Registers callbacks for exported objects at @object_path with the
4649 * D-Bus interface that is described in @interface_info.
4651 * Calls to functions in @vtable (and @user_data_free_func) will
4652 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4653 * loop</link> of the thread you are calling this method from.
4655 * Note that all #GVariant values passed to functions in @vtable will match
4656 * the signature given in @interface_info - if a remote caller passes
4657 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4658 * is returned to the remote caller.
4660 * Additionally, if the remote caller attempts to invoke methods or
4661 * access properties not mentioned in @interface_info the
4662 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4663 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4664 * are returned to the caller.
4666 * It is considered a programming error if the
4667 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4668 * #GVariant of incorrect type.
4670 * If an existing callback is already registered at @object_path and
4671 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4673 * GDBus automatically implements the standard D-Bus interfaces
4674 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4675 * and org.freedesktop.Peer, so you don't have to implement those for
4676 * the objects you export. You <emphasis>can</emphasis> implement
4677 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4678 * and setting of properties asynchronously.
4680 * Note that the reference count on @interface_info will be
4681 * incremented by 1 (unless allocated statically, e.g. if the
4682 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4683 * as the object is exported. Also note that @vtable will be copied.
4685 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4687 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4688 * that can be used with g_dbus_connection_unregister_object() .
4693 g_dbus_connection_register_object (GDBusConnection *connection,
4694 const gchar *object_path,
4695 GDBusInterfaceInfo *interface_info,
4696 const GDBusInterfaceVTable *vtable,
4698 GDestroyNotify user_data_free_func,
4702 ExportedInterface *ei;
4705 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4706 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4707 g_return_val_if_fail (interface_info != NULL, 0);
4708 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4709 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4713 CONNECTION_LOCK (connection);
4715 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4718 eo = g_new0 (ExportedObject, 1);
4719 eo->object_path = g_strdup (object_path);
4720 eo->connection = connection;
4721 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4724 (GDestroyNotify) exported_interface_free);
4725 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4728 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4734 _("An object is already exported for the interface %s at %s"),
4735 interface_info->name,
4740 ei = g_new0 (ExportedInterface, 1);
4741 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4743 ei->user_data = user_data;
4744 ei->user_data_free_func = user_data_free_func;
4745 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4746 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4747 g_dbus_interface_info_cache_build (ei->interface_info);
4748 ei->interface_name = g_strdup (interface_info->name);
4749 ei->context = g_main_context_get_thread_default ();
4750 if (ei->context != NULL)
4751 g_main_context_ref (ei->context);
4753 g_hash_table_insert (eo->map_if_name_to_ei,
4754 (gpointer) ei->interface_name,
4756 g_hash_table_insert (connection->map_id_to_ei,
4757 GUINT_TO_POINTER (ei->id),
4763 CONNECTION_UNLOCK (connection);
4769 * g_dbus_connection_unregister_object:
4770 * @connection: A #GDBusConnection.
4771 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4773 * Unregisters an object.
4775 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4780 g_dbus_connection_unregister_object (GDBusConnection *connection,
4781 guint registration_id)
4783 ExportedInterface *ei;
4787 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4791 CONNECTION_LOCK (connection);
4793 ei = g_hash_table_lookup (connection->map_id_to_ei,
4794 GUINT_TO_POINTER (registration_id));
4800 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4801 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4802 /* unregister object path if we have no more exported interfaces */
4803 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4804 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4810 CONNECTION_UNLOCK (connection);
4815 /* ---------------------------------------------------------------------------------------------------- */
4818 * g_dbus_connection_emit_signal:
4819 * @connection: A #GDBusConnection.
4820 * @destination_bus_name: (allow-none): The unique bus name for the destination
4821 * for the signal or %NULL to emit to all listeners.
4822 * @object_path: Path of remote object.
4823 * @interface_name: D-Bus interface to emit a signal on.
4824 * @signal_name: The name of the signal to emit.
4825 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
4826 * or %NULL if not passing parameters.
4827 * @error: Return location for error or %NULL.
4831 * If the parameters GVariant is floating, it is consumed.
4833 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4835 * Returns: %TRUE unless @error is set.
4840 g_dbus_connection_emit_signal (GDBusConnection *connection,
4841 const gchar *destination_bus_name,
4842 const gchar *object_path,
4843 const gchar *interface_name,
4844 const gchar *signal_name,
4845 GVariant *parameters,
4848 GDBusMessage *message;
4854 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4855 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4856 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4857 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4858 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4859 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4861 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4863 _g_dbus_debug_print_lock ();
4864 g_print ("========================================================================\n"
4865 "GDBus-debug:Emission:\n"
4866 " >>>> SIGNAL EMISSION %s.%s()\n"
4868 " destination %s\n",
4869 interface_name, signal_name,
4871 destination_bus_name != NULL ? destination_bus_name : "(none)");
4872 _g_dbus_debug_print_unlock ();
4875 message = g_dbus_message_new_signal (object_path,
4879 if (destination_bus_name != NULL)
4880 g_dbus_message_set_header (message,
4881 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4882 g_variant_new_string (destination_bus_name));
4884 if (parameters != NULL)
4885 g_dbus_message_set_body (message, parameters);
4887 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4888 g_object_unref (message);
4894 add_call_flags (GDBusMessage *message,
4895 GDBusCallFlags flags)
4897 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4898 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4902 decode_method_reply (GDBusMessage *reply,
4903 const gchar *method_name,
4904 const GVariantType *reply_type,
4905 GUnixFDList **out_fd_list,
4911 switch (g_dbus_message_get_message_type (reply))
4913 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4914 result = g_dbus_message_get_body (reply);
4917 result = g_variant_new ("()");
4918 g_variant_ref_sink (result);
4922 g_variant_ref (result);
4925 if (!g_variant_is_of_type (result, reply_type))
4927 gchar *type_string = g_variant_type_dup_string (reply_type);
4931 G_IO_ERROR_INVALID_ARGUMENT,
4932 _("Method `%s' returned type `%s', but expected `%s'"),
4933 method_name, g_variant_get_type_string (result), type_string);
4935 g_variant_unref (result);
4936 g_free (type_string);
4943 if (out_fd_list != NULL)
4945 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
4946 if (*out_fd_list != NULL)
4947 g_object_ref (*out_fd_list);
4953 case G_DBUS_MESSAGE_TYPE_ERROR:
4954 g_dbus_message_to_gerror (reply, error);
4958 g_assert_not_reached ();
4968 GSimpleAsyncResult *simple;
4969 GVariantType *reply_type;
4970 gchar *method_name; /* for error message */
4974 GUnixFDList *fd_list;
4978 call_state_free (CallState *state)
4980 g_variant_type_free (state->reply_type);
4981 g_free (state->method_name);
4983 if (state->value != NULL)
4984 g_variant_unref (state->value);
4985 if (state->fd_list != NULL)
4986 g_object_unref (state->fd_list);
4987 g_slice_free (CallState, state);
4991 g_dbus_connection_call_done (GObject *source,
4992 GAsyncResult *result,
4995 GSimpleAsyncResult *simple;
4996 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4997 CallState *state = user_data;
4999 GDBusMessage *reply;
5002 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5006 if (G_UNLIKELY (_g_dbus_debug_call ()))
5008 _g_dbus_debug_print_lock ();
5009 g_print ("========================================================================\n"
5010 "GDBus-debug:Call:\n"
5011 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5017 g_print ("SUCCESS\n");
5021 g_print ("FAILED: %s\n",
5024 _g_dbus_debug_print_unlock ();
5028 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5030 simple = state->simple; /* why? because state is freed before we unref simple.. */
5033 g_simple_async_result_take_error (state->simple, error);
5034 g_simple_async_result_complete (state->simple);
5035 call_state_free (state);
5039 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5040 g_simple_async_result_complete (state->simple);
5041 g_object_unref (reply);
5043 g_object_unref (simple);
5047 g_dbus_connection_call_internal (GDBusConnection *connection,
5048 const gchar *bus_name,
5049 const gchar *object_path,
5050 const gchar *interface_name,
5051 const gchar *method_name,
5052 GVariant *parameters,
5053 const GVariantType *reply_type,
5054 GDBusCallFlags flags,
5056 GUnixFDList *fd_list,
5057 GCancellable *cancellable,
5058 GAsyncReadyCallback callback,
5061 GDBusMessage *message;
5064 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5065 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5066 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5067 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5068 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5069 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5070 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5072 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5074 g_return_if_fail (fd_list == NULL);
5077 state = g_slice_new0 (CallState);
5078 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5079 callback, user_data,
5080 g_dbus_connection_call_internal);
5081 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5083 if (reply_type == NULL)
5084 reply_type = G_VARIANT_TYPE_ANY;
5086 state->reply_type = g_variant_type_copy (reply_type);
5088 message = g_dbus_message_new_method_call (bus_name,
5092 add_call_flags (message, flags);
5093 if (parameters != NULL)
5094 g_dbus_message_set_body (message, parameters);
5097 if (fd_list != NULL)
5098 g_dbus_message_set_unix_fd_list (message, fd_list);
5101 g_dbus_connection_send_message_with_reply (connection,
5103 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5107 g_dbus_connection_call_done,
5110 if (G_UNLIKELY (_g_dbus_debug_call ()))
5112 _g_dbus_debug_print_lock ();
5113 g_print ("========================================================================\n"
5114 "GDBus-debug:Call:\n"
5115 " >>>> ASYNC %s.%s()\n"
5117 " owned by name %s (serial %d)\n",
5121 bus_name != NULL ? bus_name : "(none)",
5123 _g_dbus_debug_print_unlock ();
5126 if (message != NULL)
5127 g_object_unref (message);
5131 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5132 GUnixFDList **out_fd_list,
5136 GSimpleAsyncResult *simple;
5139 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5140 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5141 g_dbus_connection_call_internal), NULL);
5142 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5144 simple = G_SIMPLE_ASYNC_RESULT (res);
5146 if (g_simple_async_result_propagate_error (simple, error))
5149 state = g_simple_async_result_get_op_res_gpointer (simple);
5150 if (out_fd_list != NULL)
5151 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5152 return g_variant_ref (state->value);
5156 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5157 const gchar *bus_name,
5158 const gchar *object_path,
5159 const gchar *interface_name,
5160 const gchar *method_name,
5161 GVariant *parameters,
5162 const GVariantType *reply_type,
5163 GDBusCallFlags flags,
5165 GUnixFDList *fd_list,
5166 GUnixFDList **out_fd_list,
5167 GCancellable *cancellable,
5170 GDBusMessage *message;
5171 GDBusMessage *reply;
5173 GError *local_error;
5179 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5180 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5181 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5182 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5183 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5184 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5185 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5187 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5189 g_return_val_if_fail (fd_list == NULL, NULL);
5191 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5193 if (reply_type == NULL)
5194 reply_type = G_VARIANT_TYPE_ANY;
5196 message = g_dbus_message_new_method_call (bus_name,
5200 add_call_flags (message, flags);
5201 if (parameters != NULL)
5202 g_dbus_message_set_body (message, parameters);
5205 if (fd_list != NULL)
5206 g_dbus_message_set_unix_fd_list (message, fd_list);
5209 if (G_UNLIKELY (_g_dbus_debug_call ()))
5211 _g_dbus_debug_print_lock ();
5212 g_print ("========================================================================\n"
5213 "GDBus-debug:Call:\n"
5214 " >>>> SYNC %s.%s()\n"
5216 " owned by name %s\n",
5220 bus_name != NULL ? bus_name : "(none)");
5221 _g_dbus_debug_print_unlock ();
5225 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5227 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5229 NULL, /* volatile guint32 *out_serial */
5233 if (G_UNLIKELY (_g_dbus_debug_call ()))
5235 _g_dbus_debug_print_lock ();
5236 g_print ("========================================================================\n"
5237 "GDBus-debug:Call:\n"
5238 " <<<< SYNC COMPLETE %s.%s()\n"
5244 g_print ("SUCCESS\n");
5248 g_print ("FAILED: %s\n",
5249 local_error->message);
5251 _g_dbus_debug_print_unlock ();
5257 *error = local_error;
5259 g_error_free (local_error);
5263 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5266 if (message != NULL)
5267 g_object_unref (message);
5269 g_object_unref (reply);
5274 /* ---------------------------------------------------------------------------------------------------- */
5277 * g_dbus_connection_call:
5278 * @connection: A #GDBusConnection.
5279 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5280 * @connection is not a message bus connection.
5281 * @object_path: Path of remote object.
5282 * @interface_name: D-Bus interface to invoke method on.
5283 * @method_name: The name of the method to invoke.
5284 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5285 * or %NULL if not passing parameters.
5286 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5287 * @flags: Flags from the #GDBusCallFlags enumeration.
5288 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5289 * timeout or %G_MAXINT for no timeout.
5290 * @cancellable: A #GCancellable or %NULL.
5291 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5292 * satisfied or %NULL if you don't * care about the result of the
5293 * method invocation.
5294 * @user_data: The data to pass to @callback.
5296 * Asynchronously invokes the @method_name method on the
5297 * @interface_name D-Bus interface on the remote object at
5298 * @object_path owned by @bus_name.
5300 * If @connection is closed then the operation will fail with
5301 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5302 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5303 * not compatible with the D-Bus protocol, the operation fails with
5304 * %G_IO_ERROR_INVALID_ARGUMENT.
5306 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5307 * error will be raised if it does not match. Said another way, if you give a @reply_type
5308 * then any non-%NULL return value will be of this type.
5310 * If the @parameters #GVariant is floating, it is consumed. This allows
5311 * convenient 'inline' use of g_variant_new(), e.g.:
5313 * g_dbus_connection_call (connection,
5314 * "org.freedesktop.StringThings",
5315 * "/org/freedesktop/StringThings",
5316 * "org.freedesktop.StringThings",
5318 * g_variant_new ("(ss)",
5322 * G_DBUS_CALL_FLAGS_NONE,
5325 * (GAsyncReadyCallback) two_strings_done,
5329 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5330 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5331 * of the thread you are calling this method from. You can then call
5332 * g_dbus_connection_call_finish() to get the result of the operation.
5333 * See g_dbus_connection_call_sync() for the synchronous version of this
5339 g_dbus_connection_call (GDBusConnection *connection,
5340 const gchar *bus_name,
5341 const gchar *object_path,
5342 const gchar *interface_name,
5343 const gchar *method_name,
5344 GVariant *parameters,
5345 const GVariantType *reply_type,
5346 GDBusCallFlags flags,
5348 GCancellable *cancellable,
5349 GAsyncReadyCallback callback,
5352 return g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, cancellable, callback, user_data);
5356 * g_dbus_connection_call_finish:
5357 * @connection: A #GDBusConnection.
5358 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5359 * @error: Return location for error or %NULL.
5361 * Finishes an operation started with g_dbus_connection_call().
5363 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5364 * return values. Free with g_variant_unref().
5369 g_dbus_connection_call_finish (GDBusConnection *connection,
5373 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5377 * g_dbus_connection_call_sync:
5378 * @connection: A #GDBusConnection.
5379 * @bus_name: A unique or well-known bus name.
5380 * @object_path: Path of remote object.
5381 * @interface_name: D-Bus interface to invoke method on.
5382 * @method_name: The name of the method to invoke.
5383 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5384 * or %NULL if not passing parameters.
5385 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5386 * @flags: Flags from the #GDBusCallFlags enumeration.
5387 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5388 * timeout or %G_MAXINT for no timeout.
5389 * @cancellable: A #GCancellable or %NULL.
5390 * @error: Return location for error or %NULL.
5392 * Synchronously invokes the @method_name method on the
5393 * @interface_name D-Bus interface on the remote object at
5394 * @object_path owned by @bus_name.
5396 * If @connection is closed then the operation will fail with
5397 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5398 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5399 * contains a value not compatible with the D-Bus protocol, the operation
5400 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5402 * If @reply_type is non-%NULL then the reply will be checked for having
5403 * this type and an error will be raised if it does not match. Said
5404 * another way, if you give a @reply_type then any non-%NULL return
5405 * value will be of this type.
5407 * If the @parameters #GVariant is floating, it is consumed.
5408 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5410 * g_dbus_connection_call_sync (connection,
5411 * "org.freedesktop.StringThings",
5412 * "/org/freedesktop/StringThings",
5413 * "org.freedesktop.StringThings",
5415 * g_variant_new ("(ss)",
5419 * G_DBUS_CALL_FLAGS_NONE,
5425 * The calling thread is blocked until a reply is received. See
5426 * g_dbus_connection_call() for the asynchronous version of
5429 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5430 * return values. Free with g_variant_unref().
5435 g_dbus_connection_call_sync (GDBusConnection *connection,
5436 const gchar *bus_name,
5437 const gchar *object_path,
5438 const gchar *interface_name,
5439 const gchar *method_name,
5440 GVariant *parameters,
5441 const GVariantType *reply_type,
5442 GDBusCallFlags flags,
5444 GCancellable *cancellable,
5447 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, NULL, cancellable, error);
5450 /* ---------------------------------------------------------------------------------------------------- */
5455 * g_dbus_connection_call_with_unix_fd_list:
5456 * @connection: A #GDBusConnection.
5457 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5458 * @connection is not a message bus connection.
5459 * @object_path: Path of remote object.
5460 * @interface_name: D-Bus interface to invoke method on.
5461 * @method_name: The name of the method to invoke.
5462 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5463 * or %NULL if not passing parameters.
5464 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5465 * @flags: Flags from the #GDBusCallFlags enumeration.
5466 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5467 * timeout or %G_MAXINT for no timeout.
5468 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5469 * @cancellable: A #GCancellable or %NULL.
5470 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5471 * satisfied or %NULL if you don't * care about the result of the
5472 * method invocation.
5473 * @user_data: The data to pass to @callback.
5475 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5477 * This method is only available on UNIX.
5482 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5483 const gchar *bus_name,
5484 const gchar *object_path,
5485 const gchar *interface_name,
5486 const gchar *method_name,
5487 GVariant *parameters,
5488 const GVariantType *reply_type,
5489 GDBusCallFlags flags,
5491 GUnixFDList *fd_list,
5492 GCancellable *cancellable,
5493 GAsyncReadyCallback callback,
5496 return g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, cancellable, callback, user_data);
5500 * g_dbus_connection_call_with_unix_fd_list_finish:
5501 * @connection: A #GDBusConnection.
5502 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5503 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5504 * @error: Return location for error or %NULL.
5506 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5508 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5509 * return values. Free with g_variant_unref().
5514 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5515 GUnixFDList **out_fd_list,
5519 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5523 * g_dbus_connection_call_with_unix_fd_list_sync:
5524 * @connection: A #GDBusConnection.
5525 * @bus_name: A unique or well-known bus name.
5526 * @object_path: Path of remote object.
5527 * @interface_name: D-Bus interface to invoke method on.
5528 * @method_name: The name of the method to invoke.
5529 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5530 * or %NULL if not passing parameters.
5531 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5532 * @flags: Flags from the #GDBusCallFlags enumeration.
5533 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5534 * timeout or %G_MAXINT for no timeout.
5535 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5536 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5537 * @cancellable: A #GCancellable or %NULL.
5538 * @error: Return location for error or %NULL.
5540 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5542 * This method is only available on UNIX.
5544 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5545 * return values. Free with g_variant_unref().
5550 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5551 const gchar *bus_name,
5552 const gchar *object_path,
5553 const gchar *interface_name,
5554 const gchar *method_name,
5555 GVariant *parameters,
5556 const GVariantType *reply_type,
5557 GDBusCallFlags flags,
5559 GUnixFDList *fd_list,
5560 GUnixFDList **out_fd_list,
5561 GCancellable *cancellable,
5564 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, out_fd_list, cancellable, error);
5567 #endif /* G_OS_UNIX */
5569 /* ---------------------------------------------------------------------------------------------------- */
5571 struct ExportedSubtree
5575 GDBusConnection *connection;
5576 GDBusSubtreeVTable *vtable;
5577 GDBusSubtreeFlags flags;
5579 GMainContext *context;
5581 GDestroyNotify user_data_free_func;
5585 exported_subtree_free (ExportedSubtree *es)
5587 call_destroy_notify (es->context,
5588 es->user_data_free_func,
5591 if (es->context != NULL)
5592 g_main_context_unref (es->context);
5594 _g_dbus_subtree_vtable_free (es->vtable);
5595 g_free (es->object_path);
5599 /* called without lock held */
5601 handle_subtree_introspect (GDBusConnection *connection,
5602 ExportedSubtree *es,
5603 GDBusMessage *message)
5607 GDBusMessage *reply;
5610 const gchar *sender;
5611 const gchar *requested_object_path;
5612 const gchar *requested_node;
5613 GDBusInterfaceInfo **interfaces;
5615 gchar **subnode_paths;
5616 gboolean has_properties_interface;
5617 gboolean has_introspectable_interface;
5621 requested_object_path = g_dbus_message_get_path (message);
5622 sender = g_dbus_message_get_sender (message);
5623 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5625 s = g_string_new (NULL);
5626 introspect_append_header (s);
5628 /* Strictly we don't need the children in dynamic mode, but we avoid the
5629 * conditionals to preserve code clarity
5631 children = es->vtable->enumerate (es->connection,
5638 requested_node = strrchr (requested_object_path, '/') + 1;
5640 /* Assert existence of object if we are not dynamic */
5641 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5642 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5647 requested_node = NULL;
5650 interfaces = es->vtable->introspect (es->connection,
5655 if (interfaces != NULL)
5657 has_properties_interface = FALSE;
5658 has_introspectable_interface = FALSE;
5660 for (n = 0; interfaces[n] != NULL; n++)
5662 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5663 has_properties_interface = TRUE;
5664 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5665 has_introspectable_interface = TRUE;
5667 if (!has_properties_interface)
5668 g_string_append (s, introspect_properties_interface);
5669 if (!has_introspectable_interface)
5670 g_string_append (s, introspect_introspectable_interface);
5672 for (n = 0; interfaces[n] != NULL; n++)
5674 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5675 g_dbus_interface_info_unref (interfaces[n]);
5677 g_free (interfaces);
5680 /* then include <node> entries from the Subtree for the root */
5683 for (n = 0; children != NULL && children[n] != NULL; n++)
5684 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5687 /* finally include nodes registered below us */
5688 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5689 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5690 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5691 g_strfreev (subnode_paths);
5693 g_string_append (s, "</node>\n");
5695 reply = g_dbus_message_new_method_reply (message);
5696 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5697 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5698 g_object_unref (reply);
5703 g_string_free (s, TRUE);
5704 g_strfreev (children);
5708 /* called without lock held */
5710 handle_subtree_method_invocation (GDBusConnection *connection,
5711 ExportedSubtree *es,
5712 GDBusMessage *message)
5715 const gchar *sender;
5716 const gchar *interface_name;
5717 const gchar *member;
5718 const gchar *signature;
5719 const gchar *requested_object_path;
5720 const gchar *requested_node;
5722 GDBusInterfaceInfo *interface_info;
5723 const GDBusInterfaceVTable *interface_vtable;
5724 gpointer interface_user_data;
5726 GDBusInterfaceInfo **interfaces;
5727 gboolean is_property_get;
5728 gboolean is_property_set;
5729 gboolean is_property_get_all;
5734 requested_object_path = g_dbus_message_get_path (message);
5735 sender = g_dbus_message_get_sender (message);
5736 interface_name = g_dbus_message_get_interface (message);
5737 member = g_dbus_message_get_member (message);
5738 signature = g_dbus_message_get_signature (message);
5739 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5741 is_property_get = FALSE;
5742 is_property_set = FALSE;
5743 is_property_get_all = FALSE;
5744 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5746 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5747 is_property_get = TRUE;
5748 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5749 is_property_set = TRUE;
5750 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5751 is_property_get_all = TRUE;
5756 requested_node = strrchr (requested_object_path, '/') + 1;
5758 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5760 /* We don't want to dispatch to unenumerated
5761 * nodes, so ensure that the child exists.
5766 children = es->vtable->enumerate (es->connection,
5771 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5772 g_strfreev (children);
5780 requested_node = NULL;
5783 /* get introspection data for the node */
5784 interfaces = es->vtable->introspect (es->connection,
5786 requested_object_path,
5790 if (interfaces == NULL)
5793 interface_info = NULL;
5794 for (n = 0; interfaces[n] != NULL; n++)
5796 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5797 interface_info = interfaces[n];
5800 /* dispatch the call if the user wants to handle it */
5801 if (interface_info != NULL)
5803 /* figure out where to dispatch the method call */
5804 interface_user_data = NULL;
5805 interface_vtable = es->vtable->dispatch (es->connection,
5810 &interface_user_data,
5812 if (interface_vtable == NULL)
5815 CONNECTION_LOCK (connection);
5816 handled = validate_and_maybe_schedule_method_call (es->connection,
5823 interface_user_data);
5824 CONNECTION_UNLOCK (connection);
5826 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5827 else if (is_property_get || is_property_set || is_property_get_all)
5829 if (is_property_get)
5830 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5831 else if (is_property_set)
5832 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5833 else if (is_property_get_all)
5834 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5836 g_assert_not_reached ();
5838 /* see if the object supports this interface at all */
5839 for (n = 0; interfaces[n] != NULL; n++)
5841 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5842 interface_info = interfaces[n];
5845 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5846 * claims it won't support the interface
5848 if (interface_info == NULL)
5850 GDBusMessage *reply;
5851 reply = g_dbus_message_new_method_error (message,
5852 "org.freedesktop.DBus.Error.InvalidArgs",
5853 _("No such interface `%s'"),
5855 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5856 g_object_unref (reply);
5861 /* figure out where to dispatch the property get/set/getall calls */
5862 interface_user_data = NULL;
5863 interface_vtable = es->vtable->dispatch (es->connection,
5868 &interface_user_data,
5870 if (interface_vtable == NULL)
5872 g_warning ("The subtree introspection function indicates that '%s' "
5873 "is a valid interface name, but calling the dispatch "
5874 "function on that interface gave us NULL", interface_name);
5878 if (is_property_get || is_property_set)
5880 CONNECTION_LOCK (connection);
5881 handled = validate_and_maybe_schedule_property_getset (es->connection,
5889 interface_user_data);
5890 CONNECTION_UNLOCK (connection);
5892 else if (is_property_get_all)
5894 CONNECTION_LOCK (connection);
5895 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5902 interface_user_data);
5903 CONNECTION_UNLOCK (connection);
5908 if (interfaces != NULL)
5910 for (n = 0; interfaces[n] != NULL; n++)
5911 g_dbus_interface_info_unref (interfaces[n]);
5912 g_free (interfaces);
5920 GDBusMessage *message;
5921 ExportedSubtree *es;
5922 } SubtreeDeferredData;
5925 subtree_deferred_data_free (SubtreeDeferredData *data)
5927 g_object_unref (data->message);
5931 /* called without lock held in the thread where the caller registered the subtree */
5933 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5935 SubtreeDeferredData *data = _data;
5940 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5941 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5942 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5943 handled = handle_subtree_introspect (data->es->connection,
5947 handled = handle_subtree_method_invocation (data->es->connection,
5953 CONNECTION_LOCK (data->es->connection);
5954 handled = handle_generic_unlocked (data->es->connection, data->message);
5955 CONNECTION_UNLOCK (data->es->connection);
5958 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5961 GDBusMessage *reply;
5962 reply = g_dbus_message_new_method_error (data->message,
5963 "org.freedesktop.DBus.Error.UnknownMethod",
5964 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5965 g_dbus_message_get_member (data->message),
5966 g_dbus_message_get_interface (data->message),
5967 g_dbus_message_get_signature (data->message));
5968 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5969 g_object_unref (reply);
5975 /* called in message handler thread with lock held */
5977 subtree_message_func (GDBusConnection *connection,
5978 ExportedSubtree *es,
5979 GDBusMessage *message)
5981 GSource *idle_source;
5982 SubtreeDeferredData *data;
5984 data = g_new0 (SubtreeDeferredData, 1);
5985 data->message = g_object_ref (message);
5988 /* defer this call to an idle handler in the right thread */
5989 idle_source = g_idle_source_new ();
5990 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5991 g_source_set_callback (idle_source,
5992 process_subtree_vtable_message_in_idle_cb,
5994 (GDestroyNotify) subtree_deferred_data_free);
5995 g_source_attach (idle_source, es->context);
5996 g_source_unref (idle_source);
5998 /* since we own the entire subtree, handlers for objects not in the subtree have been
5999 * tried already by libdbus-1 - so we just need to ensure that we're always going
6000 * to reply to the message
6006 * g_dbus_connection_register_subtree:
6007 * @connection: A #GDBusConnection.
6008 * @object_path: The object path to register the subtree at.
6009 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6010 * @flags: Flags used to fine tune the behavior of the subtree.
6011 * @user_data: Data to pass to functions in @vtable.
6012 * @user_data_free_func: Function to call when the subtree is unregistered.
6013 * @error: Return location for error or %NULL.
6015 * Registers a whole subtree of <quote>dynamic</quote> objects.
6017 * The @enumerate and @introspection functions in @vtable are used to
6018 * convey, to remote callers, what nodes exist in the subtree rooted
6021 * When handling remote calls into any node in the subtree, first the
6022 * @enumerate function is used to check if the node exists. If the node exists
6023 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6024 * the @introspection function is used to check if the node supports the
6025 * requested method. If so, the @dispatch function is used to determine
6026 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6027 * #gpointer will be used to call into the interface vtable for processing
6030 * All calls into user-provided code will be invoked in the <link
6031 * linkend="g-main-context-push-thread-default">thread-default main
6032 * loop</link> of the thread you are calling this method from.
6034 * If an existing subtree is already registered at @object_path or
6035 * then @error is set to #G_IO_ERROR_EXISTS.
6037 * Note that it is valid to register regular objects (using
6038 * g_dbus_connection_register_object()) in a subtree registered with
6039 * g_dbus_connection_register_subtree() - if so, the subtree handler
6040 * is tried as the last resort. One way to think about a subtree
6041 * handler is to consider it a <quote>fallback handler</quote>
6042 * for object paths not registered via g_dbus_connection_register_object()
6043 * or other bindings.
6045 * Note that @vtable will be copied so you cannot change it after
6048 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6050 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6051 * that can be used with g_dbus_connection_unregister_subtree() .
6056 g_dbus_connection_register_subtree (GDBusConnection *connection,
6057 const gchar *object_path,
6058 const GDBusSubtreeVTable *vtable,
6059 GDBusSubtreeFlags flags,
6061 GDestroyNotify user_data_free_func,
6065 ExportedSubtree *es;
6067 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6068 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6069 g_return_val_if_fail (vtable != NULL, 0);
6070 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6074 CONNECTION_LOCK (connection);
6076 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6082 _("A subtree is already exported for %s"),
6087 es = g_new0 (ExportedSubtree, 1);
6088 es->object_path = g_strdup (object_path);
6089 es->connection = connection;
6091 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6093 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6094 es->user_data = user_data;
6095 es->user_data_free_func = user_data_free_func;
6096 es->context = g_main_context_get_thread_default ();
6097 if (es->context != NULL)
6098 g_main_context_ref (es->context);
6100 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6101 g_hash_table_insert (connection->map_id_to_es,
6102 GUINT_TO_POINTER (es->id),
6108 CONNECTION_UNLOCK (connection);
6113 /* ---------------------------------------------------------------------------------------------------- */
6116 * g_dbus_connection_unregister_subtree:
6117 * @connection: A #GDBusConnection.
6118 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6120 * Unregisters a subtree.
6122 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6127 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6128 guint registration_id)
6130 ExportedSubtree *es;
6133 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6137 CONNECTION_LOCK (connection);
6139 es = g_hash_table_lookup (connection->map_id_to_es,
6140 GUINT_TO_POINTER (registration_id));
6144 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6145 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6150 CONNECTION_UNLOCK (connection);
6155 /* ---------------------------------------------------------------------------------------------------- */
6157 /* must be called with lock held */
6159 handle_generic_ping_unlocked (GDBusConnection *connection,
6160 const gchar *object_path,
6161 GDBusMessage *message)
6163 GDBusMessage *reply;
6164 reply = g_dbus_message_new_method_reply (message);
6165 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6166 g_object_unref (reply);
6169 /* must be called with lock held */
6171 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6172 const gchar *object_path,
6173 GDBusMessage *message)
6175 GDBusMessage *reply;
6178 if (connection->machine_id == NULL)
6183 connection->machine_id = _g_dbus_get_machine_id (&error);
6184 if (connection->machine_id == NULL)
6186 reply = g_dbus_message_new_method_error_literal (message,
6187 "org.freedesktop.DBus.Error.Failed",
6189 g_error_free (error);
6195 reply = g_dbus_message_new_method_reply (message);
6196 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6198 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6199 g_object_unref (reply);
6202 /* must be called with lock held */
6204 handle_generic_introspect_unlocked (GDBusConnection *connection,
6205 const gchar *object_path,
6206 GDBusMessage *message)
6211 GDBusMessage *reply;
6213 /* first the header */
6214 s = g_string_new (NULL);
6215 introspect_append_header (s);
6217 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6218 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6219 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6220 g_strfreev (registered);
6221 g_string_append (s, "</node>\n");
6223 reply = g_dbus_message_new_method_reply (message);
6224 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6225 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6226 g_object_unref (reply);
6227 g_string_free (s, TRUE);
6230 /* must be called with lock held */
6232 handle_generic_unlocked (GDBusConnection *connection,
6233 GDBusMessage *message)
6236 const gchar *interface_name;
6237 const gchar *member;
6238 const gchar *signature;
6241 CONNECTION_ENSURE_LOCK (connection);
6245 interface_name = g_dbus_message_get_interface (message);
6246 member = g_dbus_message_get_member (message);
6247 signature = g_dbus_message_get_signature (message);
6248 path = g_dbus_message_get_path (message);
6250 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6251 g_strcmp0 (member, "Introspect") == 0 &&
6252 g_strcmp0 (signature, "") == 0)
6254 handle_generic_introspect_unlocked (connection, path, message);
6257 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6258 g_strcmp0 (member, "Ping") == 0 &&
6259 g_strcmp0 (signature, "") == 0)
6261 handle_generic_ping_unlocked (connection, path, message);
6264 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6265 g_strcmp0 (member, "GetMachineId") == 0 &&
6266 g_strcmp0 (signature, "") == 0)
6268 handle_generic_get_machine_id_unlocked (connection, path, message);
6275 /* ---------------------------------------------------------------------------------------------------- */
6277 /* called in message handler thread with lock held */
6279 distribute_method_call (GDBusConnection *connection,
6280 GDBusMessage *message)
6282 GDBusMessage *reply;
6284 ExportedSubtree *es;
6285 const gchar *object_path;
6286 const gchar *interface_name;
6287 const gchar *member;
6289 gchar *subtree_path;
6292 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6294 interface_name = g_dbus_message_get_interface (message);
6295 member = g_dbus_message_get_member (message);
6296 path = g_dbus_message_get_path (message);
6297 subtree_path = g_strdup (path);
6298 needle = strrchr (subtree_path, '/');
6299 if (needle != NULL && needle != subtree_path)
6305 g_free (subtree_path);
6306 subtree_path = NULL;
6310 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6312 _g_dbus_debug_print_lock ();
6313 g_print ("========================================================================\n"
6314 "GDBus-debug:Incoming:\n"
6315 " <<<< METHOD INVOCATION %s.%s()\n"
6317 " invoked by name %s\n"
6319 interface_name, member,
6321 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6322 g_dbus_message_get_serial (message));
6323 _g_dbus_debug_print_unlock ();
6326 object_path = g_dbus_message_get_path (message);
6327 g_assert (object_path != NULL);
6329 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6332 if (obj_message_func (connection, eo, message))
6336 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6339 if (subtree_message_func (connection, es, message))
6343 if (subtree_path != NULL)
6345 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6348 if (subtree_message_func (connection, es, message))
6353 if (handle_generic_unlocked (connection, message))
6356 /* if we end up here, the message has not been not handled - so return an error saying this */
6357 reply = g_dbus_message_new_method_error (message,
6358 "org.freedesktop.DBus.Error.UnknownMethod",
6359 _("No such interface `%s' on object at path %s"),
6362 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6363 g_object_unref (reply);
6366 g_free (subtree_path);
6369 /* ---------------------------------------------------------------------------------------------------- */
6371 static GDBusConnection **
6372 message_bus_get_singleton (GBusType bus_type,
6375 GDBusConnection **ret;
6376 const gchar *starter_bus;
6382 case G_BUS_TYPE_SESSION:
6383 ret = &the_session_bus;
6386 case G_BUS_TYPE_SYSTEM:
6387 ret = &the_system_bus;
6390 case G_BUS_TYPE_STARTER:
6391 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6392 if (g_strcmp0 (starter_bus, "session") == 0)
6394 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6397 else if (g_strcmp0 (starter_bus, "system") == 0)
6399 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6404 if (starter_bus != NULL)
6408 G_IO_ERROR_INVALID_ARGUMENT,
6409 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6410 " - unknown value `%s'"),
6415 g_set_error_literal (error,
6417 G_IO_ERROR_INVALID_ARGUMENT,
6418 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6419 "variable is not set"));
6425 g_assert_not_reached ();
6433 static GDBusConnection *
6434 get_uninitialized_connection (GBusType bus_type,
6435 GCancellable *cancellable,
6438 GDBusConnection **singleton;
6439 GDBusConnection *ret;
6443 G_LOCK (message_bus_lock);
6444 singleton = message_bus_get_singleton (bus_type, error);
6445 if (singleton == NULL)
6448 if (*singleton == NULL)
6451 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6452 if (address == NULL)
6454 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6456 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6457 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6458 "exit-on-close", TRUE,
6464 ret = g_object_ref (*singleton);
6467 g_assert (ret != NULL);
6470 G_UNLOCK (message_bus_lock);
6476 * @bus_type: A #GBusType.
6477 * @cancellable: A #GCancellable or %NULL.
6478 * @error: Return location for error or %NULL.
6480 * Synchronously connects to the message bus specified by @bus_type.
6481 * Note that the returned object may shared with other callers,
6482 * e.g. if two separate parts of a process calls this function with
6483 * the same @bus_type, they will share the same object.
6485 * This is a synchronous failable function. See g_bus_get() and
6486 * g_bus_get_finish() for the asynchronous version.
6488 * The returned object is a singleton, that is, shared with other
6489 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6490 * event that you need a private message bus connection, use
6491 * g_dbus_address_get_for_bus_sync() and
6492 * g_dbus_connection_new_for_address().
6494 * Note that the returned #GDBusConnection object will (usually) have
6495 * the #GDBusConnection:exit-on-close property set to %TRUE.
6497 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6502 g_bus_get_sync (GBusType bus_type,
6503 GCancellable *cancellable,
6506 GDBusConnection *connection;
6508 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6510 connection = get_uninitialized_connection (bus_type, cancellable, error);
6511 if (connection == NULL)
6514 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6516 g_object_unref (connection);
6525 bus_get_async_initable_cb (GObject *source_object,
6529 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6533 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6537 g_assert (error != NULL);
6538 g_simple_async_result_take_error (simple, error);
6539 g_object_unref (source_object);
6543 g_simple_async_result_set_op_res_gpointer (simple,
6547 g_simple_async_result_complete_in_idle (simple);
6548 g_object_unref (simple);
6553 * @bus_type: A #GBusType.
6554 * @cancellable: A #GCancellable or %NULL.
6555 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6556 * @user_data: The data to pass to @callback.
6558 * Asynchronously connects to the message bus specified by @bus_type.
6560 * When the operation is finished, @callback will be invoked. You can
6561 * then call g_bus_get_finish() to get the result of the operation.
6563 * This is a asynchronous failable function. See g_bus_get_sync() for
6564 * the synchronous version.
6569 g_bus_get (GBusType bus_type,
6570 GCancellable *cancellable,
6571 GAsyncReadyCallback callback,
6574 GDBusConnection *connection;
6575 GSimpleAsyncResult *simple;
6578 simple = g_simple_async_result_new (NULL,
6584 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6585 if (connection == NULL)
6587 g_assert (error != NULL);
6588 g_simple_async_result_take_error (simple, error);
6589 g_simple_async_result_complete_in_idle (simple);
6590 g_object_unref (simple);
6594 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6597 bus_get_async_initable_cb,
6604 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6605 * @error: Return location for error or %NULL.
6607 * Finishes an operation started with g_bus_get().
6609 * The returned object is a singleton, that is, shared with other
6610 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6611 * event that you need a private message bus connection, use
6612 * g_dbus_address_get_for_bus_sync() and
6613 * g_dbus_connection_new_for_address().
6615 * Note that the returned #GDBusConnection object will (usually) have
6616 * the #GDBusConnection:exit-on-close property set to %TRUE.
6618 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6623 g_bus_get_finish (GAsyncResult *res,
6626 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6628 GDBusConnection *ret;
6630 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6632 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6636 if (g_simple_async_result_propagate_error (simple, error))
6639 object = g_simple_async_result_get_op_res_gpointer (simple);
6640 g_assert (object != NULL);
6641 ret = g_object_ref (G_DBUS_CONNECTION (object));
6647 /* ---------------------------------------------------------------------------------------------------- */