1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (excect
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily acheive secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "gio-marshal.h"
125 #include "ginitable.h"
126 #include "gasyncinitable.h"
127 #include "giostream.h"
128 #include "gasyncresult.h"
129 #include "gsimpleasyncresult.h"
132 #include "gunixconnection.h"
133 #include "gunixfdmessage.h"
136 #include "glibintl.h"
139 * SECTION:gdbusconnection
140 * @short_description: D-Bus Connections
141 * @include: gio/gio.h
143 * The #GDBusConnection type is used for D-Bus connections to remote
144 * peers such as a message buses. It is a low-level API that offers a
145 * lot of flexibility. For instance, it lets you establish a connection
146 * over any transport that can by represented as an #GIOStream.
148 * This class is rarely used directly in D-Bus clients. If you are writing
149 * an D-Bus client, it is often easier to use the g_bus_own_name(),
150 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
152 * <example id="gdbus-server"><title>D-Bus server example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-server.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
154 * <example id="gdbus-subtree-server"><title>D-Bus subtree example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-subtree.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
156 * <example id="gdbus-unix-fd-client"><title>D-Bus UNIX File Descriptor example</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-unix-fd-client.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
158 * <example id="gdbus-export"><title>Exporting a GObject</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-export.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
161 /* ---------------------------------------------------------------------------------------------------- */
163 typedef struct _GDBusConnectionClass GDBusConnectionClass;
166 * GDBusConnectionClass:
167 * @closed: Signal class handler for the #GDBusConnection::closed signal.
169 * Class structure for #GDBusConnection.
173 struct _GDBusConnectionClass
176 GObjectClass parent_class;
180 void (*closed) (GDBusConnection *connection,
181 gboolean remote_peer_vanished,
185 G_LOCK_DEFINE_STATIC (message_bus_lock);
187 static GDBusConnection *the_session_bus = NULL;
188 static GDBusConnection *the_system_bus = NULL;
190 /* ---------------------------------------------------------------------------------------------------- */
194 GDestroyNotify callback;
196 GMainContext *context;
197 } CallDestroyNotifyData;
200 call_destroy_notify_data_in_idle (gpointer user_data)
202 CallDestroyNotifyData *data = user_data;
203 data->callback (data->user_data);
208 call_destroy_notify_data_free (CallDestroyNotifyData *data)
210 if (data->context != NULL)
211 g_main_context_unref (data->context);
216 * call_destroy_notify: <internal>
217 * @context: A #GMainContext or %NULL.
218 * @callback: A #GDestroyNotify or %NULL.
219 * @user_data: Data to pass to @callback.
221 * Schedules @callback to run in @context.
224 call_destroy_notify (GMainContext *context,
225 GDestroyNotify callback,
228 if (callback == NULL)
231 if (context == g_main_context_get_thread_default ())
233 callback (user_data);
237 GSource *idle_source;
238 CallDestroyNotifyData *data;
240 data = g_new0 (CallDestroyNotifyData, 1);
241 data->callback = callback;
242 data->user_data = user_data;
243 data->context = context;
244 if (data->context != NULL)
245 g_main_context_ref (data->context);
247 idle_source = g_idle_source_new ();
248 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
249 g_source_set_callback (idle_source,
250 call_destroy_notify_data_in_idle,
252 (GDestroyNotify) call_destroy_notify_data_free);
253 g_source_attach (idle_source, data->context);
254 g_source_unref (idle_source);
261 /* ---------------------------------------------------------------------------------------------------- */
264 _g_strv_has_string (const gchar* const *haystack,
269 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
271 if (g_strcmp0 (haystack[n], needle) == 0)
277 /* ---------------------------------------------------------------------------------------------------- */
280 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
282 // TODO: for some reason this doesn't work on Windows
283 #define CONNECTION_ENSURE_LOCK(obj) do { \
284 if (G_UNLIKELY (g_mutex_trylock((obj)->lock))) \
286 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
287 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
292 #define CONNECTION_LOCK(obj) do { \
293 g_mutex_lock ((obj)->lock); \
296 #define CONNECTION_UNLOCK(obj) do { \
297 g_mutex_unlock ((obj)->lock); \
303 * The #GDBusConnection structure contains only private data and
304 * should only be accessed using the provided API.
308 struct _GDBusConnection
311 GObject parent_instance;
313 /* ------------------------------------------------------------------------ */
314 /* -- General object state ------------------------------------------------ */
315 /* ------------------------------------------------------------------------ */
317 /* object-wide lock */
320 /* A lock used in the init() method of the GInitable interface - see comments
321 * in initable_init() for why a separate lock is needed
325 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
326 * someone calls org.freedesktop.DBus.GetMachineId()
330 /* The underlying stream used for communication */
333 /* The object used for authentication (if any) */
336 /* Set to TRUE if the connection has been closed */
339 /* Last serial used */
342 /* The object used to send/receive message */
345 /* If connected to a message bus, this contains the unique name assigned to
346 * us by the bus (e.g. ":1.42")
348 gchar *bus_unique_name;
350 /* The GUID returned by the other side if we authenticed as a client or
351 * the GUID to use if authenticating as a server
355 /* set to TRUE exactly when initable_init() has finished running */
356 gboolean is_initialized;
358 /* If the connection could not be established during initable_init(), this GError will set */
359 GError *initialization_error;
361 /* The result of g_main_context_get_thread_default() when the object
362 * was created (the GObject _init() function) - this is used for delivery
363 * of the :closed GObject signal.
365 GMainContext *main_context_at_construction;
367 /* construct properties */
369 GDBusConnectionFlags flags;
371 /* Map used for managing method replies */
372 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
374 /* Maps used for managing signal subscription */
375 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
376 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
377 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
379 /* Maps used for managing exported objects and subtrees */
380 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
381 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
382 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
383 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
385 /* Structure used for message filters */
388 /* Whether to exit on close */
389 gboolean exit_on_close;
391 /* Capabilities negotiated during authentication */
392 GDBusCapabilityFlags capabilities;
394 GDBusAuthObserver *authentication_observer;
395 GCredentials *credentials;
397 /* set to TRUE when finalizing */
401 typedef struct ExportedObject ExportedObject;
402 static void exported_object_free (ExportedObject *eo);
404 typedef struct ExportedSubtree ExportedSubtree;
405 static void exported_subtree_free (ExportedSubtree *es);
423 PROP_CAPABILITY_FLAGS,
424 PROP_AUTHENTICATION_OBSERVER,
427 static void distribute_signals (GDBusConnection *connection,
428 GDBusMessage *message);
430 static void distribute_method_call (GDBusConnection *connection,
431 GDBusMessage *message);
433 static gboolean handle_generic_unlocked (GDBusConnection *connection,
434 GDBusMessage *message);
437 static void purge_all_signal_subscriptions (GDBusConnection *connection);
438 static void purge_all_filters (GDBusConnection *connection);
440 #define _G_ENSURE_LOCK(name) do { \
441 if (G_UNLIKELY (G_TRYLOCK(name))) \
443 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
444 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
448 static guint signals[LAST_SIGNAL] = { 0 };
450 static void initable_iface_init (GInitableIface *initable_iface);
451 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
453 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
454 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
455 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
458 static GHashTable *alive_connections = NULL;
461 g_dbus_connection_dispose (GObject *object)
463 GDBusConnection *connection = G_DBUS_CONNECTION (object);
465 G_LOCK (message_bus_lock);
466 if (connection == the_session_bus)
468 the_session_bus = NULL;
470 else if (connection == the_system_bus)
472 the_system_bus = NULL;
474 CONNECTION_LOCK (connection);
475 if (connection->worker != NULL)
477 _g_dbus_worker_stop (connection->worker);
478 connection->worker = NULL;
479 if (alive_connections != NULL)
480 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
484 if (alive_connections != NULL)
485 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
487 CONNECTION_UNLOCK (connection);
488 G_UNLOCK (message_bus_lock);
490 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
491 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
495 g_dbus_connection_finalize (GObject *object)
497 GDBusConnection *connection = G_DBUS_CONNECTION (object);
499 connection->finalizing = TRUE;
501 purge_all_signal_subscriptions (connection);
503 purge_all_filters (connection);
504 g_ptr_array_unref (connection->filters);
506 if (connection->authentication_observer != NULL)
507 g_object_unref (connection->authentication_observer);
509 if (connection->auth != NULL)
510 g_object_unref (connection->auth);
512 if (connection->credentials)
513 g_object_unref (connection->credentials);
515 if (connection->stream != NULL)
517 /* We don't really care if closing the stream succeeds or not */
518 g_io_stream_close_async (connection->stream,
520 NULL, /* GCancellable */
521 NULL, /* GAsyncReadyCallback */
522 NULL); /* userdata */
523 g_object_unref (connection->stream);
524 connection->stream = NULL;
527 g_free (connection->address);
529 g_free (connection->guid);
530 g_free (connection->bus_unique_name);
532 if (connection->initialization_error != NULL)
533 g_error_free (connection->initialization_error);
535 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
537 g_hash_table_unref (connection->map_rule_to_signal_data);
538 g_hash_table_unref (connection->map_id_to_signal_data);
539 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
541 g_hash_table_unref (connection->map_id_to_ei);
542 g_hash_table_unref (connection->map_object_path_to_eo);
543 g_hash_table_unref (connection->map_id_to_es);
544 g_hash_table_unref (connection->map_object_path_to_es);
546 if (connection->main_context_at_construction != NULL)
547 g_main_context_unref (connection->main_context_at_construction);
549 g_free (connection->machine_id);
551 g_mutex_free (connection->init_lock);
552 g_mutex_free (connection->lock);
554 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
558 g_dbus_connection_get_property (GObject *object,
563 GDBusConnection *connection = G_DBUS_CONNECTION (object);
568 g_value_set_object (value, g_dbus_connection_get_stream (connection));
572 g_value_set_string (value, g_dbus_connection_get_guid (connection));
575 case PROP_UNIQUE_NAME:
576 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
580 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
583 case PROP_EXIT_ON_CLOSE:
584 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
587 case PROP_CAPABILITY_FLAGS:
588 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
592 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
598 g_dbus_connection_set_property (GObject *object,
603 GDBusConnection *connection = G_DBUS_CONNECTION (object);
608 connection->stream = g_value_dup_object (value);
612 connection->guid = g_value_dup_string (value);
616 connection->address = g_value_dup_string (value);
620 connection->flags = g_value_get_flags (value);
623 case PROP_EXIT_ON_CLOSE:
624 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
627 case PROP_AUTHENTICATION_OBSERVER:
628 connection->authentication_observer = g_value_dup_object (value);
632 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
638 g_dbus_connection_real_closed (GDBusConnection *connection,
639 gboolean remote_peer_vanished,
642 if (remote_peer_vanished && connection->exit_on_close)
646 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
649 g_quark_to_string (error->domain), error->code);
653 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
660 g_dbus_connection_class_init (GDBusConnectionClass *klass)
662 GObjectClass *gobject_class;
664 gobject_class = G_OBJECT_CLASS (klass);
666 gobject_class->finalize = g_dbus_connection_finalize;
667 gobject_class->dispose = g_dbus_connection_dispose;
668 gobject_class->set_property = g_dbus_connection_set_property;
669 gobject_class->get_property = g_dbus_connection_get_property;
671 klass->closed = g_dbus_connection_real_closed;
674 * GDBusConnection:stream:
676 * The underlying #GIOStream used for I/O.
678 * If this is passed on construction and is a #GSocketConnection,
679 * then the corresponding #GSocket will be put into non-blocking mode.
683 g_object_class_install_property (gobject_class,
685 g_param_spec_object ("stream",
687 P_("The underlying streams used for I/O"),
691 G_PARAM_CONSTRUCT_ONLY |
692 G_PARAM_STATIC_NAME |
693 G_PARAM_STATIC_BLURB |
694 G_PARAM_STATIC_NICK));
697 * GDBusConnection:address:
699 * A D-Bus address specifying potential endpoints that can be used
700 * when establishing the connection.
704 g_object_class_install_property (gobject_class,
706 g_param_spec_string ("address",
708 P_("D-Bus address specifying potential socket endpoints"),
711 G_PARAM_CONSTRUCT_ONLY |
712 G_PARAM_STATIC_NAME |
713 G_PARAM_STATIC_BLURB |
714 G_PARAM_STATIC_NICK));
717 * GDBusConnection:flags:
719 * Flags from the #GDBusConnectionFlags enumeration.
723 g_object_class_install_property (gobject_class,
725 g_param_spec_flags ("flags",
728 G_TYPE_DBUS_CONNECTION_FLAGS,
729 G_DBUS_CONNECTION_FLAGS_NONE,
731 G_PARAM_CONSTRUCT_ONLY |
732 G_PARAM_STATIC_NAME |
733 G_PARAM_STATIC_BLURB |
734 G_PARAM_STATIC_NICK));
737 * GDBusConnection:guid:
739 * The GUID of the peer performing the role of server when
742 * If you are constructing a #GDBusConnection and pass
743 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
744 * #GDBusConnection:flags property then you MUST also set this
745 * property to a valid guid.
747 * If you are constructing a #GDBusConnection and pass
748 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
749 * #GDBusConnection:flags property you will be able to read the GUID
750 * of the other peer here after the connection has been successfully
755 g_object_class_install_property (gobject_class,
757 g_param_spec_string ("guid",
759 P_("GUID of the server peer"),
763 G_PARAM_CONSTRUCT_ONLY |
764 G_PARAM_STATIC_NAME |
765 G_PARAM_STATIC_BLURB |
766 G_PARAM_STATIC_NICK));
769 * GDBusConnection:unique-name:
771 * The unique name as assigned by the message bus or %NULL if the
772 * connection is not open or not a message bus connection.
776 g_object_class_install_property (gobject_class,
778 g_param_spec_string ("unique-name",
780 P_("Unique name of bus connection"),
783 G_PARAM_STATIC_NAME |
784 G_PARAM_STATIC_BLURB |
785 G_PARAM_STATIC_NICK));
788 * GDBusConnection:closed:
790 * A boolean specifying whether the connection has been closed.
794 g_object_class_install_property (gobject_class,
796 g_param_spec_boolean ("closed",
798 P_("Whether the connection is closed"),
801 G_PARAM_STATIC_NAME |
802 G_PARAM_STATIC_BLURB |
803 G_PARAM_STATIC_NICK));
806 * GDBusConnection:exit-on-close:
808 * A boolean specifying whether the process will be terminated (by
809 * calling <literal>raise(SIGTERM)</literal>) if the connection
810 * is closed by the remote peer.
814 g_object_class_install_property (gobject_class,
816 g_param_spec_boolean ("exit-on-close",
818 P_("Whether the process is terminated when the connection is closed"),
822 G_PARAM_STATIC_NAME |
823 G_PARAM_STATIC_BLURB |
824 G_PARAM_STATIC_NICK));
827 * GDBusConnection:capabilities:
829 * Flags from the #GDBusCapabilityFlags enumeration
830 * representing connection features negotiated with the other peer.
834 g_object_class_install_property (gobject_class,
835 PROP_CAPABILITY_FLAGS,
836 g_param_spec_flags ("capabilities",
839 G_TYPE_DBUS_CAPABILITY_FLAGS,
840 G_DBUS_CAPABILITY_FLAGS_NONE,
842 G_PARAM_STATIC_NAME |
843 G_PARAM_STATIC_BLURB |
844 G_PARAM_STATIC_NICK));
847 * GDBusConnection:authentication-observer:
849 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
853 g_object_class_install_property (gobject_class,
854 PROP_AUTHENTICATION_OBSERVER,
855 g_param_spec_object ("authentication-observer",
856 P_("Authentication Observer"),
857 P_("Object used to assist in the authentication process"),
858 G_TYPE_DBUS_AUTH_OBSERVER,
860 G_PARAM_CONSTRUCT_ONLY |
861 G_PARAM_STATIC_NAME |
862 G_PARAM_STATIC_BLURB |
863 G_PARAM_STATIC_NICK));
866 * GDBusConnection::closed:
867 * @connection: The #GDBusConnection emitting the signal.
868 * @remote_peer_vanished: %TRUE if @connection is closed because the
869 * remote peer closed its end of the connection.
870 * @error: A #GError with more details about the event or %NULL.
872 * Emitted when the connection is closed.
874 * The cause of this event can be
877 * If g_dbus_connection_close() is called. In this case
878 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
881 * If the remote peer closes the connection. In this case
882 * @remote_peer_vanished is set to %TRUE and @error is set.
885 * If the remote peer sends invalid or malformed data. In this
886 * case @remote_peer_vanished is set to %FALSE and @error
891 * Upon receiving this signal, you should give up your reference to
892 * @connection. You are guaranteed that this signal is emitted only
897 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
898 G_TYPE_DBUS_CONNECTION,
900 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
903 _gio_marshal_VOID__BOOLEAN_BOXED,
911 g_dbus_connection_init (GDBusConnection *connection)
913 connection->lock = g_mutex_new ();
914 connection->init_lock = g_mutex_new ();
916 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
918 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
920 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
922 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
925 (GDestroyNotify) g_ptr_array_unref);
927 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
930 (GDestroyNotify) exported_object_free);
932 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
935 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
938 (GDestroyNotify) exported_subtree_free);
940 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
943 connection->main_context_at_construction = g_main_context_get_thread_default ();
944 if (connection->main_context_at_construction != NULL)
945 g_main_context_ref (connection->main_context_at_construction);
947 connection->filters = g_ptr_array_new ();
951 * g_dbus_connection_get_stream:
952 * @connection: a #GDBusConnection
954 * Gets the underlying stream used for IO.
956 * Returns: (transfer none): the stream used for IO
961 g_dbus_connection_get_stream (GDBusConnection *connection)
963 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
964 return connection->stream;
968 * g_dbus_connection_start_message_processing:
969 * @connection: A #GDBusConnection.
971 * If @connection was created with
972 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
973 * starts processing messages. Does nothing on if @connection wasn't
974 * created with this flag or if the method has already been called.
979 g_dbus_connection_start_message_processing (GDBusConnection *connection)
981 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
982 _g_dbus_worker_unfreeze (connection->worker);
986 * g_dbus_connection_is_closed:
987 * @connection: A #GDBusConnection.
989 * Gets whether @connection is closed.
991 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
996 g_dbus_connection_is_closed (GDBusConnection *connection)
998 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
999 return connection->closed;
1003 * g_dbus_connection_get_capabilities:
1004 * @connection: A #GDBusConnection.
1006 * Gets the capabilities negotiated with the remote peer
1008 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1012 GDBusCapabilityFlags
1013 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1015 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1016 return connection->capabilities;
1019 /* ---------------------------------------------------------------------------------------------------- */
1022 flush_in_thread_func (GSimpleAsyncResult *res,
1024 GCancellable *cancellable)
1029 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1032 g_simple_async_result_take_error (res, error);
1036 * g_dbus_connection_flush:
1037 * @connection: A #GDBusConnection.
1038 * @cancellable: A #GCancellable or %NULL.
1039 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1040 * satisfied or %NULL if you don't care about the result.
1041 * @user_data: The data to pass to @callback.
1043 * Asynchronously flushes @connection, that is, writes all queued
1044 * outgoing message to the transport and then flushes the transport
1045 * (using g_output_stream_flush_async()). This is useful in programs
1046 * that wants to emit a D-Bus signal and then exit
1047 * immediately. Without flushing the connection, there is no guarantee
1048 * that the message has been sent to the networking buffers in the OS
1051 * This is an asynchronous method. When the operation is finished,
1052 * @callback will be invoked in the <link
1053 * linkend="g-main-context-push-thread-default">thread-default main
1054 * loop</link> of the thread you are calling this method from. You can
1055 * then call g_dbus_connection_flush_finish() to get the result of the
1056 * operation. See g_dbus_connection_flush_sync() for the synchronous
1062 g_dbus_connection_flush (GDBusConnection *connection,
1063 GCancellable *cancellable,
1064 GAsyncReadyCallback callback,
1067 GSimpleAsyncResult *simple;
1069 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1071 simple = g_simple_async_result_new (G_OBJECT (connection),
1074 g_dbus_connection_flush);
1075 g_simple_async_result_run_in_thread (simple,
1076 flush_in_thread_func,
1079 g_object_unref (simple);
1083 * g_dbus_connection_flush_finish:
1084 * @connection: A #GDBusConnection.
1085 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1086 * @error: Return location for error or %NULL.
1088 * Finishes an operation started with g_dbus_connection_flush().
1090 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1095 g_dbus_connection_flush_finish (GDBusConnection *connection,
1099 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1104 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1105 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1106 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1108 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1110 if (g_simple_async_result_propagate_error (simple, error))
1120 * g_dbus_connection_flush_sync:
1121 * @connection: A #GDBusConnection.
1122 * @cancellable: A #GCancellable or %NULL.
1123 * @error: Return location for error or %NULL.
1125 * Synchronously flushes @connection. The calling thread is blocked
1126 * until this is done. See g_dbus_connection_flush() for the
1127 * asynchronous version of this method and more details about what it
1130 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1135 g_dbus_connection_flush_sync (GDBusConnection *connection,
1136 GCancellable *cancellable,
1141 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1142 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1146 if (connection->closed)
1148 g_set_error_literal (error,
1151 _("The connection is closed"));
1155 ret = _g_dbus_worker_flush_sync (connection->worker,
1163 /* ---------------------------------------------------------------------------------------------------- */
1167 GDBusConnection *connection;
1169 gboolean remote_peer_vanished;
1173 emit_closed_data_free (EmitClosedData *data)
1175 g_object_unref (data->connection);
1176 if (data->error != NULL)
1177 g_error_free (data->error);
1182 emit_closed_in_idle (gpointer user_data)
1184 EmitClosedData *data = user_data;
1187 g_object_notify (G_OBJECT (data->connection), "closed");
1188 g_signal_emit (data->connection,
1189 signals[CLOSED_SIGNAL],
1191 data->remote_peer_vanished,
1197 /* Can be called from any thread, must hold lock */
1199 set_closed_unlocked (GDBusConnection *connection,
1200 gboolean remote_peer_vanished,
1203 GSource *idle_source;
1204 EmitClosedData *data;
1206 CONNECTION_ENSURE_LOCK (connection);
1208 g_assert (!connection->closed);
1210 connection->closed = TRUE;
1212 data = g_new0 (EmitClosedData, 1);
1213 data->connection = g_object_ref (connection);
1214 data->remote_peer_vanished = remote_peer_vanished;
1215 data->error = error != NULL ? g_error_copy (error) : NULL;
1217 idle_source = g_idle_source_new ();
1218 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1219 g_source_set_callback (idle_source,
1220 emit_closed_in_idle,
1222 (GDestroyNotify) emit_closed_data_free);
1223 g_source_attach (idle_source, connection->main_context_at_construction);
1224 g_source_unref (idle_source);
1227 /* ---------------------------------------------------------------------------------------------------- */
1230 close_in_thread_func (GSimpleAsyncResult *res,
1232 GCancellable *cancellable)
1237 if (!g_dbus_connection_close_sync (G_DBUS_CONNECTION (object),
1240 g_simple_async_result_take_error (res, error);
1244 * g_dbus_connection_close:
1245 * @connection: A #GDBusConnection.
1246 * @cancellable: A #GCancellable or %NULL.
1247 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1248 * satisfied or %NULL if you don't care about the result.
1249 * @user_data: The data to pass to @callback.
1251 * Closes @connection. Note that this never causes the process to
1252 * exit (this might only happen if the other end of a shared message
1253 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1255 * Once the connection is closed, operations such as sending a message
1256 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1257 * will not automatically flush the connection so queued messages may
1258 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1260 * If @connection is already closed, this method fails with
1261 * %G_IO_ERROR_CLOSED.
1263 * When @connection has been closed, the #GDBusConnection::closed
1264 * signal is emitted in the <link
1265 * linkend="g-main-context-push-thread-default">thread-default main
1266 * loop</link> of the thread that @connection was constructed in.
1268 * This is an asynchronous method. When the operation is finished,
1269 * @callback will be invoked in the <link
1270 * linkend="g-main-context-push-thread-default">thread-default main
1271 * loop</link> of the thread you are calling this method from. You can
1272 * then call g_dbus_connection_close_finish() to get the result of the
1273 * operation. See g_dbus_connection_close_sync() for the synchronous
1279 g_dbus_connection_close (GDBusConnection *connection,
1280 GCancellable *cancellable,
1281 GAsyncReadyCallback callback,
1284 GSimpleAsyncResult *simple;
1286 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1288 simple = g_simple_async_result_new (G_OBJECT (connection),
1291 g_dbus_connection_close);
1292 g_simple_async_result_run_in_thread (simple,
1293 close_in_thread_func,
1296 g_object_unref (simple);
1300 * g_dbus_connection_close_finish:
1301 * @connection: A #GDBusConnection.
1302 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1303 * @error: Return location for error or %NULL.
1305 * Finishes an operation started with g_dbus_connection_close().
1307 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1312 g_dbus_connection_close_finish (GDBusConnection *connection,
1316 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1321 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1322 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1323 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1325 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1327 if (g_simple_async_result_propagate_error (simple, error))
1337 * g_dbus_connection_close_sync:
1338 * @connection: A #GDBusConnection.
1339 * @cancellable: A #GCancellable or %NULL.
1340 * @error: Return location for error or %NULL.
1342 * Synchronously closees @connection. The calling thread is blocked
1343 * until this is done. See g_dbus_connection_close() for the
1344 * asynchronous version of this method and more details about what it
1347 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1352 g_dbus_connection_close_sync (GDBusConnection *connection,
1353 GCancellable *cancellable,
1358 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1359 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1363 CONNECTION_LOCK (connection);
1364 if (!connection->closed)
1366 ret = g_io_stream_close (connection->stream,
1370 set_closed_unlocked (connection, FALSE, NULL);
1374 g_set_error_literal (error,
1377 _("The connection is closed"));
1379 CONNECTION_UNLOCK (connection);
1384 /* ---------------------------------------------------------------------------------------------------- */
1387 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1388 GDBusMessage *message,
1389 GDBusSendMessageFlags flags,
1390 volatile guint32 *out_serial,
1395 guint32 serial_to_use;
1398 CONNECTION_ENSURE_LOCK (connection);
1400 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1401 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1403 /* TODO: check all necessary headers are present */
1408 if (out_serial != NULL)
1411 if (connection->closed)
1413 g_set_error_literal (error,
1416 _("The connection is closed"));
1420 blob = g_dbus_message_to_blob (message,
1422 connection->capabilities,
1427 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1428 serial_to_use = g_dbus_message_get_serial (message);
1430 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1435 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1438 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1441 g_assert_not_reached ();
1446 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1447 blob_size, serial_to_use, connection);
1448 g_printerr ("----\n");
1449 hexdump (blob, blob_size);
1450 g_printerr ("----\n");
1453 /* TODO: use connection->auth to encode the blob */
1455 if (out_serial != NULL)
1456 *out_serial = serial_to_use;
1458 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1459 g_dbus_message_set_serial (message, serial_to_use);
1461 g_dbus_message_lock (message);
1462 _g_dbus_worker_send_message (connection->worker,
1466 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1477 * g_dbus_connection_send_message:
1478 * @connection: A #GDBusConnection.
1479 * @message: A #GDBusMessage
1480 * @flags: Flags affecting how the message is sent.
1481 * @out_serial: (out) (allow-none): Return location for serial number assigned
1482 * to @message when sending it or %NULL.
1483 * @error: Return location for error or %NULL.
1485 * Asynchronously sends @message to the peer represented by @connection.
1487 * Unless @flags contain the
1488 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1489 * will be assigned by @connection and set on @message via
1490 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1491 * serial number used will be written to this location prior to
1492 * submitting the message to the underlying transport.
1494 * If @connection is closed then the operation will fail with
1495 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1496 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1498 * See <xref linkend="gdbus-server"/> and <xref
1499 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1500 * low-level API to send and receive UNIX file descriptors.
1502 * Note that @message must be unlocked, unless @flags contain the
1503 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1505 * Returns: %TRUE if the message was well-formed and queued for
1506 * transmission, %FALSE if @error is set.
1511 g_dbus_connection_send_message (GDBusConnection *connection,
1512 GDBusMessage *message,
1513 GDBusSendMessageFlags flags,
1514 volatile guint32 *out_serial,
1519 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1520 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1521 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1522 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1524 CONNECTION_LOCK (connection);
1525 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1526 CONNECTION_UNLOCK (connection);
1530 /* ---------------------------------------------------------------------------------------------------- */
1534 volatile gint ref_count;
1535 GDBusConnection *connection;
1537 GSimpleAsyncResult *simple;
1539 GMainContext *main_context;
1541 GCancellable *cancellable;
1543 gulong cancellable_handler_id;
1545 GSource *timeout_source;
1550 static SendMessageData *
1551 send_message_data_ref (SendMessageData *data)
1553 g_atomic_int_inc (&data->ref_count);
1558 send_message_data_unref (SendMessageData *data)
1560 if (g_atomic_int_dec_and_test (&data->ref_count))
1562 g_assert (data->timeout_source == NULL);
1563 g_assert (data->simple == NULL);
1564 g_assert (data->cancellable_handler_id == 0);
1565 g_object_unref (data->connection);
1566 if (data->cancellable != NULL)
1567 g_object_unref (data->cancellable);
1568 if (data->main_context != NULL)
1569 g_main_context_unref (data->main_context);
1574 /* ---------------------------------------------------------------------------------------------------- */
1576 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1578 send_message_with_reply_deliver (SendMessageData *data)
1580 CONNECTION_ENSURE_LOCK (data->connection);
1582 g_assert (!data->delivered);
1584 data->delivered = TRUE;
1586 g_simple_async_result_complete_in_idle (data->simple);
1587 g_object_unref (data->simple);
1588 data->simple = NULL;
1590 if (data->timeout_source != NULL)
1592 g_source_destroy (data->timeout_source);
1593 data->timeout_source = NULL;
1595 if (data->cancellable_handler_id > 0)
1597 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1598 data->cancellable_handler_id = 0;
1601 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1602 GUINT_TO_POINTER (data->serial)));
1604 send_message_data_unref (data);
1607 /* ---------------------------------------------------------------------------------------------------- */
1609 /* must hold lock */
1611 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1612 GDBusMessage *reply)
1614 if (data->delivered)
1617 g_simple_async_result_set_op_res_gpointer (data->simple,
1618 g_object_ref (reply),
1621 send_message_with_reply_deliver (data);
1627 /* ---------------------------------------------------------------------------------------------------- */
1630 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1632 SendMessageData *data = user_data;
1634 CONNECTION_LOCK (data->connection);
1635 if (data->delivered)
1638 g_simple_async_result_set_error (data->simple,
1640 G_IO_ERROR_CANCELLED,
1641 _("Operation was cancelled"));
1643 send_message_with_reply_deliver (data);
1646 CONNECTION_UNLOCK (data->connection);
1650 /* Can be called from any thread with or without lock held */
1652 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1655 SendMessageData *data = user_data;
1656 GSource *idle_source;
1658 /* postpone cancellation to idle handler since we may be called directly
1659 * via g_cancellable_connect() (e.g. holding lock)
1661 idle_source = g_idle_source_new ();
1662 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1663 g_source_set_callback (idle_source,
1664 send_message_with_reply_cancelled_idle_cb,
1665 send_message_data_ref (data),
1666 (GDestroyNotify) send_message_data_unref);
1667 g_source_attach (idle_source, data->main_context);
1668 g_source_unref (idle_source);
1671 /* ---------------------------------------------------------------------------------------------------- */
1674 send_message_with_reply_timeout_cb (gpointer user_data)
1676 SendMessageData *data = user_data;
1678 CONNECTION_LOCK (data->connection);
1679 if (data->delivered)
1682 g_simple_async_result_set_error (data->simple,
1684 G_IO_ERROR_TIMED_OUT,
1685 _("Timeout was reached"));
1687 send_message_with_reply_deliver (data);
1690 CONNECTION_UNLOCK (data->connection);
1695 /* ---------------------------------------------------------------------------------------------------- */
1698 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1699 GDBusMessage *message,
1700 GDBusSendMessageFlags flags,
1702 volatile guint32 *out_serial,
1703 GCancellable *cancellable,
1704 GAsyncReadyCallback callback,
1707 GSimpleAsyncResult *simple;
1708 SendMessageData *data;
1710 volatile guint32 serial;
1714 if (out_serial == NULL)
1715 out_serial = &serial;
1717 if (timeout_msec == -1)
1718 timeout_msec = 25 * 1000;
1720 simple = g_simple_async_result_new (G_OBJECT (connection),
1723 g_dbus_connection_send_message_with_reply);
1725 if (g_cancellable_is_cancelled (cancellable))
1727 g_simple_async_result_set_error (simple,
1729 G_IO_ERROR_CANCELLED,
1730 _("Operation was cancelled"));
1731 g_simple_async_result_complete_in_idle (simple);
1732 g_object_unref (simple);
1736 if (connection->closed)
1738 g_simple_async_result_set_error (simple,
1741 _("The connection is closed"));
1742 g_simple_async_result_complete_in_idle (simple);
1743 g_object_unref (simple);
1748 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1750 g_simple_async_result_take_error (simple, error);
1751 g_simple_async_result_complete_in_idle (simple);
1752 g_object_unref (simple);
1756 data = g_new0 (SendMessageData, 1);
1757 data->ref_count = 1;
1758 data->connection = g_object_ref (connection);
1759 data->simple = simple;
1760 data->serial = *out_serial;
1761 data->main_context = g_main_context_get_thread_default ();
1762 if (data->main_context != NULL)
1763 g_main_context_ref (data->main_context);
1765 if (cancellable != NULL)
1767 data->cancellable = g_object_ref (cancellable);
1768 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1769 G_CALLBACK (send_message_with_reply_cancelled_cb),
1770 send_message_data_ref (data),
1771 (GDestroyNotify) send_message_data_unref);
1772 g_object_set_data_full (G_OBJECT (simple),
1774 g_object_ref (cancellable),
1775 (GDestroyNotify) g_object_unref);
1778 if (timeout_msec != G_MAXINT)
1780 data->timeout_source = g_timeout_source_new (timeout_msec);
1781 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1782 g_source_set_callback (data->timeout_source,
1783 send_message_with_reply_timeout_cb,
1784 send_message_data_ref (data),
1785 (GDestroyNotify) send_message_data_unref);
1786 g_source_attach (data->timeout_source, data->main_context);
1787 g_source_unref (data->timeout_source);
1790 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1791 GUINT_TO_POINTER (*out_serial),
1799 * g_dbus_connection_send_message_with_reply:
1800 * @connection: A #GDBusConnection.
1801 * @message: A #GDBusMessage.
1802 * @flags: Flags affecting how the message is sent.
1803 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1804 * timeout or %G_MAXINT for no timeout.
1805 * @out_serial: (out) (allow-none): Return location for serial number assigned
1806 * to @message when sending it or %NULL.
1807 * @cancellable: A #GCancellable or %NULL.
1808 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1809 * satisfied or %NULL if you don't care about the result.
1810 * @user_data: The data to pass to @callback.
1812 * Asynchronously sends @message to the peer represented by @connection.
1814 * Unless @flags contain the
1815 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1816 * will be assigned by @connection and set on @message via
1817 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1818 * serial number used will be written to this location prior to
1819 * submitting the message to the underlying transport.
1821 * If @connection is closed then the operation will fail with
1822 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1823 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1824 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1826 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1827 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1828 * of the thread you are calling this method from. You can then call
1829 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
1830 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
1832 * Note that @message must be unlocked, unless @flags contain the
1833 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1835 * See <xref linkend="gdbus-server"/> and <xref
1836 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1837 * low-level API to send and receive UNIX file descriptors.
1842 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
1843 GDBusMessage *message,
1844 GDBusSendMessageFlags flags,
1846 volatile guint32 *out_serial,
1847 GCancellable *cancellable,
1848 GAsyncReadyCallback callback,
1851 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1852 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
1853 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
1854 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
1856 CONNECTION_LOCK (connection);
1857 g_dbus_connection_send_message_with_reply_unlocked (connection,
1865 CONNECTION_UNLOCK (connection);
1869 * g_dbus_connection_send_message_with_reply_finish:
1870 * @connection: a #GDBusConnection
1871 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
1872 * @error: Return location for error or %NULL.
1874 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
1876 * Note that @error is only set if a local in-process error
1877 * occured. That is to say that the returned #GDBusMessage object may
1878 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1879 * g_dbus_message_to_gerror() to transcode this to a #GError.
1881 * See <xref linkend="gdbus-server"/> and <xref
1882 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1883 * low-level API to send and receive UNIX file descriptors.
1885 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
1890 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
1894 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1895 GDBusMessage *reply;
1896 GCancellable *cancellable;
1898 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1899 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
1903 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
1905 if (g_simple_async_result_propagate_error (simple, error))
1908 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
1909 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
1910 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
1912 g_object_unref (reply);
1914 g_set_error_literal (error,
1916 G_IO_ERROR_CANCELLED,
1917 _("Operation was cancelled"));
1923 /* ---------------------------------------------------------------------------------------------------- */
1928 GMainContext *context;
1930 } SendMessageSyncData;
1933 send_message_with_reply_sync_cb (GDBusConnection *connection,
1937 SendMessageSyncData *data = user_data;
1938 data->res = g_object_ref (res);
1939 g_main_loop_quit (data->loop);
1943 * g_dbus_connection_send_message_with_reply_sync:
1944 * @connection: A #GDBusConnection.
1945 * @message: A #GDBusMessage.
1946 * @flags: Flags affecting how the message is sent.
1947 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1948 * timeout or %G_MAXINT for no timeout.
1949 * @out_serial: (out) (allow-none): Return location for serial number assigned
1950 * to @message when sending it or %NULL.
1951 * @cancellable: A #GCancellable or %NULL.
1952 * @error: Return location for error or %NULL.
1954 * Synchronously sends @message to the peer represented by @connection
1955 * and blocks the calling thread until a reply is received or the
1956 * timeout is reached. See g_dbus_connection_send_message_with_reply()
1957 * for the asynchronous version of this method.
1959 * Unless @flags contain the
1960 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1961 * will be assigned by @connection and set on @message via
1962 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1963 * serial number used will be written to this location prior to
1964 * submitting the message to the underlying transport.
1966 * If @connection is closed then the operation will fail with
1967 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1968 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1969 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1971 * Note that @error is only set if a local in-process error
1972 * occured. That is to say that the returned #GDBusMessage object may
1973 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
1974 * g_dbus_message_to_gerror() to transcode this to a #GError.
1976 * See <xref linkend="gdbus-server"/> and <xref
1977 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1978 * low-level API to send and receive UNIX file descriptors.
1980 * Note that @message must be unlocked, unless @flags contain the
1981 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1983 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
1988 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
1989 GDBusMessage *message,
1990 GDBusSendMessageFlags flags,
1992 volatile guint32 *out_serial,
1993 GCancellable *cancellable,
1996 SendMessageSyncData *data;
1997 GDBusMessage *reply;
1999 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2000 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2001 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2002 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2003 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2005 data = g_new0 (SendMessageSyncData, 1);
2006 data->context = g_main_context_new ();
2007 data->loop = g_main_loop_new (data->context, FALSE);
2009 g_main_context_push_thread_default (data->context);
2011 g_dbus_connection_send_message_with_reply (connection,
2017 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2019 g_main_loop_run (data->loop);
2020 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2024 g_main_context_pop_thread_default (data->context);
2026 g_main_context_unref (data->context);
2027 g_main_loop_unref (data->loop);
2028 g_object_unref (data->res);
2034 /* ---------------------------------------------------------------------------------------------------- */
2038 GDBusMessageFilterFunction func;
2045 GDBusMessageFilterFunction filter_function;
2047 GDestroyNotify user_data_free_func;
2050 /* Called in worker's thread - we must not block */
2052 on_worker_message_received (GDBusWorker *worker,
2053 GDBusMessage *message,
2056 GDBusConnection *connection;
2057 FilterCallback *filters;
2062 G_LOCK (message_bus_lock);
2063 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2066 G_UNLOCK (message_bus_lock);
2069 connection = G_DBUS_CONNECTION (user_data);
2070 g_object_ref (connection);
2071 G_UNLOCK (message_bus_lock);
2073 //g_debug ("in on_worker_message_received");
2075 g_object_ref (message);
2076 g_dbus_message_lock (message);
2078 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2080 /* First collect the set of callback functions */
2081 CONNECTION_LOCK (connection);
2082 num_filters = connection->filters->len;
2083 filters = g_new0 (FilterCallback, num_filters);
2084 for (n = 0; n < num_filters; n++)
2086 FilterData *data = connection->filters->pdata[n];
2087 filters[n].func = data->filter_function;
2088 filters[n].user_data = data->user_data;
2090 CONNECTION_UNLOCK (connection);
2092 /* then call the filters in order (without holding the lock) */
2093 for (n = 0; n < num_filters; n++)
2095 message = filters[n].func (connection,
2098 filters[n].user_data);
2099 if (message == NULL)
2101 g_dbus_message_lock (message);
2104 /* Standard dispatch unless the filter ate the message - no need to
2105 * do anything if the message was altered
2107 if (message != NULL)
2109 GDBusMessageType message_type;
2111 message_type = g_dbus_message_get_message_type (message);
2112 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2114 guint32 reply_serial;
2115 SendMessageData *send_message_data;
2117 reply_serial = g_dbus_message_get_reply_serial (message);
2118 CONNECTION_LOCK (connection);
2119 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2120 GUINT_TO_POINTER (reply_serial));
2121 if (send_message_data != NULL)
2123 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2124 send_message_data_deliver_reply_unlocked (send_message_data, message);
2128 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2130 CONNECTION_UNLOCK (connection);
2132 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2134 CONNECTION_LOCK (connection);
2135 distribute_signals (connection, message);
2136 CONNECTION_UNLOCK (connection);
2138 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2140 CONNECTION_LOCK (connection);
2141 distribute_method_call (connection, message);
2142 CONNECTION_UNLOCK (connection);
2146 if (message != NULL)
2147 g_object_unref (message);
2148 g_object_unref (connection);
2152 /* Called in worker's thread */
2153 static GDBusMessage *
2154 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2155 GDBusMessage *message,
2158 GDBusConnection *connection;
2159 FilterCallback *filters;
2164 G_LOCK (message_bus_lock);
2165 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2168 G_UNLOCK (message_bus_lock);
2171 connection = G_DBUS_CONNECTION (user_data);
2172 g_object_ref (connection);
2173 G_UNLOCK (message_bus_lock);
2175 //g_debug ("in on_worker_message_about_to_be_sent");
2177 /* First collect the set of callback functions */
2178 CONNECTION_LOCK (connection);
2179 num_filters = connection->filters->len;
2180 filters = g_new0 (FilterCallback, num_filters);
2181 for (n = 0; n < num_filters; n++)
2183 FilterData *data = connection->filters->pdata[n];
2184 filters[n].func = data->filter_function;
2185 filters[n].user_data = data->user_data;
2187 CONNECTION_UNLOCK (connection);
2189 /* then call the filters in order (without holding the lock) */
2190 for (n = 0; n < num_filters; n++)
2192 g_dbus_message_lock (message);
2193 message = filters[n].func (connection,
2196 filters[n].user_data);
2197 if (message == NULL)
2201 g_object_unref (connection);
2207 /* Called in worker's thread - we must not block */
2209 on_worker_closed (GDBusWorker *worker,
2210 gboolean remote_peer_vanished,
2214 GDBusConnection *connection;
2217 G_LOCK (message_bus_lock);
2218 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2221 G_UNLOCK (message_bus_lock);
2224 connection = G_DBUS_CONNECTION (user_data);
2225 g_object_ref (connection);
2226 G_UNLOCK (message_bus_lock);
2228 //g_debug ("in on_worker_closed: %s", error->message);
2230 CONNECTION_LOCK (connection);
2231 if (!connection->closed)
2232 set_closed_unlocked (connection, remote_peer_vanished, error);
2233 CONNECTION_UNLOCK (connection);
2235 g_object_unref (connection);
2238 /* ---------------------------------------------------------------------------------------------------- */
2240 /* Determines the biggest set of capabilities we can support on this connection */
2241 static GDBusCapabilityFlags
2242 get_offered_capabilities_max (GDBusConnection *connection)
2244 GDBusCapabilityFlags ret;
2245 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2247 if (G_IS_UNIX_CONNECTION (connection->stream))
2248 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2254 initable_init (GInitable *initable,
2255 GCancellable *cancellable,
2258 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2261 /* This method needs to be idempotent to work with the singleton
2262 * pattern. See the docs for g_initable_init(). We implement this by
2265 * Unfortunately we can't use the main lock since the on_worker_*()
2266 * callbacks above needs the lock during initialization (for message
2267 * bus connections we do a synchronous Hello() call on the bus).
2269 g_mutex_lock (connection->init_lock);
2273 /* First, handle the case where the connection already has an
2274 * initialization error set.
2276 if (connection->initialization_error != NULL)
2279 /* Also make this a no-op if we're already initialized fine */
2280 if (connection->is_initialized)
2286 g_assert (connection->initialization_error == NULL && !connection->is_initialized);
2288 /* The user can pass multiple (but mutally exclusive) construct
2291 * - stream (of type GIOStream)
2292 * - address (of type gchar*)
2294 * At the end of the day we end up with a non-NULL GIOStream
2295 * object in connection->stream.
2297 if (connection->address != NULL)
2299 g_assert (connection->stream == NULL);
2301 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2302 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2304 g_set_error_literal (error,
2306 G_IO_ERROR_INVALID_ARGUMENT,
2307 _("Unsupported flags encountered when constructing a client-side connection"));
2311 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2312 NULL, /* TODO: out_guid */
2314 &connection->initialization_error);
2315 if (connection->stream == NULL)
2318 else if (connection->stream != NULL)
2324 g_assert_not_reached ();
2327 /* Authenticate the connection */
2328 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2330 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2331 g_assert (connection->guid != NULL);
2332 connection->auth = _g_dbus_auth_new (connection->stream);
2333 if (!_g_dbus_auth_run_server (connection->auth,
2334 connection->authentication_observer,
2336 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2337 get_offered_capabilities_max (connection),
2338 &connection->capabilities,
2339 &connection->credentials,
2341 &connection->initialization_error))
2344 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2346 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2347 g_assert (connection->guid == NULL);
2348 connection->auth = _g_dbus_auth_new (connection->stream);
2349 connection->guid = _g_dbus_auth_run_client (connection->auth,
2350 get_offered_capabilities_max (connection),
2351 &connection->capabilities,
2353 &connection->initialization_error);
2354 if (connection->guid == NULL)
2358 if (connection->authentication_observer != NULL)
2360 g_object_unref (connection->authentication_observer);
2361 connection->authentication_observer = NULL;
2364 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2366 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2369 /* We want all IO operations to be non-blocking since they happen in
2370 * the worker thread which is shared by _all_ connections.
2372 if (G_IS_SOCKET_CONNECTION (connection->stream))
2374 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2378 G_LOCK (message_bus_lock);
2379 if (alive_connections == NULL)
2380 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2381 g_hash_table_insert (alive_connections, connection, connection);
2382 G_UNLOCK (message_bus_lock);
2384 connection->worker = _g_dbus_worker_new (connection->stream,
2385 connection->capabilities,
2386 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2387 on_worker_message_received,
2388 on_worker_message_about_to_be_sent,
2392 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2393 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2395 GVariant *hello_result;
2397 /* we could lift this restriction by adding code in gdbusprivate.c */
2398 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2400 g_set_error_literal (&connection->initialization_error,
2403 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2407 hello_result = g_dbus_connection_call_sync (connection,
2408 "org.freedesktop.DBus", /* name */
2409 "/org/freedesktop/DBus", /* path */
2410 "org.freedesktop.DBus", /* interface */
2412 NULL, /* parameters */
2413 G_VARIANT_TYPE ("(s)"),
2414 G_DBUS_CALL_FLAGS_NONE,
2416 NULL, /* TODO: cancellable */
2417 &connection->initialization_error);
2418 if (hello_result == NULL)
2421 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2422 g_variant_unref (hello_result);
2423 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2426 connection->is_initialized = TRUE;
2432 g_assert (connection->initialization_error != NULL);
2433 g_propagate_error (error, g_error_copy (connection->initialization_error));
2436 g_mutex_unlock (connection->init_lock);
2442 initable_iface_init (GInitableIface *initable_iface)
2444 initable_iface->init = initable_init;
2447 /* ---------------------------------------------------------------------------------------------------- */
2450 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2455 /* ---------------------------------------------------------------------------------------------------- */
2458 * g_dbus_connection_new:
2459 * @stream: A #GIOStream.
2460 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2461 * @flags: Flags describing how to make the connection.
2462 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2463 * @cancellable: A #GCancellable or %NULL.
2464 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2465 * @user_data: The data to pass to @callback.
2467 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2468 * with the end represented by @stream.
2470 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2471 * will be put into non-blocking mode.
2473 * If @observer is not %NULL it may be used to control the
2474 * authentication process.
2476 * When the operation is finished, @callback will be invoked. You can
2477 * then call g_dbus_connection_new_finish() to get the result of the
2480 * This is a asynchronous failable constructor. See
2481 * g_dbus_connection_new_sync() for the synchronous
2487 g_dbus_connection_new (GIOStream *stream,
2489 GDBusConnectionFlags flags,
2490 GDBusAuthObserver *observer,
2491 GCancellable *cancellable,
2492 GAsyncReadyCallback callback,
2495 g_return_if_fail (G_IS_IO_STREAM (stream));
2496 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2504 "authentication-observer", observer,
2509 * g_dbus_connection_new_finish:
2510 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2511 * @error: Return location for error or %NULL.
2513 * Finishes an operation started with g_dbus_connection_new().
2515 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2520 g_dbus_connection_new_finish (GAsyncResult *res,
2524 GObject *source_object;
2526 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2527 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2529 source_object = g_async_result_get_source_object (res);
2530 g_assert (source_object != NULL);
2531 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2534 g_object_unref (source_object);
2536 return G_DBUS_CONNECTION (object);
2542 * g_dbus_connection_new_sync:
2543 * @stream: A #GIOStream.
2544 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2545 * @flags: Flags describing how to make the connection.
2546 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2547 * @cancellable: A #GCancellable or %NULL.
2548 * @error: Return location for error or %NULL.
2550 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2551 * with the end represented by @stream.
2553 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2554 * will be put into non-blocking mode.
2556 * If @observer is not %NULL it may be used to control the
2557 * authentication process.
2559 * This is a synchronous failable constructor. See
2560 * g_dbus_connection_new() for the asynchronous version.
2562 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2567 g_dbus_connection_new_sync (GIOStream *stream,
2569 GDBusConnectionFlags flags,
2570 GDBusAuthObserver *observer,
2571 GCancellable *cancellable,
2574 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2575 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2576 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2582 "authentication-observer", observer,
2586 /* ---------------------------------------------------------------------------------------------------- */
2589 * g_dbus_connection_new_for_address:
2590 * @address: A D-Bus address.
2591 * @flags: Flags describing how to make the connection.
2592 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2593 * @cancellable: A #GCancellable or %NULL.
2594 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2595 * @user_data: The data to pass to @callback.
2597 * Asynchronously connects and sets up a D-Bus client connection for
2598 * exchanging D-Bus messages with an endpoint specified by @address
2599 * which must be in the D-Bus address format.
2601 * This constructor can only be used to initiate client-side
2602 * connections - use g_dbus_connection_new() if you need to act as the
2603 * server. In particular, @flags cannot contain the
2604 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2605 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2607 * When the operation is finished, @callback will be invoked. You can
2608 * then call g_dbus_connection_new_finish() to get the result of the
2611 * If @observer is not %NULL it may be used to control the
2612 * authentication process.
2614 * This is a asynchronous failable constructor. See
2615 * g_dbus_connection_new_for_address_sync() for the synchronous
2621 g_dbus_connection_new_for_address (const gchar *address,
2622 GDBusConnectionFlags flags,
2623 GDBusAuthObserver *observer,
2624 GCancellable *cancellable,
2625 GAsyncReadyCallback callback,
2628 g_return_if_fail (address != NULL);
2629 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2636 "authentication-observer", observer,
2641 * g_dbus_connection_new_for_address_finish:
2642 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2643 * @error: Return location for error or %NULL.
2645 * Finishes an operation started with g_dbus_connection_new_for_address().
2647 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2652 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2656 GObject *source_object;
2658 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2659 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2661 source_object = g_async_result_get_source_object (res);
2662 g_assert (source_object != NULL);
2663 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2666 g_object_unref (source_object);
2668 return G_DBUS_CONNECTION (object);
2674 * g_dbus_connection_new_for_address_sync:
2675 * @address: A D-Bus address.
2676 * @flags: Flags describing how to make the connection.
2677 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2678 * @cancellable: A #GCancellable or %NULL.
2679 * @error: Return location for error or %NULL.
2681 * Synchronously connects and sets up a D-Bus client connection for
2682 * exchanging D-Bus messages with an endpoint specified by @address
2683 * which must be in the D-Bus address format.
2685 * This constructor can only be used to initiate client-side
2686 * connections - use g_dbus_connection_new_sync() if you need to act
2687 * as the server. In particular, @flags cannot contain the
2688 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2689 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2691 * This is a synchronous failable constructor. See
2692 * g_dbus_connection_new_for_address() for the asynchronous version.
2694 * If @observer is not %NULL it may be used to control the
2695 * authentication process.
2697 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2702 g_dbus_connection_new_for_address_sync (const gchar *address,
2703 GDBusConnectionFlags flags,
2704 GDBusAuthObserver *observer,
2705 GCancellable *cancellable,
2708 g_return_val_if_fail (address != NULL, NULL);
2709 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2710 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2715 "authentication-observer", observer,
2719 /* ---------------------------------------------------------------------------------------------------- */
2722 * g_dbus_connection_set_exit_on_close:
2723 * @connection: A #GDBusConnection.
2724 * @exit_on_close: Whether the process should be terminated
2725 * when @connection is closed by the remote peer.
2727 * Sets whether the process should be terminated when @connection is
2728 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2731 * Note that this function should be used with care. Most modern UNIX
2732 * desktops tie the notion of a user session the session bus, and expect
2733 * all of a users applications to quit when their bus connection goes away.
2734 * If you are setting @exit_on_close to %FALSE for the shared session
2735 * bus connection, you should make sure that your application exits
2736 * when the user session ends.
2741 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2742 gboolean exit_on_close)
2744 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2745 connection->exit_on_close = exit_on_close;
2749 * g_dbus_connection_get_exit_on_close:
2750 * @connection: A #GDBusConnection.
2752 * Gets whether the process is terminated when @connection is
2753 * closed by the remote peer. See
2754 * #GDBusConnection:exit-on-close for more details.
2756 * Returns: Whether the process is terminated when @connection is
2757 * closed by the remote peer.
2762 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2764 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2765 return connection->exit_on_close;
2769 * g_dbus_connection_get_guid:
2770 * @connection: A #GDBusConnection.
2772 * The GUID of the peer performing the role of server when
2773 * authenticating. See #GDBusConnection:guid for more details.
2775 * Returns: The GUID. Do not free this string, it is owned by
2781 g_dbus_connection_get_guid (GDBusConnection *connection)
2783 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2784 return connection->guid;
2788 * g_dbus_connection_get_unique_name:
2789 * @connection: A #GDBusConnection.
2791 * Gets the unique name of @connection as assigned by the message
2792 * bus. This can also be used to figure out if @connection is a
2793 * message bus connection.
2795 * Returns: The unique name or %NULL if @connection is not a message
2796 * bus connection. Do not free this string, it is owned by
2802 g_dbus_connection_get_unique_name (GDBusConnection *connection)
2804 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2805 return connection->bus_unique_name;
2809 * g_dbus_connection_get_peer_credentials:
2810 * @connection: A #GDBusConnection.
2812 * Gets the credentials of the authenticated peer. This will always
2813 * return %NULL unless @connection acted as a server
2814 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
2815 * when set up and the client passed credentials as part of the
2816 * authentication process.
2818 * In a message bus setup, the message bus is always the server and
2819 * each application is a client. So this method will always return
2820 * %NULL for message bus clients.
2822 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
2823 * this object, it is owned by @connection.
2828 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
2830 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2831 return connection->credentials;
2834 /* ---------------------------------------------------------------------------------------------------- */
2836 static guint _global_filter_id = 1;
2839 * g_dbus_connection_add_filter:
2840 * @connection: A #GDBusConnection.
2841 * @filter_function: A filter function.
2842 * @user_data: User data to pass to @filter_function.
2843 * @user_data_free_func: Function to free @user_data with when filter
2844 * is removed or %NULL.
2846 * Adds a message filter. Filters are handlers that are run on all
2847 * incoming and outgoing messages, prior to standard dispatch. Filters
2848 * are run in the order that they were added. The same handler can be
2849 * added as a filter more than once, in which case it will be run more
2850 * than once. Filters added during a filter callback won't be run on
2851 * the message being processed. Filter functions are allowed to modify
2852 * and even drop messages.
2854 * Note that filters are run in a dedicated message handling thread so
2855 * they can't block and, generally, can't do anything but signal a
2856 * worker thread. Also note that filters are rarely needed - use API
2857 * such as g_dbus_connection_send_message_with_reply(),
2858 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
2860 * If a filter consumes an incoming message the message is not
2861 * dispatched anywhere else - not even the standard dispatch machinery
2862 * (that API such as g_dbus_connection_signal_subscribe() and
2863 * g_dbus_connection_send_message_with_reply() relies on) will see the
2864 * message. Similary, if a filter consumes an outgoing message, the
2865 * message will not be sent to the other peer.
2867 * Returns: A filter identifier that can be used with
2868 * g_dbus_connection_remove_filter().
2873 g_dbus_connection_add_filter (GDBusConnection *connection,
2874 GDBusMessageFilterFunction filter_function,
2876 GDestroyNotify user_data_free_func)
2880 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
2881 g_return_val_if_fail (filter_function != NULL, 0);
2883 CONNECTION_LOCK (connection);
2884 data = g_new0 (FilterData, 1);
2885 data->id = _global_filter_id++; /* TODO: overflow etc. */
2886 data->filter_function = filter_function;
2887 data->user_data = user_data;
2888 data->user_data_free_func = user_data_free_func;
2889 g_ptr_array_add (connection->filters, data);
2890 CONNECTION_UNLOCK (connection);
2895 /* only called from finalize(), removes all filters */
2897 purge_all_filters (GDBusConnection *connection)
2900 for (n = 0; n < connection->filters->len; n++)
2902 FilterData *data = connection->filters->pdata[n];
2903 if (data->user_data_free_func != NULL)
2904 data->user_data_free_func (data->user_data);
2910 * g_dbus_connection_remove_filter:
2911 * @connection: a #GDBusConnection
2912 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
2919 g_dbus_connection_remove_filter (GDBusConnection *connection,
2923 FilterData *to_destroy;
2925 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2927 CONNECTION_LOCK (connection);
2929 for (n = 0; n < connection->filters->len; n++)
2931 FilterData *data = connection->filters->pdata[n];
2932 if (data->id == filter_id)
2934 g_ptr_array_remove_index (connection->filters, n);
2939 CONNECTION_UNLOCK (connection);
2941 /* do free without holding lock */
2942 if (to_destroy != NULL)
2944 if (to_destroy->user_data_free_func != NULL)
2945 to_destroy->user_data_free_func (to_destroy->user_data);
2946 g_free (to_destroy);
2950 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
2954 /* ---------------------------------------------------------------------------------------------------- */
2960 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
2961 gchar *interface_name;
2965 GArray *subscribers;
2970 GDBusSignalCallback callback;
2972 GDestroyNotify user_data_free_func;
2974 GMainContext *context;
2978 signal_data_free (SignalData *signal_data)
2980 g_free (signal_data->rule);
2981 g_free (signal_data->sender);
2982 g_free (signal_data->sender_unique_name);
2983 g_free (signal_data->interface_name);
2984 g_free (signal_data->member);
2985 g_free (signal_data->object_path);
2986 g_free (signal_data->arg0);
2987 g_array_free (signal_data->subscribers, TRUE);
2988 g_free (signal_data);
2992 args_to_rule (const gchar *sender,
2993 const gchar *interface_name,
2994 const gchar *member,
2995 const gchar *object_path,
3001 rule = g_string_new ("type='signal'");
3003 g_string_prepend_c (rule, '-');
3005 g_string_append_printf (rule, ",sender='%s'", sender);
3006 if (interface_name != NULL)
3007 g_string_append_printf (rule, ",interface='%s'", interface_name);
3009 g_string_append_printf (rule, ",member='%s'", member);
3010 if (object_path != NULL)
3011 g_string_append_printf (rule, ",path='%s'", object_path);
3013 g_string_append_printf (rule, ",arg0='%s'", arg0);
3015 return g_string_free (rule, FALSE);
3018 static guint _global_subscriber_id = 1;
3019 static guint _global_registration_id = 1;
3020 static guint _global_subtree_registration_id = 1;
3022 /* ---------------------------------------------------------------------------------------------------- */
3024 /* must hold lock when calling */
3026 add_match_rule (GDBusConnection *connection,
3027 const gchar *match_rule)
3030 GDBusMessage *message;
3032 if (match_rule[0] == '-')
3035 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3036 "/org/freedesktop/DBus", /* path */
3037 "org.freedesktop.DBus", /* interface */
3039 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3041 if (!g_dbus_connection_send_message_unlocked (connection,
3043 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3047 g_critical ("Error while sending AddMatch() message: %s", error->message);
3048 g_error_free (error);
3050 g_object_unref (message);
3053 /* ---------------------------------------------------------------------------------------------------- */
3055 /* must hold lock when calling */
3057 remove_match_rule (GDBusConnection *connection,
3058 const gchar *match_rule)
3061 GDBusMessage *message;
3063 if (match_rule[0] == '-')
3066 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3067 "/org/freedesktop/DBus", /* path */
3068 "org.freedesktop.DBus", /* interface */
3070 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3073 if (!g_dbus_connection_send_message_unlocked (connection,
3075 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3079 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3080 g_error_free (error);
3082 g_object_unref (message);
3085 /* ---------------------------------------------------------------------------------------------------- */
3088 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3090 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3091 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3092 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3093 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3094 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3097 /* ---------------------------------------------------------------------------------------------------- */
3100 * g_dbus_connection_signal_subscribe:
3101 * @connection: A #GDBusConnection.
3102 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3103 * or %NULL to listen from all senders.
3104 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3105 * match on all interfaces.
3106 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3107 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3108 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3109 * to match on all kinds of arguments.
3110 * @flags: Flags describing how to subscribe to the signal (currently unused).
3111 * @callback: Callback to invoke when there is a signal matching the requested data.
3112 * @user_data: User data to pass to @callback.
3113 * @user_data_free_func: Function to free @user_data with when 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 if (parameters != NULL)
3427 g_variant_unref (parameters);
3433 signal_instance_free (SignalInstance *signal_instance)
3435 g_object_unref (signal_instance->message);
3436 g_object_unref (signal_instance->connection);
3437 g_free (signal_instance);
3440 /* called in message handler thread WITH lock held */
3442 schedule_callbacks (GDBusConnection *connection,
3443 GPtrArray *signal_data_array,
3444 GDBusMessage *message,
3445 const gchar *sender)
3448 const gchar *interface;
3449 const gchar *member;
3458 interface = g_dbus_message_get_interface (message);
3459 member = g_dbus_message_get_member (message);
3460 path = g_dbus_message_get_path (message);
3461 arg0 = g_dbus_message_get_arg0 (message);
3464 g_print ("In schedule_callbacks:\n"
3466 " interface = `%s'\n"
3477 /* TODO: if this is slow, then we can change signal_data_array into
3478 * map_object_path_to_signal_data_array or something.
3480 for (n = 0; n < signal_data_array->len; n++)
3482 SignalData *signal_data = signal_data_array->pdata[n];
3484 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3487 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3490 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3493 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3496 for (m = 0; m < signal_data->subscribers->len; m++)
3498 SignalSubscriber *subscriber;
3499 GSource *idle_source;
3500 SignalInstance *signal_instance;
3502 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3504 signal_instance = g_new0 (SignalInstance, 1);
3505 signal_instance->subscription_id = subscriber->id;
3506 signal_instance->callback = subscriber->callback;
3507 signal_instance->user_data = subscriber->user_data;
3508 signal_instance->message = g_object_ref (message);
3509 signal_instance->connection = g_object_ref (connection);
3510 signal_instance->sender = sender;
3511 signal_instance->path = path;
3512 signal_instance->interface = interface;
3513 signal_instance->member = member;
3515 idle_source = g_idle_source_new ();
3516 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3517 g_source_set_callback (idle_source,
3518 emit_signal_instance_in_idle_cb,
3520 (GDestroyNotify) signal_instance_free);
3521 g_source_attach (idle_source, subscriber->context);
3522 g_source_unref (idle_source);
3527 /* called in message handler thread with lock held */
3529 distribute_signals (GDBusConnection *connection,
3530 GDBusMessage *message)
3532 GPtrArray *signal_data_array;
3533 const gchar *sender;
3535 sender = g_dbus_message_get_sender (message);
3537 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3539 _g_dbus_debug_print_lock ();
3540 g_print ("========================================================================\n"
3541 "GDBus-debug:Signal:\n"
3542 " <<<< RECEIVED SIGNAL %s.%s\n"
3544 " sent by name %s\n",
3545 g_dbus_message_get_interface (message),
3546 g_dbus_message_get_member (message),
3547 g_dbus_message_get_path (message),
3548 sender != NULL ? sender : "(none)");
3549 _g_dbus_debug_print_unlock ();
3552 /* collect subscribers that match on sender */
3555 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3556 if (signal_data_array != NULL)
3557 schedule_callbacks (connection, signal_data_array, message, sender);
3560 /* collect subscribers not matching on sender */
3561 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3562 if (signal_data_array != NULL)
3563 schedule_callbacks (connection, signal_data_array, message, sender);
3566 /* ---------------------------------------------------------------------------------------------------- */
3568 /* only called from finalize(), removes all subscriptions */
3570 purge_all_signal_subscriptions (GDBusConnection *connection)
3572 GHashTableIter iter;
3575 GArray *subscribers;
3578 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3579 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3580 while (g_hash_table_iter_next (&iter, &key, NULL))
3582 guint subscription_id = GPOINTER_TO_UINT (key);
3583 g_array_append_val (ids, subscription_id);
3586 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3587 for (n = 0; n < ids->len; n++)
3589 guint subscription_id = g_array_index (ids, guint, n);
3590 unsubscribe_id_internal (connection,
3594 g_array_free (ids, TRUE);
3596 /* call GDestroyNotify without lock held */
3597 for (n = 0; n < subscribers->len; n++)
3599 SignalSubscriber *subscriber;
3600 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3601 call_destroy_notify (subscriber->context,
3602 subscriber->user_data_free_func,
3603 subscriber->user_data);
3604 if (subscriber->context != NULL)
3605 g_main_context_unref (subscriber->context);
3608 g_array_free (subscribers, TRUE);
3611 /* ---------------------------------------------------------------------------------------------------- */
3613 static GDBusInterfaceVTable *
3614 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3616 /* Don't waste memory by copying padding - remember to update this
3617 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3619 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3623 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3628 /* ---------------------------------------------------------------------------------------------------- */
3630 static GDBusSubtreeVTable *
3631 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3633 /* Don't waste memory by copying padding - remember to update this
3634 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3636 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3640 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3645 /* ---------------------------------------------------------------------------------------------------- */
3647 struct ExportedObject
3650 GDBusConnection *connection;
3652 /* maps gchar* -> ExportedInterface* */
3653 GHashTable *map_if_name_to_ei;
3656 /* only called with lock held */
3658 exported_object_free (ExportedObject *eo)
3660 g_free (eo->object_path);
3661 g_hash_table_unref (eo->map_if_name_to_ei);
3670 gchar *interface_name;
3671 GDBusInterfaceVTable *vtable;
3672 GDBusInterfaceInfo *interface_info;
3674 GMainContext *context;
3676 GDestroyNotify user_data_free_func;
3677 } ExportedInterface;
3679 /* called with lock held */
3681 exported_interface_free (ExportedInterface *ei)
3683 g_dbus_interface_info_cache_release (ei->interface_info);
3684 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3686 call_destroy_notify (ei->context,
3687 ei->user_data_free_func,
3690 if (ei->context != NULL)
3691 g_main_context_unref (ei->context);
3693 g_free (ei->interface_name);
3694 _g_dbus_interface_vtable_free (ei->vtable);
3698 /* ---------------------------------------------------------------------------------------------------- */
3700 /* Convenience function to check if @registration_id (if not zero) or
3701 * @subtree_registration_id (if not zero) has been unregistered. If
3702 * so, returns %TRUE.
3704 * Caller must *not* hold lock.
3707 has_object_been_unregistered (GDBusConnection *connection,
3708 guint registration_id,
3709 guint subtree_registration_id)
3713 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3717 CONNECTION_LOCK (connection);
3718 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3719 GUINT_TO_POINTER (registration_id)) == NULL)
3723 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3724 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3728 CONNECTION_UNLOCK (connection);
3733 /* ---------------------------------------------------------------------------------------------------- */
3737 GDBusConnection *connection;
3738 GDBusMessage *message;
3740 const gchar *property_name;
3741 const GDBusInterfaceVTable *vtable;
3742 GDBusInterfaceInfo *interface_info;
3743 const GDBusPropertyInfo *property_info;
3744 guint registration_id;
3745 guint subtree_registration_id;
3749 property_data_free (PropertyData *data)
3751 g_object_unref (data->connection);
3752 g_object_unref (data->message);
3756 /* called in thread where object was registered - no locks held */
3758 invoke_get_property_in_idle_cb (gpointer _data)
3760 PropertyData *data = _data;
3763 GDBusMessage *reply;
3765 if (has_object_been_unregistered (data->connection,
3766 data->registration_id,
3767 data->subtree_registration_id))
3769 reply = g_dbus_message_new_method_error (data->message,
3770 "org.freedesktop.DBus.Error.UnknownMethod",
3771 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3772 g_dbus_message_get_path (data->message));
3773 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3774 g_object_unref (reply);
3779 value = data->vtable->get_property (data->connection,
3780 g_dbus_message_get_sender (data->message),
3781 g_dbus_message_get_path (data->message),
3782 data->interface_info->name,
3783 data->property_name,
3790 g_assert_no_error (error);
3792 if (g_variant_is_floating (value))
3793 g_variant_ref_sink (value);
3794 reply = g_dbus_message_new_method_reply (data->message);
3795 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
3796 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3797 g_variant_unref (value);
3798 g_object_unref (reply);
3802 gchar *dbus_error_name;
3803 g_assert (error != NULL);
3804 dbus_error_name = g_dbus_error_encode_gerror (error);
3805 reply = g_dbus_message_new_method_error_literal (data->message,
3808 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3809 g_free (dbus_error_name);
3810 g_error_free (error);
3811 g_object_unref (reply);
3818 /* called in thread where object was registered - no locks held */
3820 invoke_set_property_in_idle_cb (gpointer _data)
3822 PropertyData *data = _data;
3824 GDBusMessage *reply;
3830 g_variant_get (g_dbus_message_get_body (data->message),
3836 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
3837 * of the given value is wrong
3839 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
3841 reply = g_dbus_message_new_method_error (data->message,
3842 "org.freedesktop.DBus.Error.InvalidArgs",
3843 _("Error setting property `%s': Expected type `%s' but got `%s'"),
3844 data->property_info->name,
3845 data->property_info->signature,
3846 g_variant_get_type_string (value));
3850 if (!data->vtable->set_property (data->connection,
3851 g_dbus_message_get_sender (data->message),
3852 g_dbus_message_get_path (data->message),
3853 data->interface_info->name,
3854 data->property_name,
3859 gchar *dbus_error_name;
3860 g_assert (error != NULL);
3861 dbus_error_name = g_dbus_error_encode_gerror (error);
3862 reply = g_dbus_message_new_method_error_literal (data->message,
3865 g_free (dbus_error_name);
3866 g_error_free (error);
3870 reply = g_dbus_message_new_method_reply (data->message);
3874 g_assert (reply != NULL);
3875 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3876 g_object_unref (reply);
3877 g_variant_unref (value);
3882 /* called with lock held */
3884 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
3885 GDBusMessage *message,
3886 guint registration_id,
3887 guint subtree_registration_id,
3889 GDBusInterfaceInfo *interface_info,
3890 const GDBusInterfaceVTable *vtable,
3891 GMainContext *main_context,
3895 const char *interface_name;
3896 const char *property_name;
3897 const GDBusPropertyInfo *property_info;
3898 GSource *idle_source;
3899 PropertyData *property_data;
3900 GDBusMessage *reply;
3905 g_variant_get (g_dbus_message_get_body (message),
3910 g_variant_get (g_dbus_message_get_body (message),
3919 if (vtable == NULL || vtable->get_property == NULL)
3924 if (vtable == NULL || vtable->set_property == NULL)
3928 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
3930 property_info = NULL;
3932 /* TODO: the cost of this is O(n) - it might be worth caching the result */
3933 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
3934 if (property_info == NULL)
3936 reply = g_dbus_message_new_method_error (message,
3937 "org.freedesktop.DBus.Error.InvalidArgs",
3938 _("No such property `%s'"),
3940 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3941 g_object_unref (reply);
3946 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
3948 reply = g_dbus_message_new_method_error (message,
3949 "org.freedesktop.DBus.Error.InvalidArgs",
3950 _("Property `%s' is not readable"),
3952 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3953 g_object_unref (reply);
3957 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
3959 reply = g_dbus_message_new_method_error (message,
3960 "org.freedesktop.DBus.Error.InvalidArgs",
3961 _("Property `%s' is not writable"),
3963 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3964 g_object_unref (reply);
3969 /* ok, got the property info - call user code in an idle handler */
3970 property_data = g_new0 (PropertyData, 1);
3971 property_data->connection = g_object_ref (connection);
3972 property_data->message = g_object_ref (message);
3973 property_data->user_data = user_data;
3974 property_data->property_name = property_name;
3975 property_data->vtable = vtable;
3976 property_data->interface_info = interface_info;
3977 property_data->property_info = property_info;
3978 property_data->registration_id = registration_id;
3979 property_data->subtree_registration_id = subtree_registration_id;
3981 idle_source = g_idle_source_new ();
3982 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3983 g_source_set_callback (idle_source,
3984 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
3986 (GDestroyNotify) property_data_free);
3987 g_source_attach (idle_source, main_context);
3988 g_source_unref (idle_source);
3996 /* called with lock held */
3998 handle_getset_property (GDBusConnection *connection,
4000 GDBusMessage *message,
4003 ExportedInterface *ei;
4005 const char *interface_name;
4006 const char *property_name;
4011 g_variant_get (g_dbus_message_get_body (message),
4016 g_variant_get (g_dbus_message_get_body (message),
4022 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4023 * no such interface registered
4025 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4028 GDBusMessage *reply;
4029 reply = g_dbus_message_new_method_error (message,
4030 "org.freedesktop.DBus.Error.InvalidArgs",
4031 _("No such interface `%s'"),
4033 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4034 g_object_unref (reply);
4039 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4052 /* ---------------------------------------------------------------------------------------------------- */
4056 GDBusConnection *connection;
4057 GDBusMessage *message;
4059 const GDBusInterfaceVTable *vtable;
4060 GDBusInterfaceInfo *interface_info;
4061 guint registration_id;
4062 guint subtree_registration_id;
4063 } PropertyGetAllData;
4066 property_get_all_data_free (PropertyData *data)
4068 g_object_unref (data->connection);
4069 g_object_unref (data->message);
4073 /* called in thread where object was registered - no locks held */
4075 invoke_get_all_properties_in_idle_cb (gpointer _data)
4077 PropertyGetAllData *data = _data;
4078 GVariantBuilder builder;
4079 GDBusMessage *reply;
4082 if (has_object_been_unregistered (data->connection,
4083 data->registration_id,
4084 data->subtree_registration_id))
4086 reply = g_dbus_message_new_method_error (data->message,
4087 "org.freedesktop.DBus.Error.UnknownMethod",
4088 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4089 g_dbus_message_get_path (data->message));
4090 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4091 g_object_unref (reply);
4095 /* TODO: Right now we never fail this call - we just omit values if
4096 * a get_property() call is failing.
4098 * We could fail the whole call if just a single get_property() call
4099 * returns an error. We need clarification in the D-Bus spec about this.
4101 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4102 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4103 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4105 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4108 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4111 value = data->vtable->get_property (data->connection,
4112 g_dbus_message_get_sender (data->message),
4113 g_dbus_message_get_path (data->message),
4114 data->interface_info->name,
4115 property_info->name,
4122 if (g_variant_is_floating (value))
4123 g_variant_ref_sink (value);
4124 g_variant_builder_add (&builder,
4126 property_info->name,
4128 g_variant_unref (value);
4130 g_variant_builder_close (&builder);
4132 reply = g_dbus_message_new_method_reply (data->message);
4133 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4134 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4135 g_object_unref (reply);
4141 /* called with lock held */
4143 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4144 GDBusMessage *message,
4145 guint registration_id,
4146 guint subtree_registration_id,
4147 GDBusInterfaceInfo *interface_info,
4148 const GDBusInterfaceVTable *vtable,
4149 GMainContext *main_context,
4153 const char *interface_name;
4154 GSource *idle_source;
4155 PropertyGetAllData *property_get_all_data;
4159 g_variant_get (g_dbus_message_get_body (message),
4163 if (vtable == NULL || vtable->get_property == NULL)
4166 /* ok, got the property info - call user in an idle handler */
4167 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4168 property_get_all_data->connection = g_object_ref (connection);
4169 property_get_all_data->message = g_object_ref (message);
4170 property_get_all_data->user_data = user_data;
4171 property_get_all_data->vtable = vtable;
4172 property_get_all_data->interface_info = interface_info;
4173 property_get_all_data->registration_id = registration_id;
4174 property_get_all_data->subtree_registration_id = subtree_registration_id;
4176 idle_source = g_idle_source_new ();
4177 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4178 g_source_set_callback (idle_source,
4179 invoke_get_all_properties_in_idle_cb,
4180 property_get_all_data,
4181 (GDestroyNotify) property_get_all_data_free);
4182 g_source_attach (idle_source, main_context);
4183 g_source_unref (idle_source);
4191 /* called with lock held */
4193 handle_get_all_properties (GDBusConnection *connection,
4195 GDBusMessage *message)
4197 ExportedInterface *ei;
4199 const char *interface_name;
4203 g_variant_get (g_dbus_message_get_body (message),
4207 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4208 * no such interface registered
4210 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4213 GDBusMessage *reply;
4214 reply = g_dbus_message_new_method_error (message,
4215 "org.freedesktop.DBus.Error.InvalidArgs",
4216 _("No such interface"),
4218 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4219 g_object_unref (reply);
4224 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4236 /* ---------------------------------------------------------------------------------------------------- */
4238 static const gchar introspect_header[] =
4239 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4240 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4241 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4244 static const gchar introspect_tail[] =
4247 static const gchar introspect_properties_interface[] =
4248 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4249 " <method name=\"Get\">\n"
4250 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4251 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4252 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4254 " <method name=\"GetAll\">\n"
4255 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4256 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4258 " <method name=\"Set\">\n"
4259 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4260 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4261 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4263 " <signal name=\"PropertiesChanged\">\n"
4264 " <arg type=\"s\" name=\"interface_name\"/>\n"
4265 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4266 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4270 static const gchar introspect_introspectable_interface[] =
4271 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4272 " <method name=\"Introspect\">\n"
4273 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4276 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4277 " <method name=\"Ping\"/>\n"
4278 " <method name=\"GetMachineId\">\n"
4279 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4284 introspect_append_header (GString *s)
4286 g_string_append (s, introspect_header);
4290 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4292 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4298 begin = object_path + path_len;
4299 end = strchr (begin, '/');
4301 s = g_strndup (begin, end - begin);
4303 s = g_strdup (begin);
4305 if (g_hash_table_lookup (set, s) == NULL)
4306 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4312 /* TODO: we want a nicer public interface for this */
4314 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4319 GHashTableIter hash_iter;
4320 const gchar *object_path;
4326 CONNECTION_ENSURE_LOCK (connection);
4328 path_len = strlen (path);
4332 set = g_hash_table_new (g_str_hash, g_str_equal);
4334 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4335 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4336 maybe_add_path (path, path_len, object_path, set);
4338 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4339 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4340 maybe_add_path (path, path_len, object_path, set);
4342 p = g_ptr_array_new ();
4343 keys = g_hash_table_get_keys (set);
4344 for (l = keys; l != NULL; l = l->next)
4345 g_ptr_array_add (p, l->data);
4346 g_hash_table_unref (set);
4349 g_ptr_array_add (p, NULL);
4350 ret = (gchar **) g_ptr_array_free (p, FALSE);
4355 g_dbus_connection_list_registered (GDBusConnection *connection,
4359 CONNECTION_LOCK (connection);
4360 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4361 CONNECTION_UNLOCK (connection);
4365 /* called in message handler thread with lock held */
4367 handle_introspect (GDBusConnection *connection,
4369 GDBusMessage *message)
4373 GDBusMessage *reply;
4374 GHashTableIter hash_iter;
4375 ExportedInterface *ei;
4378 /* first the header with the standard interfaces */
4379 s = g_string_sized_new (sizeof (introspect_header) +
4380 sizeof (introspect_properties_interface) +
4381 sizeof (introspect_introspectable_interface) +
4382 sizeof (introspect_tail));
4383 introspect_append_header (s);
4384 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4385 "org.freedesktop.DBus.Properties"))
4386 g_string_append (s, introspect_properties_interface);
4388 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4389 "org.freedesktop.DBus.Introspectable"))
4390 g_string_append (s, introspect_introspectable_interface);
4392 /* then include the registered interfaces */
4393 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4394 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4395 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4397 /* finally include nodes registered below us */
4398 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4399 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4400 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4401 g_strfreev (registered);
4402 g_string_append (s, introspect_tail);
4404 reply = g_dbus_message_new_method_reply (message);
4405 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4406 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4407 g_object_unref (reply);
4408 g_string_free (s, TRUE);
4413 /* called in thread where object was registered - no locks held */
4415 call_in_idle_cb (gpointer user_data)
4417 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4418 GDBusInterfaceVTable *vtable;
4419 guint registration_id;
4420 guint subtree_registration_id;
4422 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4423 g_assert (vtable != NULL && vtable->method_call != NULL);
4425 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4426 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4428 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4430 subtree_registration_id))
4432 GDBusMessage *reply;
4433 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4434 "org.freedesktop.DBus.Error.UnknownMethod",
4435 _("No such interface `%s' on object at path %s"),
4436 g_dbus_method_invocation_get_interface_name (invocation),
4437 g_dbus_method_invocation_get_object_path (invocation));
4438 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4439 g_object_unref (reply);
4443 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4444 g_dbus_method_invocation_get_sender (invocation),
4445 g_dbus_method_invocation_get_object_path (invocation),
4446 g_dbus_method_invocation_get_interface_name (invocation),
4447 g_dbus_method_invocation_get_method_name (invocation),
4448 g_dbus_method_invocation_get_parameters (invocation),
4449 g_object_ref (invocation),
4450 g_dbus_method_invocation_get_user_data (invocation));
4456 /* called in message handler thread with lock held */
4458 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4459 GDBusMessage *message,
4460 guint registration_id,
4461 guint subtree_registration_id,
4462 GDBusInterfaceInfo *interface_info,
4463 const GDBusInterfaceVTable *vtable,
4464 GMainContext *main_context,
4467 GDBusMethodInvocation *invocation;
4468 const GDBusMethodInfo *method_info;
4469 GDBusMessage *reply;
4470 GVariant *parameters;
4471 GSource *idle_source;
4473 GVariantType *in_type;
4477 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4478 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4480 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4481 * error to the caller
4483 if (method_info == NULL)
4485 reply = g_dbus_message_new_method_error (message,
4486 "org.freedesktop.DBus.Error.UnknownMethod",
4487 _("No such method `%s'"),
4488 g_dbus_message_get_member (message));
4489 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4490 g_object_unref (reply);
4495 parameters = g_dbus_message_get_body (message);
4496 if (parameters == NULL)
4498 parameters = g_variant_new ("()");
4499 g_variant_ref_sink (parameters);
4503 g_variant_ref (parameters);
4506 /* Check that the incoming args are of the right type - if they are not, return
4507 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4509 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4510 if (!g_variant_is_of_type (parameters, in_type))
4514 type_string = g_variant_type_dup_string (in_type);
4516 reply = g_dbus_message_new_method_error (message,
4517 "org.freedesktop.DBus.Error.InvalidArgs",
4518 _("Type of message, `%s', does not match expected type `%s'"),
4519 g_variant_get_type_string (parameters),
4521 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4522 g_variant_type_free (in_type);
4523 g_variant_unref (parameters);
4524 g_object_unref (reply);
4525 g_free (type_string);
4529 g_variant_type_free (in_type);
4531 /* schedule the call in idle */
4532 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4533 g_dbus_message_get_path (message),
4534 g_dbus_message_get_interface (message),
4535 g_dbus_message_get_member (message),
4541 g_variant_unref (parameters);
4543 /* TODO: would be nicer with a real MethodData like we already
4544 * have PropertyData and PropertyGetAllData... */
4545 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4546 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4547 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4549 idle_source = g_idle_source_new ();
4550 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4551 g_source_set_callback (idle_source,
4555 g_source_attach (idle_source, main_context);
4556 g_source_unref (idle_source);
4564 /* ---------------------------------------------------------------------------------------------------- */
4566 /* called in message handler thread with lock held */
4568 obj_message_func (GDBusConnection *connection,
4570 GDBusMessage *message)
4572 const gchar *interface_name;
4573 const gchar *member;
4574 const gchar *signature;
4579 interface_name = g_dbus_message_get_interface (message);
4580 member = g_dbus_message_get_member (message);
4581 signature = g_dbus_message_get_signature (message);
4583 /* see if we have an interface for handling this call */
4584 if (interface_name != NULL)
4586 ExportedInterface *ei;
4587 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4590 /* we do - invoke the handler in idle in the right thread */
4592 /* handle no vtable or handler being present */
4593 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4596 handled = validate_and_maybe_schedule_method_call (connection,
4608 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4609 g_strcmp0 (member, "Introspect") == 0 &&
4610 g_strcmp0 (signature, "") == 0)
4612 handled = handle_introspect (connection, eo, message);
4615 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4616 g_strcmp0 (member, "Get") == 0 &&
4617 g_strcmp0 (signature, "ss") == 0)
4619 handled = handle_getset_property (connection, eo, message, TRUE);
4622 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4623 g_strcmp0 (member, "Set") == 0 &&
4624 g_strcmp0 (signature, "ssv") == 0)
4626 handled = handle_getset_property (connection, eo, message, FALSE);
4629 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4630 g_strcmp0 (member, "GetAll") == 0 &&
4631 g_strcmp0 (signature, "s") == 0)
4633 handled = handle_get_all_properties (connection, eo, message);
4642 * g_dbus_connection_register_object:
4643 * @connection: A #GDBusConnection.
4644 * @object_path: The object path to register at.
4645 * @interface_info: Introspection data for the interface.
4646 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4647 * @user_data: Data to pass to functions in @vtable.
4648 * @user_data_free_func: Function to call when the object path is unregistered.
4649 * @error: Return location for error or %NULL.
4651 * Registers callbacks for exported objects at @object_path with the
4652 * D-Bus interface that is described in @interface_info.
4654 * Calls to functions in @vtable (and @user_data_free_func) will
4655 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4656 * loop</link> of the thread you are calling this method from.
4658 * Note that all #GVariant values passed to functions in @vtable will match
4659 * the signature given in @interface_info - if a remote caller passes
4660 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4661 * is returned to the remote caller.
4663 * Additionally, if the remote caller attempts to invoke methods or
4664 * access properties not mentioned in @interface_info the
4665 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4666 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4667 * are returned to the caller.
4669 * It is considered a programming error if the
4670 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4671 * #GVariant of incorrect type.
4673 * If an existing callback is already registered at @object_path and
4674 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4676 * GDBus automatically implements the standard D-Bus interfaces
4677 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4678 * and org.freedesktop.Peer, so you don't have to implement those for
4679 * the objects you export. You <emphasis>can</emphasis> implement
4680 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4681 * and setting of properties asynchronously.
4683 * Note that the reference count on @interface_info will be
4684 * incremented by 1 (unless allocated statically, e.g. if the
4685 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4686 * as the object is exported. Also note that @vtable will be copied.
4688 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4690 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4691 * that can be used with g_dbus_connection_unregister_object() .
4696 g_dbus_connection_register_object (GDBusConnection *connection,
4697 const gchar *object_path,
4698 GDBusInterfaceInfo *interface_info,
4699 const GDBusInterfaceVTable *vtable,
4701 GDestroyNotify user_data_free_func,
4705 ExportedInterface *ei;
4708 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4709 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4710 g_return_val_if_fail (interface_info != NULL, 0);
4711 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4712 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4716 CONNECTION_LOCK (connection);
4718 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4721 eo = g_new0 (ExportedObject, 1);
4722 eo->object_path = g_strdup (object_path);
4723 eo->connection = connection;
4724 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4727 (GDestroyNotify) exported_interface_free);
4728 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4731 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4737 _("An object is already exported for the interface %s at %s"),
4738 interface_info->name,
4743 ei = g_new0 (ExportedInterface, 1);
4744 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4746 ei->user_data = user_data;
4747 ei->user_data_free_func = user_data_free_func;
4748 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4749 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4750 g_dbus_interface_info_cache_build (ei->interface_info);
4751 ei->interface_name = g_strdup (interface_info->name);
4752 ei->context = g_main_context_get_thread_default ();
4753 if (ei->context != NULL)
4754 g_main_context_ref (ei->context);
4756 g_hash_table_insert (eo->map_if_name_to_ei,
4757 (gpointer) ei->interface_name,
4759 g_hash_table_insert (connection->map_id_to_ei,
4760 GUINT_TO_POINTER (ei->id),
4766 CONNECTION_UNLOCK (connection);
4772 * g_dbus_connection_unregister_object:
4773 * @connection: A #GDBusConnection.
4774 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4776 * Unregisters an object.
4778 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4783 g_dbus_connection_unregister_object (GDBusConnection *connection,
4784 guint registration_id)
4786 ExportedInterface *ei;
4790 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4794 CONNECTION_LOCK (connection);
4796 ei = g_hash_table_lookup (connection->map_id_to_ei,
4797 GUINT_TO_POINTER (registration_id));
4803 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
4804 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
4805 /* unregister object path if we have no more exported interfaces */
4806 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
4807 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
4813 CONNECTION_UNLOCK (connection);
4818 /* ---------------------------------------------------------------------------------------------------- */
4821 * g_dbus_connection_emit_signal:
4822 * @connection: A #GDBusConnection.
4823 * @destination_bus_name: (allow-none): The unique bus name for the destination
4824 * for the signal or %NULL to emit to all listeners.
4825 * @object_path: Path of remote object.
4826 * @interface_name: D-Bus interface to emit a signal on.
4827 * @signal_name: The name of the signal to emit.
4828 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
4829 * or %NULL if not passing parameters.
4830 * @error: Return location for error or %NULL.
4834 * If the parameters GVariant is floating, it is consumed.
4836 * This can only fail if @parameters is not compatible with the D-Bus protocol.
4838 * Returns: %TRUE unless @error is set.
4843 g_dbus_connection_emit_signal (GDBusConnection *connection,
4844 const gchar *destination_bus_name,
4845 const gchar *object_path,
4846 const gchar *interface_name,
4847 const gchar *signal_name,
4848 GVariant *parameters,
4851 GDBusMessage *message;
4857 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4858 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
4859 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
4860 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
4861 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
4862 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
4864 if (G_UNLIKELY (_g_dbus_debug_emission ()))
4866 _g_dbus_debug_print_lock ();
4867 g_print ("========================================================================\n"
4868 "GDBus-debug:Emission:\n"
4869 " >>>> SIGNAL EMISSION %s.%s()\n"
4871 " destination %s\n",
4872 interface_name, signal_name,
4874 destination_bus_name != NULL ? destination_bus_name : "(none)");
4875 _g_dbus_debug_print_unlock ();
4878 message = g_dbus_message_new_signal (object_path,
4882 if (destination_bus_name != NULL)
4883 g_dbus_message_set_header (message,
4884 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
4885 g_variant_new_string (destination_bus_name));
4887 if (parameters != NULL)
4888 g_dbus_message_set_body (message, parameters);
4890 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
4891 g_object_unref (message);
4897 add_call_flags (GDBusMessage *message,
4898 GDBusCallFlags flags)
4900 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
4901 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
4905 decode_method_reply (GDBusMessage *reply,
4906 const gchar *method_name,
4907 const GVariantType *reply_type,
4913 switch (g_dbus_message_get_message_type (reply))
4915 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
4916 result = g_dbus_message_get_body (reply);
4919 result = g_variant_new ("()");
4920 g_variant_ref_sink (result);
4924 g_variant_ref (result);
4927 if (!g_variant_is_of_type (result, reply_type))
4929 gchar *type_string = g_variant_type_dup_string (reply_type);
4933 G_IO_ERROR_INVALID_ARGUMENT,
4934 _("Method `%s' returned type `%s', but expected `%s'"),
4935 method_name, g_variant_get_type_string (result), type_string);
4937 g_variant_unref (result);
4938 g_free (type_string);
4943 case G_DBUS_MESSAGE_TYPE_ERROR:
4944 g_dbus_message_to_gerror (reply, error);
4948 g_assert_not_reached ();
4958 GSimpleAsyncResult *simple;
4959 GVariantType *reply_type;
4960 gchar *method_name; /* for error message */
4965 g_dbus_connection_call_done (GObject *source,
4966 GAsyncResult *result,
4969 GDBusConnection *connection = G_DBUS_CONNECTION (source);
4970 CallState *state = user_data;
4972 GDBusMessage *reply;
4976 reply = g_dbus_connection_send_message_with_reply_finish (connection,
4980 if (G_UNLIKELY (_g_dbus_debug_call ()))
4982 _g_dbus_debug_print_lock ();
4983 g_print ("========================================================================\n"
4984 "GDBus-debug:Call:\n"
4985 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
4991 g_print ("SUCCESS\n");
4995 g_print ("FAILED: %s\n",
4998 _g_dbus_debug_print_unlock ();
5004 value = decode_method_reply (reply, state->method_name,
5005 state->reply_type, &error);
5006 g_object_unref (reply);
5012 g_simple_async_result_take_error (state->simple, error);
5014 g_simple_async_result_set_op_res_gpointer (state->simple, value,
5015 (GDestroyNotify) g_variant_unref);
5017 g_simple_async_result_complete (state->simple);
5018 g_variant_type_free (state->reply_type);
5019 g_object_unref (state->simple);
5020 g_free (state->method_name);
5022 g_slice_free (CallState, state);
5026 * g_dbus_connection_call:
5027 * @connection: A #GDBusConnection.
5028 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5029 * @connection is not a message bus connection.
5030 * @object_path: Path of remote object.
5031 * @interface_name: D-Bus interface to invoke method on.
5032 * @method_name: The name of the method to invoke.
5033 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5034 * or %NULL if not passing parameters.
5035 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5036 * @flags: Flags from the #GDBusCallFlags enumeration.
5037 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5038 * timeout or %G_MAXINT for no timeout.
5039 * @cancellable: A #GCancellable or %NULL.
5040 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5041 * satisfied or %NULL if you don't * care about the result of the
5042 * method invocation.
5043 * @user_data: The data to pass to @callback.
5045 * Asynchronously invokes the @method_name method on the
5046 * @interface_name D-Bus interface on the remote object at
5047 * @object_path owned by @bus_name.
5049 * If @connection is closed then the operation will fail with
5050 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5051 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5052 * not compatible with the D-Bus protocol, the operation fails with
5053 * %G_IO_ERROR_INVALID_ARGUMENT.
5055 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5056 * error will be raised if it does not match. Said another way, if you give a @reply_type
5057 * then any non-%NULL return value will be of this type.
5059 * If the @parameters #GVariant is floating, it is consumed. This allows
5060 * convenient 'inline' use of g_variant_new(), e.g.:
5062 * g_dbus_connection_call (connection,
5063 * "org.freedesktop.StringThings",
5064 * "/org/freedesktop/StringThings",
5065 * "org.freedesktop.StringThings",
5067 * g_variant_new ("(ss)",
5071 * G_DBUS_CALL_FLAGS_NONE,
5074 * (GAsyncReadyCallback) two_strings_done,
5078 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5079 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5080 * of the thread you are calling this method from. You can then call
5081 * g_dbus_connection_call_finish() to get the result of the operation.
5082 * See g_dbus_connection_call_sync() for the synchronous version of this
5088 g_dbus_connection_call (GDBusConnection *connection,
5089 const gchar *bus_name,
5090 const gchar *object_path,
5091 const gchar *interface_name,
5092 const gchar *method_name,
5093 GVariant *parameters,
5094 const GVariantType *reply_type,
5095 GDBusCallFlags flags,
5097 GCancellable *cancellable,
5098 GAsyncReadyCallback callback,
5101 GDBusMessage *message;
5104 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5105 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5106 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5107 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5108 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5109 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5110 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5112 state = g_slice_new (CallState);
5113 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5114 callback, user_data,
5115 g_dbus_connection_call);
5116 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5118 if (reply_type == NULL)
5119 reply_type = G_VARIANT_TYPE_ANY;
5121 state->reply_type = g_variant_type_copy (reply_type);
5123 message = g_dbus_message_new_method_call (bus_name,
5127 add_call_flags (message, flags);
5128 if (parameters != NULL)
5129 g_dbus_message_set_body (message, parameters);
5131 g_dbus_connection_send_message_with_reply (connection,
5133 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5137 g_dbus_connection_call_done,
5140 if (G_UNLIKELY (_g_dbus_debug_call ()))
5142 _g_dbus_debug_print_lock ();
5143 g_print ("========================================================================\n"
5144 "GDBus-debug:Call:\n"
5145 " >>>> ASYNC %s.%s()\n"
5147 " owned by name %s (serial %d)\n",
5151 bus_name != NULL ? bus_name : "(none)",
5153 _g_dbus_debug_print_unlock ();
5156 if (message != NULL)
5157 g_object_unref (message);
5161 * g_dbus_connection_call_finish:
5162 * @connection: A #GDBusConnection.
5163 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5164 * @error: Return location for error or %NULL.
5166 * Finishes an operation started with g_dbus_connection_call().
5168 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5169 * return values. Free with g_variant_unref().
5174 g_dbus_connection_call_finish (GDBusConnection *connection,
5178 GSimpleAsyncResult *simple;
5180 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5181 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5182 g_dbus_connection_call), NULL);
5183 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5185 simple = G_SIMPLE_ASYNC_RESULT (res);
5187 if (g_simple_async_result_propagate_error (simple, error))
5190 return g_variant_ref (g_simple_async_result_get_op_res_gpointer (simple));
5193 /* ---------------------------------------------------------------------------------------------------- */
5196 * g_dbus_connection_call_sync:
5197 * @connection: A #GDBusConnection.
5198 * @bus_name: A unique or well-known bus name.
5199 * @object_path: Path of remote object.
5200 * @interface_name: D-Bus interface to invoke method on.
5201 * @method_name: The name of the method to invoke.
5202 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5203 * or %NULL if not passing parameters.
5204 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5205 * @flags: Flags from the #GDBusCallFlags enumeration.
5206 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5207 * timeout or %G_MAXINT for no timeout.
5208 * @cancellable: A #GCancellable or %NULL.
5209 * @error: Return location for error or %NULL.
5211 * Synchronously invokes the @method_name method on the
5212 * @interface_name D-Bus interface on the remote object at
5213 * @object_path owned by @bus_name.
5215 * If @connection is closed then the operation will fail with
5216 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5217 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5218 * contains a value not compatible with the D-Bus protocol, the operation
5219 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5221 * If @reply_type is non-%NULL then the reply will be checked for having
5222 * this type and an error will be raised if it does not match. Said
5223 * another way, if you give a @reply_type then any non-%NULL return
5224 * value will be of this type.
5226 * If the @parameters #GVariant is floating, it is consumed.
5227 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5229 * g_dbus_connection_call_sync (connection,
5230 * "org.freedesktop.StringThings",
5231 * "/org/freedesktop/StringThings",
5232 * "org.freedesktop.StringThings",
5234 * g_variant_new ("(ss)",
5238 * G_DBUS_CALL_FLAGS_NONE,
5244 * The calling thread is blocked until a reply is received. See
5245 * g_dbus_connection_call() for the asynchronous version of
5248 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5249 * return values. Free with g_variant_unref().
5254 g_dbus_connection_call_sync (GDBusConnection *connection,
5255 const gchar *bus_name,
5256 const gchar *object_path,
5257 const gchar *interface_name,
5258 const gchar *method_name,
5259 GVariant *parameters,
5260 const GVariantType *reply_type,
5261 GDBusCallFlags flags,
5263 GCancellable *cancellable,
5266 GDBusMessage *message;
5267 GDBusMessage *reply;
5269 GError *local_error;
5275 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5276 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5277 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5278 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5279 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5280 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5281 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5283 if (reply_type == NULL)
5284 reply_type = G_VARIANT_TYPE_ANY;
5286 message = g_dbus_message_new_method_call (bus_name,
5290 add_call_flags (message, flags);
5291 if (parameters != NULL)
5292 g_dbus_message_set_body (message, parameters);
5294 if (G_UNLIKELY (_g_dbus_debug_call ()))
5296 _g_dbus_debug_print_lock ();
5297 g_print ("========================================================================\n"
5298 "GDBus-debug:Call:\n"
5299 " >>>> SYNC %s.%s()\n"
5301 " owned by name %s\n",
5305 bus_name != NULL ? bus_name : "(none)");
5306 _g_dbus_debug_print_unlock ();
5310 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5312 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5314 NULL, /* volatile guint32 *out_serial */
5318 if (G_UNLIKELY (_g_dbus_debug_call ()))
5320 _g_dbus_debug_print_lock ();
5321 g_print ("========================================================================\n"
5322 "GDBus-debug:Call:\n"
5323 " <<<< SYNC COMPLETE %s.%s()\n"
5329 g_print ("SUCCESS\n");
5333 g_print ("FAILED: %s\n",
5334 local_error->message);
5336 _g_dbus_debug_print_unlock ();
5342 *error = local_error;
5344 g_error_free (local_error);
5348 result = decode_method_reply (reply, method_name, reply_type, error);
5351 if (message != NULL)
5352 g_object_unref (message);
5354 g_object_unref (reply);
5359 /* ---------------------------------------------------------------------------------------------------- */
5361 struct ExportedSubtree
5365 GDBusConnection *connection;
5366 GDBusSubtreeVTable *vtable;
5367 GDBusSubtreeFlags flags;
5369 GMainContext *context;
5371 GDestroyNotify user_data_free_func;
5375 exported_subtree_free (ExportedSubtree *es)
5377 call_destroy_notify (es->context,
5378 es->user_data_free_func,
5381 if (es->context != NULL)
5382 g_main_context_unref (es->context);
5384 _g_dbus_subtree_vtable_free (es->vtable);
5385 g_free (es->object_path);
5389 /* called without lock held */
5391 handle_subtree_introspect (GDBusConnection *connection,
5392 ExportedSubtree *es,
5393 GDBusMessage *message)
5397 GDBusMessage *reply;
5400 const gchar *sender;
5401 const gchar *requested_object_path;
5402 const gchar *requested_node;
5403 GDBusInterfaceInfo **interfaces;
5405 gchar **subnode_paths;
5406 gboolean has_properties_interface;
5407 gboolean has_introspectable_interface;
5411 requested_object_path = g_dbus_message_get_path (message);
5412 sender = g_dbus_message_get_sender (message);
5413 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5415 s = g_string_new (NULL);
5416 introspect_append_header (s);
5418 /* Strictly we don't need the children in dynamic mode, but we avoid the
5419 * conditionals to preserve code clarity
5421 children = es->vtable->enumerate (es->connection,
5428 requested_node = strrchr (requested_object_path, '/') + 1;
5430 /* Assert existence of object if we are not dynamic */
5431 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5432 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5437 requested_node = NULL;
5440 interfaces = es->vtable->introspect (es->connection,
5445 if (interfaces != NULL)
5447 has_properties_interface = FALSE;
5448 has_introspectable_interface = FALSE;
5450 for (n = 0; interfaces[n] != NULL; n++)
5452 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5453 has_properties_interface = TRUE;
5454 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5455 has_introspectable_interface = TRUE;
5457 if (!has_properties_interface)
5458 g_string_append (s, introspect_properties_interface);
5459 if (!has_introspectable_interface)
5460 g_string_append (s, introspect_introspectable_interface);
5462 for (n = 0; interfaces[n] != NULL; n++)
5464 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5465 g_dbus_interface_info_unref (interfaces[n]);
5467 g_free (interfaces);
5470 /* then include <node> entries from the Subtree for the root */
5473 for (n = 0; children != NULL && children[n] != NULL; n++)
5474 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5477 /* finally include nodes registered below us */
5478 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5479 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5480 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5481 g_strfreev (subnode_paths);
5483 g_string_append (s, "</node>\n");
5485 reply = g_dbus_message_new_method_reply (message);
5486 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5487 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5488 g_object_unref (reply);
5493 g_string_free (s, TRUE);
5494 g_strfreev (children);
5498 /* called without lock held */
5500 handle_subtree_method_invocation (GDBusConnection *connection,
5501 ExportedSubtree *es,
5502 GDBusMessage *message)
5505 const gchar *sender;
5506 const gchar *interface_name;
5507 const gchar *member;
5508 const gchar *signature;
5509 const gchar *requested_object_path;
5510 const gchar *requested_node;
5512 GDBusInterfaceInfo *interface_info;
5513 const GDBusInterfaceVTable *interface_vtable;
5514 gpointer interface_user_data;
5516 GDBusInterfaceInfo **interfaces;
5517 gboolean is_property_get;
5518 gboolean is_property_set;
5519 gboolean is_property_get_all;
5524 requested_object_path = g_dbus_message_get_path (message);
5525 sender = g_dbus_message_get_sender (message);
5526 interface_name = g_dbus_message_get_interface (message);
5527 member = g_dbus_message_get_member (message);
5528 signature = g_dbus_message_get_signature (message);
5529 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5531 is_property_get = FALSE;
5532 is_property_set = FALSE;
5533 is_property_get_all = FALSE;
5534 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5536 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5537 is_property_get = TRUE;
5538 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5539 is_property_set = TRUE;
5540 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5541 is_property_get_all = TRUE;
5546 requested_node = strrchr (requested_object_path, '/') + 1;
5548 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5550 /* We don't want to dispatch to unenumerated
5551 * nodes, so ensure that the child exists.
5556 children = es->vtable->enumerate (es->connection,
5561 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
5562 g_strfreev (children);
5570 requested_node = NULL;
5573 /* get introspection data for the node */
5574 interfaces = es->vtable->introspect (es->connection,
5576 requested_object_path,
5580 if (interfaces == NULL)
5583 interface_info = NULL;
5584 for (n = 0; interfaces[n] != NULL; n++)
5586 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5587 interface_info = interfaces[n];
5590 /* dispatch the call if the user wants to handle it */
5591 if (interface_info != NULL)
5593 /* figure out where to dispatch the method call */
5594 interface_user_data = NULL;
5595 interface_vtable = es->vtable->dispatch (es->connection,
5600 &interface_user_data,
5602 if (interface_vtable == NULL)
5605 CONNECTION_LOCK (connection);
5606 handled = validate_and_maybe_schedule_method_call (es->connection,
5613 interface_user_data);
5614 CONNECTION_UNLOCK (connection);
5616 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
5617 else if (is_property_get || is_property_set || is_property_get_all)
5619 if (is_property_get)
5620 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
5621 else if (is_property_set)
5622 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
5623 else if (is_property_get_all)
5624 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
5626 g_assert_not_reached ();
5628 /* see if the object supports this interface at all */
5629 for (n = 0; interfaces[n] != NULL; n++)
5631 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
5632 interface_info = interfaces[n];
5635 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
5636 * claims it won't support the interface
5638 if (interface_info == NULL)
5640 GDBusMessage *reply;
5641 reply = g_dbus_message_new_method_error (message,
5642 "org.freedesktop.DBus.Error.InvalidArgs",
5643 _("No such interface `%s'"),
5645 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5646 g_object_unref (reply);
5651 /* figure out where to dispatch the property get/set/getall calls */
5652 interface_user_data = NULL;
5653 interface_vtable = es->vtable->dispatch (es->connection,
5658 &interface_user_data,
5660 if (interface_vtable == NULL)
5662 g_warning ("The subtree introspection function indicates that '%s' "
5663 "is a valid interface name, but calling the dispatch "
5664 "function on that interface gave us NULL", interface_name);
5668 if (is_property_get || is_property_set)
5670 CONNECTION_LOCK (connection);
5671 handled = validate_and_maybe_schedule_property_getset (es->connection,
5679 interface_user_data);
5680 CONNECTION_UNLOCK (connection);
5682 else if (is_property_get_all)
5684 CONNECTION_LOCK (connection);
5685 handled = validate_and_maybe_schedule_property_get_all (es->connection,
5692 interface_user_data);
5693 CONNECTION_UNLOCK (connection);
5698 if (interfaces != NULL)
5700 for (n = 0; interfaces[n] != NULL; n++)
5701 g_dbus_interface_info_unref (interfaces[n]);
5702 g_free (interfaces);
5710 GDBusMessage *message;
5711 ExportedSubtree *es;
5712 } SubtreeDeferredData;
5715 subtree_deferred_data_free (SubtreeDeferredData *data)
5717 g_object_unref (data->message);
5721 /* called without lock held in the thread where the caller registered the subtree */
5723 process_subtree_vtable_message_in_idle_cb (gpointer _data)
5725 SubtreeDeferredData *data = _data;
5730 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
5731 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
5732 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
5733 handled = handle_subtree_introspect (data->es->connection,
5737 handled = handle_subtree_method_invocation (data->es->connection,
5743 CONNECTION_LOCK (data->es->connection);
5744 handled = handle_generic_unlocked (data->es->connection, data->message);
5745 CONNECTION_UNLOCK (data->es->connection);
5748 /* if we couldn't handle the request, just bail with the UnknownMethod error */
5751 GDBusMessage *reply;
5752 reply = g_dbus_message_new_method_error (data->message,
5753 "org.freedesktop.DBus.Error.UnknownMethod",
5754 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
5755 g_dbus_message_get_member (data->message),
5756 g_dbus_message_get_interface (data->message),
5757 g_dbus_message_get_signature (data->message));
5758 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5759 g_object_unref (reply);
5765 /* called in message handler thread with lock held */
5767 subtree_message_func (GDBusConnection *connection,
5768 ExportedSubtree *es,
5769 GDBusMessage *message)
5771 GSource *idle_source;
5772 SubtreeDeferredData *data;
5774 data = g_new0 (SubtreeDeferredData, 1);
5775 data->message = g_object_ref (message);
5778 /* defer this call to an idle handler in the right thread */
5779 idle_source = g_idle_source_new ();
5780 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
5781 g_source_set_callback (idle_source,
5782 process_subtree_vtable_message_in_idle_cb,
5784 (GDestroyNotify) subtree_deferred_data_free);
5785 g_source_attach (idle_source, es->context);
5786 g_source_unref (idle_source);
5788 /* since we own the entire subtree, handlers for objects not in the subtree have been
5789 * tried already by libdbus-1 - so we just need to ensure that we're always going
5790 * to reply to the message
5796 * g_dbus_connection_register_subtree:
5797 * @connection: A #GDBusConnection.
5798 * @object_path: The object path to register the subtree at.
5799 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
5800 * @flags: Flags used to fine tune the behavior of the subtree.
5801 * @user_data: Data to pass to functions in @vtable.
5802 * @user_data_free_func: Function to call when the subtree is unregistered.
5803 * @error: Return location for error or %NULL.
5805 * Registers a whole subtree of <quote>dynamic</quote> objects.
5807 * The @enumerate and @introspection functions in @vtable are used to
5808 * convey, to remote callers, what nodes exist in the subtree rooted
5811 * When handling remote calls into any node in the subtree, first the
5812 * @enumerate function is used to check if the node exists. If the node exists
5813 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
5814 * the @introspection function is used to check if the node supports the
5815 * requested method. If so, the @dispatch function is used to determine
5816 * where to dispatch the call. The collected #GDBusInterfaceVTable and
5817 * #gpointer will be used to call into the interface vtable for processing
5820 * All calls into user-provided code will be invoked in the <link
5821 * linkend="g-main-context-push-thread-default">thread-default main
5822 * loop</link> of the thread you are calling this method from.
5824 * If an existing subtree is already registered at @object_path or
5825 * then @error is set to #G_IO_ERROR_EXISTS.
5827 * Note that it is valid to register regular objects (using
5828 * g_dbus_connection_register_object()) in a subtree registered with
5829 * g_dbus_connection_register_subtree() - if so, the subtree handler
5830 * is tried as the last resort. One way to think about a subtree
5831 * handler is to consider it a <quote>fallback handler</quote>
5832 * for object paths not registered via g_dbus_connection_register_object()
5833 * or other bindings.
5835 * Note that @vtable will be copied so you cannot change it after
5838 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
5840 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
5841 * that can be used with g_dbus_connection_unregister_subtree() .
5846 g_dbus_connection_register_subtree (GDBusConnection *connection,
5847 const gchar *object_path,
5848 const GDBusSubtreeVTable *vtable,
5849 GDBusSubtreeFlags flags,
5851 GDestroyNotify user_data_free_func,
5855 ExportedSubtree *es;
5857 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5858 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5859 g_return_val_if_fail (vtable != NULL, 0);
5860 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5864 CONNECTION_LOCK (connection);
5866 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
5872 _("A subtree is already exported for %s"),
5877 es = g_new0 (ExportedSubtree, 1);
5878 es->object_path = g_strdup (object_path);
5879 es->connection = connection;
5881 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
5883 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
5884 es->user_data = user_data;
5885 es->user_data_free_func = user_data_free_func;
5886 es->context = g_main_context_get_thread_default ();
5887 if (es->context != NULL)
5888 g_main_context_ref (es->context);
5890 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
5891 g_hash_table_insert (connection->map_id_to_es,
5892 GUINT_TO_POINTER (es->id),
5898 CONNECTION_UNLOCK (connection);
5903 /* ---------------------------------------------------------------------------------------------------- */
5906 * g_dbus_connection_unregister_subtree:
5907 * @connection: A #GDBusConnection.
5908 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
5910 * Unregisters a subtree.
5912 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
5917 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
5918 guint registration_id)
5920 ExportedSubtree *es;
5923 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5927 CONNECTION_LOCK (connection);
5929 es = g_hash_table_lookup (connection->map_id_to_es,
5930 GUINT_TO_POINTER (registration_id));
5934 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
5935 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
5940 CONNECTION_UNLOCK (connection);
5945 /* ---------------------------------------------------------------------------------------------------- */
5947 /* must be called with lock held */
5949 handle_generic_ping_unlocked (GDBusConnection *connection,
5950 const gchar *object_path,
5951 GDBusMessage *message)
5953 GDBusMessage *reply;
5954 reply = g_dbus_message_new_method_reply (message);
5955 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5956 g_object_unref (reply);
5959 /* must be called with lock held */
5961 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
5962 const gchar *object_path,
5963 GDBusMessage *message)
5965 GDBusMessage *reply;
5968 if (connection->machine_id == NULL)
5973 connection->machine_id = _g_dbus_get_machine_id (&error);
5974 if (connection->machine_id == NULL)
5976 reply = g_dbus_message_new_method_error_literal (message,
5977 "org.freedesktop.DBus.Error.Failed",
5979 g_error_free (error);
5985 reply = g_dbus_message_new_method_reply (message);
5986 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
5988 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5989 g_object_unref (reply);
5992 /* must be called with lock held */
5994 handle_generic_introspect_unlocked (GDBusConnection *connection,
5995 const gchar *object_path,
5996 GDBusMessage *message)
6001 GDBusMessage *reply;
6003 /* first the header */
6004 s = g_string_new (NULL);
6005 introspect_append_header (s);
6007 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6008 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6009 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6010 g_strfreev (registered);
6011 g_string_append (s, "</node>\n");
6013 reply = g_dbus_message_new_method_reply (message);
6014 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6015 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6016 g_object_unref (reply);
6017 g_string_free (s, TRUE);
6020 /* must be called with lock held */
6022 handle_generic_unlocked (GDBusConnection *connection,
6023 GDBusMessage *message)
6026 const gchar *interface_name;
6027 const gchar *member;
6028 const gchar *signature;
6031 CONNECTION_ENSURE_LOCK (connection);
6035 interface_name = g_dbus_message_get_interface (message);
6036 member = g_dbus_message_get_member (message);
6037 signature = g_dbus_message_get_signature (message);
6038 path = g_dbus_message_get_path (message);
6040 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6041 g_strcmp0 (member, "Introspect") == 0 &&
6042 g_strcmp0 (signature, "") == 0)
6044 handle_generic_introspect_unlocked (connection, path, message);
6047 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6048 g_strcmp0 (member, "Ping") == 0 &&
6049 g_strcmp0 (signature, "") == 0)
6051 handle_generic_ping_unlocked (connection, path, message);
6054 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6055 g_strcmp0 (member, "GetMachineId") == 0 &&
6056 g_strcmp0 (signature, "") == 0)
6058 handle_generic_get_machine_id_unlocked (connection, path, message);
6065 /* ---------------------------------------------------------------------------------------------------- */
6067 /* called in message handler thread with lock held */
6069 distribute_method_call (GDBusConnection *connection,
6070 GDBusMessage *message)
6072 GDBusMessage *reply;
6074 ExportedSubtree *es;
6075 const gchar *object_path;
6076 const gchar *interface_name;
6077 const gchar *member;
6079 gchar *subtree_path;
6082 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6084 interface_name = g_dbus_message_get_interface (message);
6085 member = g_dbus_message_get_member (message);
6086 path = g_dbus_message_get_path (message);
6087 subtree_path = g_strdup (path);
6088 needle = strrchr (subtree_path, '/');
6089 if (needle != NULL && needle != subtree_path)
6095 g_free (subtree_path);
6096 subtree_path = NULL;
6100 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6102 _g_dbus_debug_print_lock ();
6103 g_print ("========================================================================\n"
6104 "GDBus-debug:Incoming:\n"
6105 " <<<< METHOD INVOCATION %s.%s()\n"
6107 " invoked by name %s\n"
6109 interface_name, member,
6111 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6112 g_dbus_message_get_serial (message));
6113 _g_dbus_debug_print_unlock ();
6116 object_path = g_dbus_message_get_path (message);
6117 g_assert (object_path != NULL);
6119 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6122 if (obj_message_func (connection, eo, message))
6126 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6129 if (subtree_message_func (connection, es, message))
6133 if (subtree_path != NULL)
6135 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6138 if (subtree_message_func (connection, es, message))
6143 if (handle_generic_unlocked (connection, message))
6146 /* if we end up here, the message has not been not handled - so return an error saying this */
6147 reply = g_dbus_message_new_method_error (message,
6148 "org.freedesktop.DBus.Error.UnknownMethod",
6149 _("No such interface `%s' on object at path %s"),
6152 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6153 g_object_unref (reply);
6156 g_free (subtree_path);
6159 /* ---------------------------------------------------------------------------------------------------- */
6161 static GDBusConnection **
6162 message_bus_get_singleton (GBusType bus_type,
6165 GDBusConnection **ret;
6166 const gchar *starter_bus;
6172 case G_BUS_TYPE_SESSION:
6173 ret = &the_session_bus;
6176 case G_BUS_TYPE_SYSTEM:
6177 ret = &the_system_bus;
6180 case G_BUS_TYPE_STARTER:
6181 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6182 if (g_strcmp0 (starter_bus, "session") == 0)
6184 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6187 else if (g_strcmp0 (starter_bus, "system") == 0)
6189 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6194 if (starter_bus != NULL)
6198 G_IO_ERROR_INVALID_ARGUMENT,
6199 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6200 " - unknown value `%s'"),
6205 g_set_error_literal (error,
6207 G_IO_ERROR_INVALID_ARGUMENT,
6208 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6209 "variable is not set"));
6215 g_assert_not_reached ();
6223 static GDBusConnection *
6224 get_uninitialized_connection (GBusType bus_type,
6225 GCancellable *cancellable,
6228 GDBusConnection **singleton;
6229 GDBusConnection *ret;
6233 G_LOCK (message_bus_lock);
6234 singleton = message_bus_get_singleton (bus_type, error);
6235 if (singleton == NULL)
6238 if (*singleton == NULL)
6241 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6242 if (address == NULL)
6244 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6246 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6247 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6248 "exit-on-close", TRUE,
6254 ret = g_object_ref (*singleton);
6257 g_assert (ret != NULL);
6260 G_UNLOCK (message_bus_lock);
6266 * @bus_type: A #GBusType.
6267 * @cancellable: A #GCancellable or %NULL.
6268 * @error: Return location for error or %NULL.
6270 * Synchronously connects to the message bus specified by @bus_type.
6271 * Note that the returned object may shared with other callers,
6272 * e.g. if two separate parts of a process calls this function with
6273 * the same @bus_type, they will share the same object.
6275 * This is a synchronous failable function. See g_bus_get() and
6276 * g_bus_get_finish() for the asynchronous version.
6278 * The returned object is a singleton, that is, shared with other
6279 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6280 * event that you need a private message bus connection, use
6281 * g_dbus_address_get_for_bus_sync() and
6282 * g_dbus_connection_new_for_address().
6284 * Note that the returned #GDBusConnection object will (usually) have
6285 * the #GDBusConnection:exit-on-close property set to %TRUE.
6287 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6292 g_bus_get_sync (GBusType bus_type,
6293 GCancellable *cancellable,
6296 GDBusConnection *connection;
6298 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6300 connection = get_uninitialized_connection (bus_type, cancellable, error);
6301 if (connection == NULL)
6304 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6306 g_object_unref (connection);
6315 bus_get_async_initable_cb (GObject *source_object,
6319 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6323 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6327 g_assert (error != NULL);
6328 g_simple_async_result_take_error (simple, error);
6329 g_object_unref (source_object);
6333 g_simple_async_result_set_op_res_gpointer (simple,
6337 g_simple_async_result_complete_in_idle (simple);
6338 g_object_unref (simple);
6343 * @bus_type: A #GBusType.
6344 * @cancellable: A #GCancellable or %NULL.
6345 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6346 * @user_data: The data to pass to @callback.
6348 * Asynchronously connects to the message bus specified by @bus_type.
6350 * When the operation is finished, @callback will be invoked. You can
6351 * then call g_bus_get_finish() to get the result of the operation.
6353 * This is a asynchronous failable function. See g_bus_get_sync() for
6354 * the synchronous version.
6359 g_bus_get (GBusType bus_type,
6360 GCancellable *cancellable,
6361 GAsyncReadyCallback callback,
6364 GDBusConnection *connection;
6365 GSimpleAsyncResult *simple;
6368 simple = g_simple_async_result_new (NULL,
6374 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6375 if (connection == NULL)
6377 g_assert (error != NULL);
6378 g_simple_async_result_take_error (simple, error);
6379 g_simple_async_result_complete_in_idle (simple);
6380 g_object_unref (simple);
6384 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6387 bus_get_async_initable_cb,
6394 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6395 * @error: Return location for error or %NULL.
6397 * Finishes an operation started with g_bus_get().
6399 * The returned object is a singleton, that is, shared with other
6400 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6401 * event that you need a private message bus connection, use
6402 * g_dbus_address_get_for_bus_sync() and
6403 * g_dbus_connection_new_for_address().
6405 * Note that the returned #GDBusConnection object will (usually) have
6406 * the #GDBusConnection:exit-on-close property set to %TRUE.
6408 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6413 g_bus_get_finish (GAsyncResult *res,
6416 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6418 GDBusConnection *ret;
6420 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6422 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6426 if (g_simple_async_result_propagate_error (simple, error))
6429 object = g_simple_async_result_get_op_res_gpointer (simple);
6430 g_assert (object != NULL);
6431 ret = g_object_ref (G_DBUS_CONNECTION (object));
6437 /* ---------------------------------------------------------------------------------------------------- */