1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * Most of the ways to obtain a #GDBusConnection automatically initialize it
152 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
153 * g_bus_get(), and the synchronous versions of those methods, give you an
154 * initialized connection. Language bindings for GIO should use
155 * g_initable_new() or g_async_initable_new(), which also initialize the
158 * If you construct an uninitialized #GDBusConnection, such as via
159 * g_object_new(), you must initialize it via g_initable_init() or
160 * g_async_initable_init() before using its methods or properties. Calling
161 * methods or accessing properties on a #GDBusConnection that has not completed
162 * initialization successfully is considered to be invalid, and leads to
163 * undefined behaviour. In particular, if initialization fails with a #GError,
164 * the only valid thing you can do with that #GDBusConnection is to free it
165 * with g_object_unref().
167 * <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>
169 * <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>
171 * <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>
173 * <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>
176 /* ---------------------------------------------------------------------------------------------------- */
178 typedef struct _GDBusConnectionClass GDBusConnectionClass;
181 * GDBusConnectionClass:
182 * @closed: Signal class handler for the #GDBusConnection::closed signal.
184 * Class structure for #GDBusConnection.
188 struct _GDBusConnectionClass
191 GObjectClass parent_class;
195 void (*closed) (GDBusConnection *connection,
196 gboolean remote_peer_vanished,
200 G_LOCK_DEFINE_STATIC (message_bus_lock);
202 static GDBusConnection *the_session_bus = NULL;
203 static GDBusConnection *the_system_bus = NULL;
205 /* Extra pseudo-member of GDBusSendMessageFlags.
206 * Set by initable_init() to indicate that despite not being initialized yet,
207 * enough of the only-valid-after-init members are set that we can send a
208 * message, and we're being called from its thread, so no memory barrier is
209 * required before accessing them.
211 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
213 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
214 #define CALL_FLAGS_INITIALIZING (1<<31)
216 /* ---------------------------------------------------------------------------------------------------- */
220 GDestroyNotify callback;
222 GMainContext *context;
223 } CallDestroyNotifyData;
226 call_destroy_notify_data_in_idle (gpointer user_data)
228 CallDestroyNotifyData *data = user_data;
229 data->callback (data->user_data);
234 call_destroy_notify_data_free (CallDestroyNotifyData *data)
236 if (data->context != NULL)
237 g_main_context_unref (data->context);
242 * call_destroy_notify: <internal>
243 * @context: A #GMainContext or %NULL.
244 * @callback: A #GDestroyNotify or %NULL.
245 * @user_data: Data to pass to @callback.
247 * Schedules @callback to run in @context.
250 call_destroy_notify (GMainContext *context,
251 GDestroyNotify callback,
254 GMainContext *current_context;
256 if (callback == NULL)
259 current_context = g_main_context_get_thread_default ();
260 if ((context == current_context) ||
261 (current_context == NULL && context == g_main_context_default ()))
263 callback (user_data);
267 GSource *idle_source;
268 CallDestroyNotifyData *data;
270 data = g_new0 (CallDestroyNotifyData, 1);
271 data->callback = callback;
272 data->user_data = user_data;
273 data->context = context;
274 if (data->context != NULL)
275 g_main_context_ref (data->context);
277 idle_source = g_idle_source_new ();
278 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
279 g_source_set_callback (idle_source,
280 call_destroy_notify_data_in_idle,
282 (GDestroyNotify) call_destroy_notify_data_free);
283 g_source_attach (idle_source, data->context);
284 g_source_unref (idle_source);
291 /* ---------------------------------------------------------------------------------------------------- */
294 _g_strv_has_string (const gchar* const *haystack,
299 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
301 if (g_strcmp0 (haystack[n], needle) == 0)
307 /* ---------------------------------------------------------------------------------------------------- */
310 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
312 // TODO: for some reason this doesn't work on Windows
313 #define CONNECTION_ENSURE_LOCK(obj) do { \
314 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
316 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
317 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
322 #define CONNECTION_LOCK(obj) do { \
323 g_mutex_lock (&(obj)->lock); \
326 #define CONNECTION_UNLOCK(obj) do { \
327 g_mutex_unlock (&(obj)->lock); \
330 /* Flags in connection->atomic_flags */
332 FLAG_INITIALIZED = 1 << 0
338 * The #GDBusConnection structure contains only private data and
339 * should only be accessed using the provided API.
343 struct _GDBusConnection
346 GObject parent_instance;
348 /* ------------------------------------------------------------------------ */
349 /* -- General object state ------------------------------------------------ */
350 /* ------------------------------------------------------------------------ */
352 /* object-wide lock */
355 /* A lock used in the init() method of the GInitable interface - see comments
356 * in initable_init() for why a separate lock is needed
360 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
361 * someone calls org.freedesktop.DBus.GetMachineId()
365 /* The underlying stream used for communication
366 * Read-only after initable_init(), so it may be read if you either
367 * hold @init_lock or check for initialization first.
371 /* The object used for authentication (if any).
372 * Read-only after initable_init(), so it may be read if you either
373 * hold @init_lock or check for initialization first.
377 /* Set to TRUE if the connection has been closed */
380 /* Last serial used */
383 /* The object used to send/receive messages.
384 * Read-only after initable_init(), so it may be read if you either
385 * hold @init_lock or check for initialization first.
389 /* If connected to a message bus, this contains the unique name assigned to
390 * us by the bus (e.g. ":1.42").
391 * Read-only after initable_init(), so it may be read if you either
392 * hold @init_lock or check for initialization first.
394 gchar *bus_unique_name;
396 /* The GUID returned by the other side if we authenticed as a client or
397 * the GUID to use if authenticating as a server.
398 * Read-only after initable_init(), so it may be read if you either
399 * hold @init_lock or check for initialization first.
403 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
404 * Inspect @initialization_error to see whether it succeeded or failed.
406 volatile gint atomic_flags;
408 /* If the connection could not be established during initable_init(),
409 * this GError will be set.
410 * Read-only after initable_init(), so it may be read if you either
411 * hold @init_lock or check for initialization first.
413 GError *initialization_error;
415 /* The result of g_main_context_ref_thread_default() when the object
416 * was created (the GObject _init() function) - this is used for delivery
417 * of the :closed GObject signal.
419 GMainContext *main_context_at_construction;
421 /* construct properties */
423 GDBusConnectionFlags flags;
425 /* Map used for managing method replies */
426 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
428 /* Maps used for managing signal subscription */
429 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
430 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
431 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
433 /* Maps used for managing exported objects and subtrees */
434 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
435 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
436 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
437 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
439 /* Structure used for message filters */
442 /* Whether to exit on close */
443 gboolean exit_on_close;
445 /* Capabilities negotiated during authentication
446 * Read-only after initable_init(), so it may be read without holding a
447 * lock, if you check for initialization first.
449 GDBusCapabilityFlags capabilities;
451 GDBusAuthObserver *authentication_observer;
453 /* Read-only after initable_init(), so it may be read if you either
454 * hold @init_lock or check for initialization first.
456 GCredentials *credentials;
458 /* set to TRUE when finalizing */
462 typedef struct ExportedObject ExportedObject;
463 static void exported_object_free (ExportedObject *eo);
465 typedef struct ExportedSubtree ExportedSubtree;
466 static void exported_subtree_free (ExportedSubtree *es);
484 PROP_CAPABILITY_FLAGS,
485 PROP_AUTHENTICATION_OBSERVER,
488 static void distribute_signals (GDBusConnection *connection,
489 GDBusMessage *message);
491 static void distribute_method_call (GDBusConnection *connection,
492 GDBusMessage *message);
494 static gboolean handle_generic_unlocked (GDBusConnection *connection,
495 GDBusMessage *message);
498 static void purge_all_signal_subscriptions (GDBusConnection *connection);
499 static void purge_all_filters (GDBusConnection *connection);
501 #define _G_ENSURE_LOCK(name) do { \
502 if (G_UNLIKELY (G_TRYLOCK(name))) \
504 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
505 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
509 static guint signals[LAST_SIGNAL] = { 0 };
511 static void initable_iface_init (GInitableIface *initable_iface);
512 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
514 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
515 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
516 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
520 * Check that all members of @connection that can only be accessed after
521 * the connection is initialized can safely be accessed. If not,
522 * log a critical warning. This function is a memory barrier.
524 * Returns: %TRUE if initialized
527 check_initialized (GDBusConnection *connection)
529 /* The access to @atomic_flags isn't conditional, so that this function
530 * provides a memory barrier for thread-safety even if checks are disabled.
531 * (If you don't want this stricter guarantee, you can call
532 * g_return_if_fail (check_initialized (c)).)
534 * This isn't strictly necessary now that we've decided use of an
535 * uninitialized GDBusConnection is undefined behaviour, but it seems
536 * better to be as deterministic as is feasible.
538 * (Anything that could suffer a crash from seeing undefined values
539 * must have a race condition - thread A initializes the connection while
540 * thread B calls a method without initialization, hoping that thread A will
541 * win the race - so its behaviour is undefined anyway.)
543 gint flags = g_atomic_int_get (&connection->atomic_flags);
545 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
547 /* We can safely access this, due to the memory barrier above */
548 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
553 static GHashTable *alive_connections = NULL;
556 g_dbus_connection_dispose (GObject *object)
558 GDBusConnection *connection = G_DBUS_CONNECTION (object);
560 G_LOCK (message_bus_lock);
561 if (connection == the_session_bus)
563 the_session_bus = NULL;
565 else if (connection == the_system_bus)
567 the_system_bus = NULL;
569 CONNECTION_LOCK (connection);
570 if (connection->worker != NULL)
572 _g_dbus_worker_stop (connection->worker);
573 connection->worker = NULL;
574 if (alive_connections != NULL)
575 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
579 if (alive_connections != NULL)
580 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
582 CONNECTION_UNLOCK (connection);
583 G_UNLOCK (message_bus_lock);
585 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
586 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
590 g_dbus_connection_finalize (GObject *object)
592 GDBusConnection *connection = G_DBUS_CONNECTION (object);
594 connection->finalizing = TRUE;
596 purge_all_signal_subscriptions (connection);
598 purge_all_filters (connection);
599 g_ptr_array_unref (connection->filters);
601 if (connection->authentication_observer != NULL)
602 g_object_unref (connection->authentication_observer);
604 if (connection->auth != NULL)
605 g_object_unref (connection->auth);
607 if (connection->credentials)
608 g_object_unref (connection->credentials);
610 if (connection->stream != NULL)
612 g_object_unref (connection->stream);
613 connection->stream = NULL;
616 g_free (connection->address);
618 g_free (connection->guid);
619 g_free (connection->bus_unique_name);
621 if (connection->initialization_error != NULL)
622 g_error_free (connection->initialization_error);
624 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
626 g_hash_table_unref (connection->map_rule_to_signal_data);
627 g_hash_table_unref (connection->map_id_to_signal_data);
628 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
630 g_hash_table_unref (connection->map_id_to_ei);
631 g_hash_table_unref (connection->map_object_path_to_eo);
632 g_hash_table_unref (connection->map_id_to_es);
633 g_hash_table_unref (connection->map_object_path_to_es);
635 g_main_context_unref (connection->main_context_at_construction);
637 g_free (connection->machine_id);
639 g_mutex_clear (&connection->init_lock);
640 g_mutex_clear (&connection->lock);
642 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
645 /* called in any user thread, with the connection's lock not held */
647 g_dbus_connection_get_property (GObject *object,
652 GDBusConnection *connection = G_DBUS_CONNECTION (object);
657 g_value_set_object (value, g_dbus_connection_get_stream (connection));
661 g_value_set_string (value, g_dbus_connection_get_guid (connection));
664 case PROP_UNIQUE_NAME:
665 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
669 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
672 case PROP_EXIT_ON_CLOSE:
673 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
676 case PROP_CAPABILITY_FLAGS:
677 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
681 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
686 /* called in any user thread, with the connection's lock not held */
688 g_dbus_connection_set_property (GObject *object,
693 GDBusConnection *connection = G_DBUS_CONNECTION (object);
698 connection->stream = g_value_dup_object (value);
702 connection->guid = g_value_dup_string (value);
706 connection->address = g_value_dup_string (value);
710 connection->flags = g_value_get_flags (value);
713 case PROP_EXIT_ON_CLOSE:
714 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
717 case PROP_AUTHENTICATION_OBSERVER:
718 connection->authentication_observer = g_value_dup_object (value);
722 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
727 /* Base-class implementation of GDBusConnection::closed.
729 * Called in a user thread, by the main context that was thread-default when
730 * the object was constructed.
733 g_dbus_connection_real_closed (GDBusConnection *connection,
734 gboolean remote_peer_vanished,
737 gint flags = g_atomic_int_get (&connection->atomic_flags);
739 /* Because atomic int access is a memory barrier, we can safely read
740 * initialization_error without a lock, as long as we do it afterwards.
742 if (remote_peer_vanished && connection->exit_on_close &&
743 (flags & FLAG_INITIALIZED) != 0 &&
744 connection->initialization_error == NULL)
748 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
751 g_quark_to_string (error->domain), error->code);
755 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
762 g_dbus_connection_class_init (GDBusConnectionClass *klass)
764 GObjectClass *gobject_class;
766 gobject_class = G_OBJECT_CLASS (klass);
768 gobject_class->finalize = g_dbus_connection_finalize;
769 gobject_class->dispose = g_dbus_connection_dispose;
770 gobject_class->set_property = g_dbus_connection_set_property;
771 gobject_class->get_property = g_dbus_connection_get_property;
773 klass->closed = g_dbus_connection_real_closed;
776 * GDBusConnection:stream:
778 * The underlying #GIOStream used for I/O.
780 * If this is passed on construction and is a #GSocketConnection,
781 * then the corresponding #GSocket will be put into non-blocking mode.
783 * While the #GDBusConnection is active, it will interact with this
784 * stream from a worker thread, so it is not safe to interact with
785 * the stream directly.
789 g_object_class_install_property (gobject_class,
791 g_param_spec_object ("stream",
793 P_("The underlying streams used for I/O"),
797 G_PARAM_CONSTRUCT_ONLY |
798 G_PARAM_STATIC_NAME |
799 G_PARAM_STATIC_BLURB |
800 G_PARAM_STATIC_NICK));
803 * GDBusConnection:address:
805 * A D-Bus address specifying potential endpoints that can be used
806 * when establishing the connection.
810 g_object_class_install_property (gobject_class,
812 g_param_spec_string ("address",
814 P_("D-Bus address specifying potential socket endpoints"),
817 G_PARAM_CONSTRUCT_ONLY |
818 G_PARAM_STATIC_NAME |
819 G_PARAM_STATIC_BLURB |
820 G_PARAM_STATIC_NICK));
823 * GDBusConnection:flags:
825 * Flags from the #GDBusConnectionFlags enumeration.
829 g_object_class_install_property (gobject_class,
831 g_param_spec_flags ("flags",
834 G_TYPE_DBUS_CONNECTION_FLAGS,
835 G_DBUS_CONNECTION_FLAGS_NONE,
837 G_PARAM_CONSTRUCT_ONLY |
838 G_PARAM_STATIC_NAME |
839 G_PARAM_STATIC_BLURB |
840 G_PARAM_STATIC_NICK));
843 * GDBusConnection:guid:
845 * The GUID of the peer performing the role of server when
848 * If you are constructing a #GDBusConnection and pass
849 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
850 * #GDBusConnection:flags property then you MUST also set this
851 * property to a valid guid.
853 * If you are constructing a #GDBusConnection and pass
854 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
855 * #GDBusConnection:flags property you will be able to read the GUID
856 * of the other peer here after the connection has been successfully
861 g_object_class_install_property (gobject_class,
863 g_param_spec_string ("guid",
865 P_("GUID of the server peer"),
869 G_PARAM_CONSTRUCT_ONLY |
870 G_PARAM_STATIC_NAME |
871 G_PARAM_STATIC_BLURB |
872 G_PARAM_STATIC_NICK));
875 * GDBusConnection:unique-name:
877 * The unique name as assigned by the message bus or %NULL if the
878 * connection is not open or not a message bus connection.
882 g_object_class_install_property (gobject_class,
884 g_param_spec_string ("unique-name",
886 P_("Unique name of bus connection"),
889 G_PARAM_STATIC_NAME |
890 G_PARAM_STATIC_BLURB |
891 G_PARAM_STATIC_NICK));
894 * GDBusConnection:closed:
896 * A boolean specifying whether the connection has been closed.
900 g_object_class_install_property (gobject_class,
902 g_param_spec_boolean ("closed",
904 P_("Whether the connection is closed"),
907 G_PARAM_STATIC_NAME |
908 G_PARAM_STATIC_BLURB |
909 G_PARAM_STATIC_NICK));
912 * GDBusConnection:exit-on-close:
914 * A boolean specifying whether the process will be terminated (by
915 * calling <literal>raise(SIGTERM)</literal>) if the connection
916 * is closed by the remote peer.
920 g_object_class_install_property (gobject_class,
922 g_param_spec_boolean ("exit-on-close",
924 P_("Whether the process is terminated when the connection is closed"),
928 G_PARAM_STATIC_NAME |
929 G_PARAM_STATIC_BLURB |
930 G_PARAM_STATIC_NICK));
933 * GDBusConnection:capabilities:
935 * Flags from the #GDBusCapabilityFlags enumeration
936 * representing connection features negotiated with the other peer.
940 g_object_class_install_property (gobject_class,
941 PROP_CAPABILITY_FLAGS,
942 g_param_spec_flags ("capabilities",
945 G_TYPE_DBUS_CAPABILITY_FLAGS,
946 G_DBUS_CAPABILITY_FLAGS_NONE,
948 G_PARAM_STATIC_NAME |
949 G_PARAM_STATIC_BLURB |
950 G_PARAM_STATIC_NICK));
953 * GDBusConnection:authentication-observer:
955 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
959 g_object_class_install_property (gobject_class,
960 PROP_AUTHENTICATION_OBSERVER,
961 g_param_spec_object ("authentication-observer",
962 P_("Authentication Observer"),
963 P_("Object used to assist in the authentication process"),
964 G_TYPE_DBUS_AUTH_OBSERVER,
966 G_PARAM_CONSTRUCT_ONLY |
967 G_PARAM_STATIC_NAME |
968 G_PARAM_STATIC_BLURB |
969 G_PARAM_STATIC_NICK));
972 * GDBusConnection::closed:
973 * @connection: The #GDBusConnection emitting the signal.
974 * @remote_peer_vanished: %TRUE if @connection is closed because the
975 * remote peer closed its end of the connection.
976 * @error: A #GError with more details about the event or %NULL.
978 * Emitted when the connection is closed.
980 * The cause of this event can be
983 * If g_dbus_connection_close() is called. In this case
984 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
987 * If the remote peer closes the connection. In this case
988 * @remote_peer_vanished is set to %TRUE and @error is set.
991 * If the remote peer sends invalid or malformed data. In this
992 * case @remote_peer_vanished is set to %FALSE and @error
997 * Upon receiving this signal, you should give up your reference to
998 * @connection. You are guaranteed that this signal is emitted only
1003 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1004 G_TYPE_DBUS_CONNECTION,
1006 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1017 g_dbus_connection_init (GDBusConnection *connection)
1019 g_mutex_init (&connection->lock);
1020 g_mutex_init (&connection->init_lock);
1022 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1024 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1026 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1028 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1031 (GDestroyNotify) g_ptr_array_unref);
1033 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1036 (GDestroyNotify) exported_object_free);
1038 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1041 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1044 (GDestroyNotify) exported_subtree_free);
1046 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1049 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1051 connection->filters = g_ptr_array_new ();
1055 * g_dbus_connection_get_stream:
1056 * @connection: a #GDBusConnection
1058 * Gets the underlying stream used for IO.
1060 * While the #GDBusConnection is active, it will interact with this
1061 * stream from a worker thread, so it is not safe to interact with
1062 * the stream directly.
1064 * Returns: (transfer none): the stream used for IO
1069 g_dbus_connection_get_stream (GDBusConnection *connection)
1071 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1073 /* do not use g_return_val_if_fail(), we want the memory barrier */
1074 if (!check_initialized (connection))
1077 return connection->stream;
1081 * g_dbus_connection_start_message_processing:
1082 * @connection: A #GDBusConnection.
1084 * If @connection was created with
1085 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1086 * starts processing messages. Does nothing on if @connection wasn't
1087 * created with this flag or if the method has already been called.
1092 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1094 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1096 /* do not use g_return_val_if_fail(), we want the memory barrier */
1097 if (!check_initialized (connection))
1100 g_assert (connection->worker != NULL);
1101 _g_dbus_worker_unfreeze (connection->worker);
1105 * g_dbus_connection_is_closed:
1106 * @connection: A #GDBusConnection.
1108 * Gets whether @connection is closed.
1110 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1115 g_dbus_connection_is_closed (GDBusConnection *connection)
1117 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1118 return connection->closed;
1122 * g_dbus_connection_get_capabilities:
1123 * @connection: A #GDBusConnection.
1125 * Gets the capabilities negotiated with the remote peer
1127 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1131 GDBusCapabilityFlags
1132 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1134 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1136 /* do not use g_return_val_if_fail(), we want the memory barrier */
1137 if (!check_initialized (connection))
1138 return G_DBUS_CAPABILITY_FLAGS_NONE;
1140 return connection->capabilities;
1143 /* ---------------------------------------------------------------------------------------------------- */
1145 /* Called in a temporary thread without holding locks. */
1147 flush_in_thread_func (GSimpleAsyncResult *res,
1149 GCancellable *cancellable)
1154 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1157 g_simple_async_result_take_error (res, error);
1161 * g_dbus_connection_flush:
1162 * @connection: A #GDBusConnection.
1163 * @cancellable: A #GCancellable or %NULL.
1164 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1165 * satisfied or %NULL if you don't care about the result.
1166 * @user_data: The data to pass to @callback.
1168 * Asynchronously flushes @connection, that is, writes all queued
1169 * outgoing message to the transport and then flushes the transport
1170 * (using g_output_stream_flush_async()). This is useful in programs
1171 * that wants to emit a D-Bus signal and then exit
1172 * immediately. Without flushing the connection, there is no guarantee
1173 * that the message has been sent to the networking buffers in the OS
1176 * This is an asynchronous method. When the operation is finished,
1177 * @callback will be invoked in the <link
1178 * linkend="g-main-context-push-thread-default">thread-default main
1179 * loop</link> of the thread you are calling this method from. You can
1180 * then call g_dbus_connection_flush_finish() to get the result of the
1181 * operation. See g_dbus_connection_flush_sync() for the synchronous
1187 g_dbus_connection_flush (GDBusConnection *connection,
1188 GCancellable *cancellable,
1189 GAsyncReadyCallback callback,
1192 GSimpleAsyncResult *simple;
1194 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1196 simple = g_simple_async_result_new (G_OBJECT (connection),
1199 g_dbus_connection_flush);
1200 g_simple_async_result_run_in_thread (simple,
1201 flush_in_thread_func,
1204 g_object_unref (simple);
1208 * g_dbus_connection_flush_finish:
1209 * @connection: A #GDBusConnection.
1210 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1211 * @error: Return location for error or %NULL.
1213 * Finishes an operation started with g_dbus_connection_flush().
1215 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1220 g_dbus_connection_flush_finish (GDBusConnection *connection,
1224 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1229 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1230 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1231 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1233 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1235 if (g_simple_async_result_propagate_error (simple, error))
1245 * g_dbus_connection_flush_sync:
1246 * @connection: A #GDBusConnection.
1247 * @cancellable: A #GCancellable or %NULL.
1248 * @error: Return location for error or %NULL.
1250 * Synchronously flushes @connection. The calling thread is blocked
1251 * until this is done. See g_dbus_connection_flush() for the
1252 * asynchronous version of this method and more details about what it
1255 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1260 g_dbus_connection_flush_sync (GDBusConnection *connection,
1261 GCancellable *cancellable,
1266 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1267 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1271 /* do not use g_return_val_if_fail(), we want the memory barrier */
1272 if (!check_initialized (connection))
1275 g_assert (connection->worker != NULL);
1277 if (connection->closed)
1279 g_set_error_literal (error,
1282 _("The connection is closed"));
1286 ret = _g_dbus_worker_flush_sync (connection->worker,
1294 /* ---------------------------------------------------------------------------------------------------- */
1298 GDBusConnection *connection;
1300 gboolean remote_peer_vanished;
1304 emit_closed_data_free (EmitClosedData *data)
1306 g_object_unref (data->connection);
1307 if (data->error != NULL)
1308 g_error_free (data->error);
1312 /* Called in a user thread that has acquired the main context that was
1313 * thread-default when the object was constructed
1316 emit_closed_in_idle (gpointer user_data)
1318 EmitClosedData *data = user_data;
1321 g_object_notify (G_OBJECT (data->connection), "closed");
1322 g_signal_emit (data->connection,
1323 signals[CLOSED_SIGNAL],
1325 data->remote_peer_vanished,
1331 /* Can be called from any thread, must hold lock */
1333 set_closed_unlocked (GDBusConnection *connection,
1334 gboolean remote_peer_vanished,
1337 GSource *idle_source;
1338 EmitClosedData *data;
1340 CONNECTION_ENSURE_LOCK (connection);
1342 g_assert (!connection->closed);
1344 connection->closed = TRUE;
1346 data = g_new0 (EmitClosedData, 1);
1347 data->connection = g_object_ref (connection);
1348 data->remote_peer_vanished = remote_peer_vanished;
1349 data->error = error != NULL ? g_error_copy (error) : NULL;
1351 idle_source = g_idle_source_new ();
1352 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1353 g_source_set_callback (idle_source,
1354 emit_closed_in_idle,
1356 (GDestroyNotify) emit_closed_data_free);
1357 g_source_attach (idle_source, connection->main_context_at_construction);
1358 g_source_unref (idle_source);
1361 /* ---------------------------------------------------------------------------------------------------- */
1364 * g_dbus_connection_close:
1365 * @connection: A #GDBusConnection.
1366 * @cancellable: A #GCancellable or %NULL.
1367 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1368 * satisfied or %NULL if you don't care about the result.
1369 * @user_data: The data to pass to @callback.
1371 * Closes @connection. Note that this never causes the process to
1372 * exit (this might only happen if the other end of a shared message
1373 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1375 * Once the connection is closed, operations such as sending a message
1376 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1377 * will not automatically flush the connection so queued messages may
1378 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1380 * If @connection is already closed, this method fails with
1381 * %G_IO_ERROR_CLOSED.
1383 * When @connection has been closed, the #GDBusConnection::closed
1384 * signal is emitted in the <link
1385 * linkend="g-main-context-push-thread-default">thread-default main
1386 * loop</link> of the thread that @connection was constructed in.
1388 * This is an asynchronous method. When the operation is finished,
1389 * @callback will be invoked in the <link
1390 * linkend="g-main-context-push-thread-default">thread-default main
1391 * loop</link> of the thread you are calling this method from. You can
1392 * then call g_dbus_connection_close_finish() to get the result of the
1393 * operation. See g_dbus_connection_close_sync() for the synchronous
1399 g_dbus_connection_close (GDBusConnection *connection,
1400 GCancellable *cancellable,
1401 GAsyncReadyCallback callback,
1404 GSimpleAsyncResult *simple;
1406 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1408 /* do not use g_return_val_if_fail(), we want the memory barrier */
1409 if (!check_initialized (connection))
1412 g_assert (connection->worker != NULL);
1414 simple = g_simple_async_result_new (G_OBJECT (connection),
1417 g_dbus_connection_close);
1418 _g_dbus_worker_close (connection->worker, cancellable, simple);
1419 g_object_unref (simple);
1423 * g_dbus_connection_close_finish:
1424 * @connection: A #GDBusConnection.
1425 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1426 * @error: Return location for error or %NULL.
1428 * Finishes an operation started with g_dbus_connection_close().
1430 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1435 g_dbus_connection_close_finish (GDBusConnection *connection,
1439 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1444 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1445 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1446 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1448 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1450 if (g_simple_async_result_propagate_error (simple, error))
1461 GAsyncResult *result;
1464 /* Can be called by any thread, without the connection lock */
1466 sync_close_cb (GObject *source_object,
1470 SyncCloseData *data = user_data;
1472 data->result = g_object_ref (res);
1473 g_main_loop_quit (data->loop);
1477 * g_dbus_connection_close_sync:
1478 * @connection: A #GDBusConnection.
1479 * @cancellable: A #GCancellable or %NULL.
1480 * @error: Return location for error or %NULL.
1482 * Synchronously closees @connection. The calling thread is blocked
1483 * until this is done. See g_dbus_connection_close() for the
1484 * asynchronous version of this method and more details about what it
1487 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1492 g_dbus_connection_close_sync (GDBusConnection *connection,
1493 GCancellable *cancellable,
1498 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1499 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1503 CONNECTION_LOCK (connection);
1504 if (!connection->closed)
1506 GMainContext *context;
1509 context = g_main_context_new ();
1510 g_main_context_push_thread_default (context);
1511 data.loop = g_main_loop_new (context, TRUE);
1514 CONNECTION_UNLOCK (connection);
1515 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1516 g_main_loop_run (data.loop);
1517 ret = g_dbus_connection_close_finish (connection, data.result, error);
1518 CONNECTION_LOCK (connection);
1520 g_object_unref (data.result);
1521 g_main_loop_unref (data.loop);
1522 g_main_context_pop_thread_default (context);
1523 g_main_context_unref (context);
1527 g_set_error_literal (error,
1530 _("The connection is closed"));
1532 CONNECTION_UNLOCK (connection);
1537 /* ---------------------------------------------------------------------------------------------------- */
1539 /* Can be called by any thread, with the connection lock held */
1541 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1542 GDBusMessage *message,
1543 GDBusSendMessageFlags flags,
1544 volatile guint32 *out_serial,
1549 guint32 serial_to_use;
1552 CONNECTION_ENSURE_LOCK (connection);
1554 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1555 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1557 /* TODO: check all necessary headers are present */
1562 if (out_serial != NULL)
1565 /* If we're in initable_init(), don't check for being initialized, to avoid
1566 * chicken-and-egg problems. initable_init() is responsible for setting up
1567 * our prerequisites (mainly connection->worker), and only calling us
1568 * from its own thread (so no memory barrier is needed).
1570 * In the case where we're not initializing, do not use
1571 * g_return_val_if_fail() - we want the memory barrier.
1573 if ((flags & SEND_MESSAGE_FLAGS_INITIALIZING) == 0 &&
1574 !check_initialized (connection))
1577 if (connection->closed)
1579 g_set_error_literal (error,
1582 _("The connection is closed"));
1586 blob = g_dbus_message_to_blob (message,
1588 connection->capabilities,
1593 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1594 serial_to_use = g_dbus_message_get_serial (message);
1596 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1601 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1604 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1607 g_assert_not_reached ();
1612 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1613 blob_size, serial_to_use, connection);
1614 g_printerr ("----\n");
1615 hexdump (blob, blob_size);
1616 g_printerr ("----\n");
1619 /* TODO: use connection->auth to encode the blob */
1621 if (out_serial != NULL)
1622 *out_serial = serial_to_use;
1624 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1625 g_dbus_message_set_serial (message, serial_to_use);
1627 g_dbus_message_lock (message);
1628 _g_dbus_worker_send_message (connection->worker,
1632 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1643 * g_dbus_connection_send_message:
1644 * @connection: A #GDBusConnection.
1645 * @message: A #GDBusMessage
1646 * @flags: Flags affecting how the message is sent.
1647 * @out_serial: (out) (allow-none): Return location for serial number assigned
1648 * to @message when sending it or %NULL.
1649 * @error: Return location for error or %NULL.
1651 * Asynchronously sends @message to the peer represented by @connection.
1653 * Unless @flags contain the
1654 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1655 * will be assigned by @connection and set on @message via
1656 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1657 * serial number used will be written to this location prior to
1658 * submitting the message to the underlying transport.
1660 * If @connection is closed then the operation will fail with
1661 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1662 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1664 * See <xref linkend="gdbus-server"/> and <xref
1665 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1666 * low-level API to send and receive UNIX file descriptors.
1668 * Note that @message must be unlocked, unless @flags contain the
1669 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1671 * Returns: %TRUE if the message was well-formed and queued for
1672 * transmission, %FALSE if @error is set.
1677 g_dbus_connection_send_message (GDBusConnection *connection,
1678 GDBusMessage *message,
1679 GDBusSendMessageFlags flags,
1680 volatile guint32 *out_serial,
1685 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1686 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1687 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1688 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1690 CONNECTION_LOCK (connection);
1691 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1692 CONNECTION_UNLOCK (connection);
1696 /* ---------------------------------------------------------------------------------------------------- */
1700 volatile gint ref_count;
1701 GDBusConnection *connection;
1703 GSimpleAsyncResult *simple;
1705 GMainContext *main_context;
1707 GCancellable *cancellable;
1709 gulong cancellable_handler_id;
1711 GSource *timeout_source;
1716 /* Can be called from any thread with or without lock held */
1717 static SendMessageData *
1718 send_message_data_ref (SendMessageData *data)
1720 g_atomic_int_inc (&data->ref_count);
1724 /* Can be called from any thread with or without lock held */
1726 send_message_data_unref (SendMessageData *data)
1728 if (g_atomic_int_dec_and_test (&data->ref_count))
1730 g_assert (data->timeout_source == NULL);
1731 g_assert (data->simple == NULL);
1732 g_assert (data->cancellable_handler_id == 0);
1733 g_object_unref (data->connection);
1734 if (data->cancellable != NULL)
1735 g_object_unref (data->cancellable);
1736 g_main_context_unref (data->main_context);
1741 /* ---------------------------------------------------------------------------------------------------- */
1743 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1745 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1747 CONNECTION_ENSURE_LOCK (data->connection);
1749 g_assert (!data->delivered);
1751 data->delivered = TRUE;
1753 g_simple_async_result_complete_in_idle (data->simple);
1754 g_object_unref (data->simple);
1755 data->simple = NULL;
1757 if (data->timeout_source != NULL)
1759 g_source_destroy (data->timeout_source);
1760 data->timeout_source = NULL;
1762 if (data->cancellable_handler_id > 0)
1764 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1765 data->cancellable_handler_id = 0;
1770 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1771 GUINT_TO_POINTER (data->serial)));
1774 send_message_data_unref (data);
1777 /* ---------------------------------------------------------------------------------------------------- */
1779 /* Can be called from any thread with lock held */
1781 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1782 GDBusMessage *reply)
1784 if (data->delivered)
1787 g_simple_async_result_set_op_res_gpointer (data->simple,
1788 g_object_ref (reply),
1791 send_message_with_reply_deliver (data, TRUE);
1797 /* ---------------------------------------------------------------------------------------------------- */
1799 /* Called from a user thread, lock is not held */
1801 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1803 SendMessageData *data = user_data;
1805 CONNECTION_LOCK (data->connection);
1806 if (data->delivered)
1809 g_simple_async_result_set_error (data->simple,
1811 G_IO_ERROR_CANCELLED,
1812 _("Operation was cancelled"));
1814 send_message_with_reply_deliver (data, TRUE);
1817 CONNECTION_UNLOCK (data->connection);
1821 /* Can be called from any thread with or without lock held */
1823 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1826 SendMessageData *data = user_data;
1827 GSource *idle_source;
1829 /* postpone cancellation to idle handler since we may be called directly
1830 * via g_cancellable_connect() (e.g. holding lock)
1832 idle_source = g_idle_source_new ();
1833 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1834 g_source_set_callback (idle_source,
1835 send_message_with_reply_cancelled_idle_cb,
1836 send_message_data_ref (data),
1837 (GDestroyNotify) send_message_data_unref);
1838 g_source_attach (idle_source, data->main_context);
1839 g_source_unref (idle_source);
1842 /* ---------------------------------------------------------------------------------------------------- */
1844 /* Called from a user thread, lock is not held */
1846 send_message_with_reply_timeout_cb (gpointer user_data)
1848 SendMessageData *data = user_data;
1850 CONNECTION_LOCK (data->connection);
1851 if (data->delivered)
1854 g_simple_async_result_set_error (data->simple,
1856 G_IO_ERROR_TIMED_OUT,
1857 _("Timeout was reached"));
1859 send_message_with_reply_deliver (data, TRUE);
1862 CONNECTION_UNLOCK (data->connection);
1867 /* ---------------------------------------------------------------------------------------------------- */
1869 /* Called from a user thread, connection's lock is held */
1871 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1872 GDBusMessage *message,
1873 GDBusSendMessageFlags flags,
1875 volatile guint32 *out_serial,
1876 GCancellable *cancellable,
1877 GAsyncReadyCallback callback,
1880 GSimpleAsyncResult *simple;
1881 SendMessageData *data;
1883 volatile guint32 serial;
1887 if (out_serial == NULL)
1888 out_serial = &serial;
1890 if (timeout_msec == -1)
1891 timeout_msec = 25 * 1000;
1893 simple = g_simple_async_result_new (G_OBJECT (connection),
1896 g_dbus_connection_send_message_with_reply);
1898 if (g_cancellable_is_cancelled (cancellable))
1900 g_simple_async_result_set_error (simple,
1902 G_IO_ERROR_CANCELLED,
1903 _("Operation was cancelled"));
1904 g_simple_async_result_complete_in_idle (simple);
1905 g_object_unref (simple);
1909 if (connection->closed)
1911 g_simple_async_result_set_error (simple,
1914 _("The connection is closed"));
1915 g_simple_async_result_complete_in_idle (simple);
1916 g_object_unref (simple);
1921 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1923 g_simple_async_result_take_error (simple, error);
1924 g_simple_async_result_complete_in_idle (simple);
1925 g_object_unref (simple);
1929 data = g_new0 (SendMessageData, 1);
1930 data->ref_count = 1;
1931 data->connection = g_object_ref (connection);
1932 data->simple = simple;
1933 data->serial = *out_serial;
1934 data->main_context = g_main_context_ref_thread_default ();
1936 if (cancellable != NULL)
1938 data->cancellable = g_object_ref (cancellable);
1939 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1940 G_CALLBACK (send_message_with_reply_cancelled_cb),
1941 send_message_data_ref (data),
1942 (GDestroyNotify) send_message_data_unref);
1943 g_object_set_data_full (G_OBJECT (simple),
1945 g_object_ref (cancellable),
1946 (GDestroyNotify) g_object_unref);
1949 if (timeout_msec != G_MAXINT)
1951 data->timeout_source = g_timeout_source_new (timeout_msec);
1952 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1953 g_source_set_callback (data->timeout_source,
1954 send_message_with_reply_timeout_cb,
1955 send_message_data_ref (data),
1956 (GDestroyNotify) send_message_data_unref);
1957 g_source_attach (data->timeout_source, data->main_context);
1958 g_source_unref (data->timeout_source);
1961 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1962 GUINT_TO_POINTER (*out_serial),
1970 * g_dbus_connection_send_message_with_reply:
1971 * @connection: A #GDBusConnection.
1972 * @message: A #GDBusMessage.
1973 * @flags: Flags affecting how the message is sent.
1974 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1975 * timeout or %G_MAXINT for no timeout.
1976 * @out_serial: (out) (allow-none): Return location for serial number assigned
1977 * to @message when sending it or %NULL.
1978 * @cancellable: A #GCancellable or %NULL.
1979 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1980 * satisfied or %NULL if you don't care about the result.
1981 * @user_data: The data to pass to @callback.
1983 * Asynchronously sends @message to the peer represented by @connection.
1985 * Unless @flags contain the
1986 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1987 * will be assigned by @connection and set on @message via
1988 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1989 * serial number used will be written to this location prior to
1990 * submitting the message to the underlying transport.
1992 * If @connection is closed then the operation will fail with
1993 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
1994 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
1995 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1997 * This is an asynchronous method. When the operation is finished, @callback will be invoked
1998 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
1999 * of the thread you are calling this method from. You can then call
2000 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2001 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2003 * Note that @message must be unlocked, unless @flags contain the
2004 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2006 * See <xref linkend="gdbus-server"/> and <xref
2007 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2008 * low-level API to send and receive UNIX file descriptors.
2013 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2014 GDBusMessage *message,
2015 GDBusSendMessageFlags flags,
2017 volatile guint32 *out_serial,
2018 GCancellable *cancellable,
2019 GAsyncReadyCallback callback,
2022 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2023 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2024 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2025 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2027 CONNECTION_LOCK (connection);
2028 g_dbus_connection_send_message_with_reply_unlocked (connection,
2036 CONNECTION_UNLOCK (connection);
2040 * g_dbus_connection_send_message_with_reply_finish:
2041 * @connection: a #GDBusConnection
2042 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2043 * @error: Return location for error or %NULL.
2045 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2047 * Note that @error is only set if a local in-process error
2048 * occurred. That is to say that the returned #GDBusMessage object may
2049 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2050 * g_dbus_message_to_gerror() to transcode this to a #GError.
2052 * See <xref linkend="gdbus-server"/> and <xref
2053 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2054 * low-level API to send and receive UNIX file descriptors.
2056 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2061 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2065 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2066 GDBusMessage *reply;
2067 GCancellable *cancellable;
2069 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2070 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2074 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2076 if (g_simple_async_result_propagate_error (simple, error))
2079 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2080 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2081 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2083 g_object_unref (reply);
2085 g_set_error_literal (error,
2087 G_IO_ERROR_CANCELLED,
2088 _("Operation was cancelled"));
2094 /* ---------------------------------------------------------------------------------------------------- */
2099 GMainContext *context;
2101 } SendMessageSyncData;
2103 /* Called from a user thread, lock is not held */
2105 send_message_with_reply_sync_cb (GDBusConnection *connection,
2109 SendMessageSyncData *data = user_data;
2110 data->res = g_object_ref (res);
2111 g_main_loop_quit (data->loop);
2115 * g_dbus_connection_send_message_with_reply_sync:
2116 * @connection: A #GDBusConnection.
2117 * @message: A #GDBusMessage.
2118 * @flags: Flags affecting how the message is sent.
2119 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2120 * timeout or %G_MAXINT for no timeout.
2121 * @out_serial: (out) (allow-none): Return location for serial number assigned
2122 * to @message when sending it or %NULL.
2123 * @cancellable: A #GCancellable or %NULL.
2124 * @error: Return location for error or %NULL.
2126 * Synchronously sends @message to the peer represented by @connection
2127 * and blocks the calling thread until a reply is received or the
2128 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2129 * for the asynchronous version of this method.
2131 * Unless @flags contain the
2132 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2133 * will be assigned by @connection and set on @message via
2134 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2135 * serial number used will be written to this location prior to
2136 * submitting the message to the underlying transport.
2138 * If @connection is closed then the operation will fail with
2139 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2140 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2141 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2143 * Note that @error is only set if a local in-process error
2144 * occurred. That is to say that the returned #GDBusMessage object may
2145 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2146 * g_dbus_message_to_gerror() to transcode this to a #GError.
2148 * See <xref linkend="gdbus-server"/> and <xref
2149 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2150 * low-level API to send and receive UNIX file descriptors.
2152 * Note that @message must be unlocked, unless @flags contain the
2153 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2155 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2160 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2161 GDBusMessage *message,
2162 GDBusSendMessageFlags flags,
2164 volatile guint32 *out_serial,
2165 GCancellable *cancellable,
2168 SendMessageSyncData *data;
2169 GDBusMessage *reply;
2171 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2172 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2173 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2174 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2175 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2177 data = g_new0 (SendMessageSyncData, 1);
2178 data->context = g_main_context_new ();
2179 data->loop = g_main_loop_new (data->context, FALSE);
2181 g_main_context_push_thread_default (data->context);
2183 g_dbus_connection_send_message_with_reply (connection,
2189 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2191 g_main_loop_run (data->loop);
2192 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2196 g_main_context_pop_thread_default (data->context);
2198 g_main_context_unref (data->context);
2199 g_main_loop_unref (data->loop);
2200 g_object_unref (data->res);
2206 /* ---------------------------------------------------------------------------------------------------- */
2210 GDBusMessageFilterFunction func;
2217 GDBusMessageFilterFunction filter_function;
2219 GDestroyNotify user_data_free_func;
2222 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2224 on_worker_message_received (GDBusWorker *worker,
2225 GDBusMessage *message,
2228 GDBusConnection *connection;
2229 FilterCallback *filters;
2234 G_LOCK (message_bus_lock);
2235 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2238 G_UNLOCK (message_bus_lock);
2241 connection = G_DBUS_CONNECTION (user_data);
2242 g_object_ref (connection);
2243 G_UNLOCK (message_bus_lock);
2245 //g_debug ("in on_worker_message_received");
2247 g_object_ref (message);
2248 g_dbus_message_lock (message);
2250 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2252 /* First collect the set of callback functions */
2253 CONNECTION_LOCK (connection);
2254 num_filters = connection->filters->len;
2255 filters = g_new0 (FilterCallback, num_filters);
2256 for (n = 0; n < num_filters; n++)
2258 FilterData *data = connection->filters->pdata[n];
2259 filters[n].func = data->filter_function;
2260 filters[n].user_data = data->user_data;
2262 CONNECTION_UNLOCK (connection);
2264 /* then call the filters in order (without holding the lock) */
2265 for (n = 0; n < num_filters; n++)
2267 message = filters[n].func (connection,
2270 filters[n].user_data);
2271 if (message == NULL)
2273 g_dbus_message_lock (message);
2276 /* Standard dispatch unless the filter ate the message - no need to
2277 * do anything if the message was altered
2279 if (message != NULL)
2281 GDBusMessageType message_type;
2283 message_type = g_dbus_message_get_message_type (message);
2284 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2286 guint32 reply_serial;
2287 SendMessageData *send_message_data;
2289 reply_serial = g_dbus_message_get_reply_serial (message);
2290 CONNECTION_LOCK (connection);
2291 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2292 GUINT_TO_POINTER (reply_serial));
2293 if (send_message_data != NULL)
2295 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2296 send_message_data_deliver_reply_unlocked (send_message_data, message);
2300 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2302 CONNECTION_UNLOCK (connection);
2304 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2306 CONNECTION_LOCK (connection);
2307 distribute_signals (connection, message);
2308 CONNECTION_UNLOCK (connection);
2310 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2312 CONNECTION_LOCK (connection);
2313 distribute_method_call (connection, message);
2314 CONNECTION_UNLOCK (connection);
2318 if (message != NULL)
2319 g_object_unref (message);
2320 g_object_unref (connection);
2324 /* Called in GDBusWorker's thread, lock is not held */
2325 static GDBusMessage *
2326 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2327 GDBusMessage *message,
2330 GDBusConnection *connection;
2331 FilterCallback *filters;
2336 G_LOCK (message_bus_lock);
2337 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2340 G_UNLOCK (message_bus_lock);
2343 connection = G_DBUS_CONNECTION (user_data);
2344 g_object_ref (connection);
2345 G_UNLOCK (message_bus_lock);
2347 //g_debug ("in on_worker_message_about_to_be_sent");
2349 /* First collect the set of callback functions */
2350 CONNECTION_LOCK (connection);
2351 num_filters = connection->filters->len;
2352 filters = g_new0 (FilterCallback, num_filters);
2353 for (n = 0; n < num_filters; n++)
2355 FilterData *data = connection->filters->pdata[n];
2356 filters[n].func = data->filter_function;
2357 filters[n].user_data = data->user_data;
2359 CONNECTION_UNLOCK (connection);
2361 /* then call the filters in order (without holding the lock) */
2362 for (n = 0; n < num_filters; n++)
2364 g_dbus_message_lock (message);
2365 message = filters[n].func (connection,
2368 filters[n].user_data);
2369 if (message == NULL)
2373 g_object_unref (connection);
2379 /* called with connection lock held, in GDBusWorker thread */
2381 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2383 SendMessageData *data = value;
2385 if (data->delivered)
2388 g_simple_async_result_set_error (data->simple,
2391 _("The connection is closed"));
2393 /* Ask send_message_with_reply_deliver not to remove the element from the
2394 * hash table - we're in the middle of a foreach; that would be unsafe.
2395 * Instead, return TRUE from this function so that it gets removed safely.
2397 send_message_with_reply_deliver (data, FALSE);
2401 /* Called in GDBusWorker's thread - we must not block - without lock held */
2403 on_worker_closed (GDBusWorker *worker,
2404 gboolean remote_peer_vanished,
2408 GDBusConnection *connection;
2411 G_LOCK (message_bus_lock);
2412 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2415 G_UNLOCK (message_bus_lock);
2418 connection = G_DBUS_CONNECTION (user_data);
2419 g_object_ref (connection);
2420 G_UNLOCK (message_bus_lock);
2422 //g_debug ("in on_worker_closed: %s", error->message);
2424 CONNECTION_LOCK (connection);
2425 if (!connection->closed)
2427 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2428 set_closed_unlocked (connection, remote_peer_vanished, error);
2430 CONNECTION_UNLOCK (connection);
2432 g_object_unref (connection);
2435 /* ---------------------------------------------------------------------------------------------------- */
2437 /* Determines the biggest set of capabilities we can support on this
2440 * Called with the init_lock held.
2442 static GDBusCapabilityFlags
2443 get_offered_capabilities_max (GDBusConnection *connection)
2445 GDBusCapabilityFlags ret;
2446 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2448 if (G_IS_UNIX_CONNECTION (connection->stream))
2449 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2454 /* Called in a user thread, lock is not held */
2456 initable_init (GInitable *initable,
2457 GCancellable *cancellable,
2460 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2463 /* This method needs to be idempotent to work with the singleton
2464 * pattern. See the docs for g_initable_init(). We implement this by
2467 * Unfortunately we can't use the main lock since the on_worker_*()
2468 * callbacks above needs the lock during initialization (for message
2469 * bus connections we do a synchronous Hello() call on the bus).
2471 g_mutex_lock (&connection->init_lock);
2475 /* Make this a no-op if we're already initialized (successfully or
2478 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2480 ret = (connection->initialization_error == NULL);
2484 /* Because of init_lock, we can't get here twice in different threads */
2485 g_assert (connection->initialization_error == NULL);
2487 /* The user can pass multiple (but mutally exclusive) construct
2490 * - stream (of type GIOStream)
2491 * - address (of type gchar*)
2493 * At the end of the day we end up with a non-NULL GIOStream
2494 * object in connection->stream.
2496 if (connection->address != NULL)
2498 g_assert (connection->stream == NULL);
2500 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2501 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2503 g_set_error_literal (error,
2505 G_IO_ERROR_INVALID_ARGUMENT,
2506 _("Unsupported flags encountered when constructing a client-side connection"));
2510 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2511 NULL, /* TODO: out_guid */
2513 &connection->initialization_error);
2514 if (connection->stream == NULL)
2517 else if (connection->stream != NULL)
2523 g_assert_not_reached ();
2526 /* Authenticate the connection */
2527 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2529 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2530 g_assert (connection->guid != NULL);
2531 connection->auth = _g_dbus_auth_new (connection->stream);
2532 if (!_g_dbus_auth_run_server (connection->auth,
2533 connection->authentication_observer,
2535 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2536 get_offered_capabilities_max (connection),
2537 &connection->capabilities,
2538 &connection->credentials,
2540 &connection->initialization_error))
2543 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2545 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2546 g_assert (connection->guid == NULL);
2547 connection->auth = _g_dbus_auth_new (connection->stream);
2548 connection->guid = _g_dbus_auth_run_client (connection->auth,
2549 get_offered_capabilities_max (connection),
2550 &connection->capabilities,
2552 &connection->initialization_error);
2553 if (connection->guid == NULL)
2557 if (connection->authentication_observer != NULL)
2559 g_object_unref (connection->authentication_observer);
2560 connection->authentication_observer = NULL;
2563 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2565 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2568 /* We want all IO operations to be non-blocking since they happen in
2569 * the worker thread which is shared by _all_ connections.
2571 if (G_IS_SOCKET_CONNECTION (connection->stream))
2573 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2577 G_LOCK (message_bus_lock);
2578 if (alive_connections == NULL)
2579 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2580 g_hash_table_insert (alive_connections, connection, connection);
2581 G_UNLOCK (message_bus_lock);
2583 connection->worker = _g_dbus_worker_new (connection->stream,
2584 connection->capabilities,
2585 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2586 on_worker_message_received,
2587 on_worker_message_about_to_be_sent,
2591 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2592 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2594 GVariant *hello_result;
2596 /* we could lift this restriction by adding code in gdbusprivate.c */
2597 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2599 g_set_error_literal (&connection->initialization_error,
2602 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2606 hello_result = g_dbus_connection_call_sync (connection,
2607 "org.freedesktop.DBus", /* name */
2608 "/org/freedesktop/DBus", /* path */
2609 "org.freedesktop.DBus", /* interface */
2611 NULL, /* parameters */
2612 G_VARIANT_TYPE ("(s)"),
2613 CALL_FLAGS_INITIALIZING,
2615 NULL, /* TODO: cancellable */
2616 &connection->initialization_error);
2617 if (hello_result == NULL)
2620 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2621 g_variant_unref (hello_result);
2622 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2629 g_assert (connection->initialization_error != NULL);
2630 g_propagate_error (error, g_error_copy (connection->initialization_error));
2633 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2634 g_mutex_unlock (&connection->init_lock);
2640 initable_iface_init (GInitableIface *initable_iface)
2642 initable_iface->init = initable_init;
2645 /* ---------------------------------------------------------------------------------------------------- */
2648 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2653 /* ---------------------------------------------------------------------------------------------------- */
2656 * g_dbus_connection_new:
2657 * @stream: A #GIOStream.
2658 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2659 * @flags: Flags describing how to make the connection.
2660 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2661 * @cancellable: A #GCancellable or %NULL.
2662 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2663 * @user_data: The data to pass to @callback.
2665 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2666 * with the end represented by @stream.
2668 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2669 * will be put into non-blocking mode.
2671 * The D-Bus connection will interact with @stream from a worker thread.
2672 * As a result, the caller should not interact with @stream after this
2673 * method has been called, except by calling g_object_unref() on it.
2675 * If @observer is not %NULL it may be used to control the
2676 * authentication process.
2678 * When the operation is finished, @callback will be invoked. You can
2679 * then call g_dbus_connection_new_finish() to get the result of the
2682 * This is a asynchronous failable constructor. See
2683 * g_dbus_connection_new_sync() for the synchronous
2689 g_dbus_connection_new (GIOStream *stream,
2691 GDBusConnectionFlags flags,
2692 GDBusAuthObserver *observer,
2693 GCancellable *cancellable,
2694 GAsyncReadyCallback callback,
2697 g_return_if_fail (G_IS_IO_STREAM (stream));
2698 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2706 "authentication-observer", observer,
2711 * g_dbus_connection_new_finish:
2712 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2713 * @error: Return location for error or %NULL.
2715 * Finishes an operation started with g_dbus_connection_new().
2717 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2722 g_dbus_connection_new_finish (GAsyncResult *res,
2726 GObject *source_object;
2728 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2729 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2731 source_object = g_async_result_get_source_object (res);
2732 g_assert (source_object != NULL);
2733 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2736 g_object_unref (source_object);
2738 return G_DBUS_CONNECTION (object);
2744 * g_dbus_connection_new_sync:
2745 * @stream: A #GIOStream.
2746 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2747 * @flags: Flags describing how to make the connection.
2748 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2749 * @cancellable: A #GCancellable or %NULL.
2750 * @error: Return location for error or %NULL.
2752 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2753 * with the end represented by @stream.
2755 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2756 * will be put into non-blocking mode.
2758 * The D-Bus connection will interact with @stream from a worker thread.
2759 * As a result, the caller should not interact with @stream after this
2760 * method has been called, except by calling g_object_unref() on it.
2762 * If @observer is not %NULL it may be used to control the
2763 * authentication process.
2765 * This is a synchronous failable constructor. See
2766 * g_dbus_connection_new() for the asynchronous version.
2768 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2773 g_dbus_connection_new_sync (GIOStream *stream,
2775 GDBusConnectionFlags flags,
2776 GDBusAuthObserver *observer,
2777 GCancellable *cancellable,
2780 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2781 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2782 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2788 "authentication-observer", observer,
2792 /* ---------------------------------------------------------------------------------------------------- */
2795 * g_dbus_connection_new_for_address:
2796 * @address: A D-Bus address.
2797 * @flags: Flags describing how to make the connection.
2798 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2799 * @cancellable: A #GCancellable or %NULL.
2800 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2801 * @user_data: The data to pass to @callback.
2803 * Asynchronously connects and sets up a D-Bus client connection for
2804 * exchanging D-Bus messages with an endpoint specified by @address
2805 * which must be in the D-Bus address format.
2807 * This constructor can only be used to initiate client-side
2808 * connections - use g_dbus_connection_new() if you need to act as the
2809 * server. In particular, @flags cannot contain the
2810 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2811 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2813 * When the operation is finished, @callback will be invoked. You can
2814 * then call g_dbus_connection_new_finish() to get the result of the
2817 * If @observer is not %NULL it may be used to control the
2818 * authentication process.
2820 * This is a asynchronous failable constructor. See
2821 * g_dbus_connection_new_for_address_sync() for the synchronous
2827 g_dbus_connection_new_for_address (const gchar *address,
2828 GDBusConnectionFlags flags,
2829 GDBusAuthObserver *observer,
2830 GCancellable *cancellable,
2831 GAsyncReadyCallback callback,
2834 g_return_if_fail (address != NULL);
2835 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2842 "authentication-observer", observer,
2847 * g_dbus_connection_new_for_address_finish:
2848 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2849 * @error: Return location for error or %NULL.
2851 * Finishes an operation started with g_dbus_connection_new_for_address().
2853 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2858 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2862 GObject *source_object;
2864 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2865 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2867 source_object = g_async_result_get_source_object (res);
2868 g_assert (source_object != NULL);
2869 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2872 g_object_unref (source_object);
2874 return G_DBUS_CONNECTION (object);
2880 * g_dbus_connection_new_for_address_sync:
2881 * @address: A D-Bus address.
2882 * @flags: Flags describing how to make the connection.
2883 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2884 * @cancellable: A #GCancellable or %NULL.
2885 * @error: Return location for error or %NULL.
2887 * Synchronously connects and sets up a D-Bus client connection for
2888 * exchanging D-Bus messages with an endpoint specified by @address
2889 * which must be in the D-Bus address format.
2891 * This constructor can only be used to initiate client-side
2892 * connections - use g_dbus_connection_new_sync() if you need to act
2893 * as the server. In particular, @flags cannot contain the
2894 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2895 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2897 * This is a synchronous failable constructor. See
2898 * g_dbus_connection_new_for_address() for the asynchronous version.
2900 * If @observer is not %NULL it may be used to control the
2901 * authentication process.
2903 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2908 g_dbus_connection_new_for_address_sync (const gchar *address,
2909 GDBusConnectionFlags flags,
2910 GDBusAuthObserver *observer,
2911 GCancellable *cancellable,
2914 g_return_val_if_fail (address != NULL, NULL);
2915 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2916 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2921 "authentication-observer", observer,
2925 /* ---------------------------------------------------------------------------------------------------- */
2928 * g_dbus_connection_set_exit_on_close:
2929 * @connection: A #GDBusConnection.
2930 * @exit_on_close: Whether the process should be terminated
2931 * when @connection is closed by the remote peer.
2933 * Sets whether the process should be terminated when @connection is
2934 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2937 * Note that this function should be used with care. Most modern UNIX
2938 * desktops tie the notion of a user session the session bus, and expect
2939 * all of a users applications to quit when their bus connection goes away.
2940 * If you are setting @exit_on_close to %FALSE for the shared session
2941 * bus connection, you should make sure that your application exits
2942 * when the user session ends.
2947 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2948 gboolean exit_on_close)
2950 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2951 connection->exit_on_close = exit_on_close;
2955 * g_dbus_connection_get_exit_on_close:
2956 * @connection: A #GDBusConnection.
2958 * Gets whether the process is terminated when @connection is
2959 * closed by the remote peer. See
2960 * #GDBusConnection:exit-on-close for more details.
2962 * Returns: Whether the process is terminated when @connection is
2963 * closed by the remote peer.
2968 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
2970 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
2971 return connection->exit_on_close;
2975 * g_dbus_connection_get_guid:
2976 * @connection: A #GDBusConnection.
2978 * The GUID of the peer performing the role of server when
2979 * authenticating. See #GDBusConnection:guid for more details.
2981 * Returns: The GUID. Do not free this string, it is owned by
2987 g_dbus_connection_get_guid (GDBusConnection *connection)
2989 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2990 return connection->guid;
2994 * g_dbus_connection_get_unique_name:
2995 * @connection: A #GDBusConnection.
2997 * Gets the unique name of @connection as assigned by the message
2998 * bus. This can also be used to figure out if @connection is a
2999 * message bus connection.
3001 * Returns: The unique name or %NULL if @connection is not a message
3002 * bus connection. Do not free this string, it is owned by
3008 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3010 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3012 /* do not use g_return_val_if_fail(), we want the memory barrier */
3013 if (!check_initialized (connection))
3016 return connection->bus_unique_name;
3020 * g_dbus_connection_get_peer_credentials:
3021 * @connection: A #GDBusConnection.
3023 * Gets the credentials of the authenticated peer. This will always
3024 * return %NULL unless @connection acted as a server
3025 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3026 * when set up and the client passed credentials as part of the
3027 * authentication process.
3029 * In a message bus setup, the message bus is always the server and
3030 * each application is a client. So this method will always return
3031 * %NULL for message bus clients.
3033 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3034 * this object, it is owned by @connection.
3039 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3041 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3043 /* do not use g_return_val_if_fail(), we want the memory barrier */
3044 if (!check_initialized (connection))
3047 return connection->credentials;
3050 /* ---------------------------------------------------------------------------------------------------- */
3052 static guint _global_filter_id = 1;
3055 * g_dbus_connection_add_filter:
3056 * @connection: A #GDBusConnection.
3057 * @filter_function: A filter function.
3058 * @user_data: User data to pass to @filter_function.
3059 * @user_data_free_func: Function to free @user_data with when filter
3060 * is removed or %NULL.
3062 * Adds a message filter. Filters are handlers that are run on all
3063 * incoming and outgoing messages, prior to standard dispatch. Filters
3064 * are run in the order that they were added. The same handler can be
3065 * added as a filter more than once, in which case it will be run more
3066 * than once. Filters added during a filter callback won't be run on
3067 * the message being processed. Filter functions are allowed to modify
3068 * and even drop messages.
3070 * Note that filters are run in a dedicated message handling thread so
3071 * they can't block and, generally, can't do anything but signal a
3072 * worker thread. Also note that filters are rarely needed - use API
3073 * such as g_dbus_connection_send_message_with_reply(),
3074 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3076 * If a filter consumes an incoming message the message is not
3077 * dispatched anywhere else - not even the standard dispatch machinery
3078 * (that API such as g_dbus_connection_signal_subscribe() and
3079 * g_dbus_connection_send_message_with_reply() relies on) will see the
3080 * message. Similary, if a filter consumes an outgoing message, the
3081 * message will not be sent to the other peer.
3083 * Returns: A filter identifier that can be used with
3084 * g_dbus_connection_remove_filter().
3089 g_dbus_connection_add_filter (GDBusConnection *connection,
3090 GDBusMessageFilterFunction filter_function,
3092 GDestroyNotify user_data_free_func)
3096 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3097 g_return_val_if_fail (filter_function != NULL, 0);
3098 g_return_val_if_fail (check_initialized (connection), 0);
3100 CONNECTION_LOCK (connection);
3101 data = g_new0 (FilterData, 1);
3102 data->id = _global_filter_id++; /* TODO: overflow etc. */
3103 data->filter_function = filter_function;
3104 data->user_data = user_data;
3105 data->user_data_free_func = user_data_free_func;
3106 g_ptr_array_add (connection->filters, data);
3107 CONNECTION_UNLOCK (connection);
3112 /* only called from finalize(), removes all filters */
3114 purge_all_filters (GDBusConnection *connection)
3117 for (n = 0; n < connection->filters->len; n++)
3119 FilterData *data = connection->filters->pdata[n];
3120 if (data->user_data_free_func != NULL)
3121 data->user_data_free_func (data->user_data);
3127 * g_dbus_connection_remove_filter:
3128 * @connection: a #GDBusConnection
3129 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3136 g_dbus_connection_remove_filter (GDBusConnection *connection,
3140 FilterData *to_destroy;
3142 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3143 g_return_if_fail (check_initialized (connection));
3145 CONNECTION_LOCK (connection);
3147 for (n = 0; n < connection->filters->len; n++)
3149 FilterData *data = connection->filters->pdata[n];
3150 if (data->id == filter_id)
3152 g_ptr_array_remove_index (connection->filters, n);
3157 CONNECTION_UNLOCK (connection);
3159 /* do free without holding lock */
3160 if (to_destroy != NULL)
3162 if (to_destroy->user_data_free_func != NULL)
3163 to_destroy->user_data_free_func (to_destroy->user_data);
3164 g_free (to_destroy);
3168 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3172 /* ---------------------------------------------------------------------------------------------------- */
3178 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3179 gchar *interface_name;
3183 GArray *subscribers;
3188 GDBusSignalCallback callback;
3190 GDestroyNotify user_data_free_func;
3192 GMainContext *context;
3196 signal_data_free (SignalData *signal_data)
3198 g_free (signal_data->rule);
3199 g_free (signal_data->sender);
3200 g_free (signal_data->sender_unique_name);
3201 g_free (signal_data->interface_name);
3202 g_free (signal_data->member);
3203 g_free (signal_data->object_path);
3204 g_free (signal_data->arg0);
3205 g_array_free (signal_data->subscribers, TRUE);
3206 g_free (signal_data);
3210 args_to_rule (const gchar *sender,
3211 const gchar *interface_name,
3212 const gchar *member,
3213 const gchar *object_path,
3219 rule = g_string_new ("type='signal'");
3221 g_string_prepend_c (rule, '-');
3223 g_string_append_printf (rule, ",sender='%s'", sender);
3224 if (interface_name != NULL)
3225 g_string_append_printf (rule, ",interface='%s'", interface_name);
3227 g_string_append_printf (rule, ",member='%s'", member);
3228 if (object_path != NULL)
3229 g_string_append_printf (rule, ",path='%s'", object_path);
3231 g_string_append_printf (rule, ",arg0='%s'", arg0);
3233 return g_string_free (rule, FALSE);
3236 static guint _global_subscriber_id = 1;
3237 static guint _global_registration_id = 1;
3238 static guint _global_subtree_registration_id = 1;
3240 /* ---------------------------------------------------------------------------------------------------- */
3242 /* Called in a user thread, lock is held */
3244 add_match_rule (GDBusConnection *connection,
3245 const gchar *match_rule)
3248 GDBusMessage *message;
3250 if (match_rule[0] == '-')
3253 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3254 "/org/freedesktop/DBus", /* path */
3255 "org.freedesktop.DBus", /* interface */
3257 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3259 if (!g_dbus_connection_send_message_unlocked (connection,
3261 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3265 g_critical ("Error while sending AddMatch() message: %s", error->message);
3266 g_error_free (error);
3268 g_object_unref (message);
3271 /* ---------------------------------------------------------------------------------------------------- */
3273 /* Called in a user thread, lock is held */
3275 remove_match_rule (GDBusConnection *connection,
3276 const gchar *match_rule)
3279 GDBusMessage *message;
3281 if (match_rule[0] == '-')
3284 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3285 "/org/freedesktop/DBus", /* path */
3286 "org.freedesktop.DBus", /* interface */
3288 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3291 if (!g_dbus_connection_send_message_unlocked (connection,
3293 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3297 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3298 g_error_free (error);
3300 g_object_unref (message);
3303 /* ---------------------------------------------------------------------------------------------------- */
3306 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3308 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3309 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3310 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3311 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3312 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3315 /* ---------------------------------------------------------------------------------------------------- */
3318 * g_dbus_connection_signal_subscribe:
3319 * @connection: A #GDBusConnection.
3320 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3321 * or %NULL to listen from all senders.
3322 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3323 * match on all interfaces.
3324 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3325 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3326 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3327 * to match on all kinds of arguments.
3328 * @flags: Flags describing how to subscribe to the signal (currently unused).
3329 * @callback: Callback to invoke when there is a signal matching the requested data.
3330 * @user_data: User data to pass to @callback.
3331 * @user_data_free_func: (allow-none): Function to free @user_data with when
3332 * subscription is removed or %NULL.
3334 * Subscribes to signals on @connection and invokes @callback with a
3335 * whenever the signal is received. Note that @callback
3336 * will be invoked in the <link
3337 * linkend="g-main-context-push-thread-default">thread-default main
3338 * loop</link> of the thread you are calling this method from.
3340 * If @connection is not a message bus connection, @sender must be
3343 * If @sender is a well-known name note that @callback is invoked with
3344 * the unique name for the owner of @sender, not the well-known name
3345 * as one would expect. This is because the message bus rewrites the
3346 * name. As such, to avoid certain race conditions, users should be
3347 * tracking the name owner of the well-known name and use that when
3348 * processing the received signal.
3350 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3355 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3356 const gchar *sender,
3357 const gchar *interface_name,
3358 const gchar *member,
3359 const gchar *object_path,
3361 GDBusSignalFlags flags,
3362 GDBusSignalCallback callback,
3364 GDestroyNotify user_data_free_func)
3367 SignalData *signal_data;
3368 SignalSubscriber subscriber;
3369 GPtrArray *signal_data_array;
3370 const gchar *sender_unique_name;
3372 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3373 * an OOM condition. We might want to change that but that would involve making
3374 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3375 * handle that. And there's really no sensible way of handling this short of retrying
3376 * to add the match rule... and then there's the little thing that, hey, maybe there's
3377 * a reason the bus in an OOM condition.
3379 * Doable, but not really sure it's worth it...
3382 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3383 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3384 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3385 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3386 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3387 g_return_val_if_fail (callback != NULL, 0);
3388 g_return_val_if_fail (check_initialized (connection), 0);
3390 CONNECTION_LOCK (connection);
3392 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3393 * with a '-' character to prefix the rule (which will otherwise be
3396 * This allows us to hash the rule and do our lifecycle tracking in
3397 * the usual way, but the '-' prevents the match rule from ever
3398 * actually being send to the bus (either for add or remove).
3400 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3401 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3403 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3404 sender_unique_name = sender;
3406 sender_unique_name = "";
3408 subscriber.callback = callback;
3409 subscriber.user_data = user_data;
3410 subscriber.user_data_free_func = user_data_free_func;
3411 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3412 subscriber.context = g_main_context_ref_thread_default ();
3414 /* see if we've already have this rule */
3415 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3416 if (signal_data != NULL)
3418 g_array_append_val (signal_data->subscribers, subscriber);
3423 signal_data = g_new0 (SignalData, 1);
3424 signal_data->rule = rule;
3425 signal_data->sender = g_strdup (sender);
3426 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3427 signal_data->interface_name = g_strdup (interface_name);
3428 signal_data->member = g_strdup (member);
3429 signal_data->object_path = g_strdup (object_path);
3430 signal_data->arg0 = g_strdup (arg0);
3431 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3432 g_array_append_val (signal_data->subscribers, subscriber);
3434 g_hash_table_insert (connection->map_rule_to_signal_data,
3438 /* Add the match rule to the bus...
3440 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3441 * always send such messages to us.
3443 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3445 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3446 add_match_rule (connection, signal_data->rule);
3449 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3450 signal_data->sender_unique_name);
3451 if (signal_data_array == NULL)
3453 signal_data_array = g_ptr_array_new ();
3454 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3455 g_strdup (signal_data->sender_unique_name),
3458 g_ptr_array_add (signal_data_array, signal_data);
3461 g_hash_table_insert (connection->map_id_to_signal_data,
3462 GUINT_TO_POINTER (subscriber.id),
3465 CONNECTION_UNLOCK (connection);
3467 return subscriber.id;
3470 /* ---------------------------------------------------------------------------------------------------- */
3472 /* called in any thread */
3473 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3475 unsubscribe_id_internal (GDBusConnection *connection,
3476 guint subscription_id,
3477 GArray *out_removed_subscribers)
3479 SignalData *signal_data;
3480 GPtrArray *signal_data_array;
3483 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3484 GUINT_TO_POINTER (subscription_id));
3485 if (signal_data == NULL)
3487 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3491 for (n = 0; n < signal_data->subscribers->len; n++)
3493 SignalSubscriber *subscriber;
3495 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3496 if (subscriber->id != subscription_id)
3499 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3500 GUINT_TO_POINTER (subscription_id)));
3501 g_array_append_val (out_removed_subscribers, *subscriber);
3502 g_array_remove_index (signal_data->subscribers, n);
3504 if (signal_data->subscribers->len == 0)
3506 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3508 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3509 signal_data->sender_unique_name);
3510 g_warn_if_fail (signal_data_array != NULL);
3511 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3513 if (signal_data_array->len == 0)
3515 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3516 signal_data->sender_unique_name));
3519 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3520 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3522 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3523 if (!connection->closed && !connection->finalizing)
3524 remove_match_rule (connection, signal_data->rule);
3526 signal_data_free (signal_data);
3532 g_assert_not_reached ();
3539 * g_dbus_connection_signal_unsubscribe:
3540 * @connection: A #GDBusConnection.
3541 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3543 * Unsubscribes from signals.
3548 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3549 guint subscription_id)
3551 GArray *subscribers;
3554 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3555 g_return_if_fail (check_initialized (connection));
3557 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3559 CONNECTION_LOCK (connection);
3560 unsubscribe_id_internal (connection,
3563 CONNECTION_UNLOCK (connection);
3566 g_assert (subscribers->len == 0 || subscribers->len == 1);
3568 /* call GDestroyNotify without lock held */
3569 for (n = 0; n < subscribers->len; n++)
3571 SignalSubscriber *subscriber;
3572 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3573 call_destroy_notify (subscriber->context,
3574 subscriber->user_data_free_func,
3575 subscriber->user_data);
3576 g_main_context_unref (subscriber->context);
3579 g_array_free (subscribers, TRUE);
3582 /* ---------------------------------------------------------------------------------------------------- */
3586 guint subscription_id;
3587 GDBusSignalCallback callback;
3589 GDBusMessage *message;
3590 GDBusConnection *connection;
3591 const gchar *sender;
3593 const gchar *interface;
3594 const gchar *member;
3597 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3601 emit_signal_instance_in_idle_cb (gpointer data)
3603 SignalInstance *signal_instance = data;
3604 GVariant *parameters;
3605 gboolean has_subscription;
3607 parameters = g_dbus_message_get_body (signal_instance->message);
3608 if (parameters == NULL)
3610 parameters = g_variant_new ("()");
3611 g_variant_ref_sink (parameters);
3615 g_variant_ref_sink (parameters);
3619 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3620 signal_instance->subscription_id,
3621 signal_instance->sender,
3622 signal_instance->path,
3623 signal_instance->interface,
3624 signal_instance->member,
3625 g_variant_print (parameters, TRUE));
3628 /* Careful here, don't do the callback if we no longer has the subscription */
3629 CONNECTION_LOCK (signal_instance->connection);
3630 has_subscription = FALSE;
3631 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3632 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3633 has_subscription = TRUE;
3634 CONNECTION_UNLOCK (signal_instance->connection);
3636 if (has_subscription)
3637 signal_instance->callback (signal_instance->connection,
3638 signal_instance->sender,
3639 signal_instance->path,
3640 signal_instance->interface,
3641 signal_instance->member,
3643 signal_instance->user_data);
3645 g_variant_unref (parameters);
3651 signal_instance_free (SignalInstance *signal_instance)
3653 g_object_unref (signal_instance->message);
3654 g_object_unref (signal_instance->connection);
3655 g_free (signal_instance);
3658 /* called in GDBusWorker thread WITH lock held */
3660 schedule_callbacks (GDBusConnection *connection,
3661 GPtrArray *signal_data_array,
3662 GDBusMessage *message,
3663 const gchar *sender)
3666 const gchar *interface;
3667 const gchar *member;
3676 interface = g_dbus_message_get_interface (message);
3677 member = g_dbus_message_get_member (message);
3678 path = g_dbus_message_get_path (message);
3679 arg0 = g_dbus_message_get_arg0 (message);
3682 g_print ("In schedule_callbacks:\n"
3684 " interface = `%s'\n"
3695 /* TODO: if this is slow, then we can change signal_data_array into
3696 * map_object_path_to_signal_data_array or something.
3698 for (n = 0; n < signal_data_array->len; n++)
3700 SignalData *signal_data = signal_data_array->pdata[n];
3702 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3705 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3708 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3711 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3714 for (m = 0; m < signal_data->subscribers->len; m++)
3716 SignalSubscriber *subscriber;
3717 GSource *idle_source;
3718 SignalInstance *signal_instance;
3720 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3722 signal_instance = g_new0 (SignalInstance, 1);
3723 signal_instance->subscription_id = subscriber->id;
3724 signal_instance->callback = subscriber->callback;
3725 signal_instance->user_data = subscriber->user_data;
3726 signal_instance->message = g_object_ref (message);
3727 signal_instance->connection = g_object_ref (connection);
3728 signal_instance->sender = sender;
3729 signal_instance->path = path;
3730 signal_instance->interface = interface;
3731 signal_instance->member = member;
3733 idle_source = g_idle_source_new ();
3734 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3735 g_source_set_callback (idle_source,
3736 emit_signal_instance_in_idle_cb,
3738 (GDestroyNotify) signal_instance_free);
3739 g_source_attach (idle_source, subscriber->context);
3740 g_source_unref (idle_source);
3745 /* called in GDBusWorker thread with lock held */
3747 distribute_signals (GDBusConnection *connection,
3748 GDBusMessage *message)
3750 GPtrArray *signal_data_array;
3751 const gchar *sender;
3753 sender = g_dbus_message_get_sender (message);
3755 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3757 _g_dbus_debug_print_lock ();
3758 g_print ("========================================================================\n"
3759 "GDBus-debug:Signal:\n"
3760 " <<<< RECEIVED SIGNAL %s.%s\n"
3762 " sent by name %s\n",
3763 g_dbus_message_get_interface (message),
3764 g_dbus_message_get_member (message),
3765 g_dbus_message_get_path (message),
3766 sender != NULL ? sender : "(none)");
3767 _g_dbus_debug_print_unlock ();
3770 /* collect subscribers that match on sender */
3773 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3774 if (signal_data_array != NULL)
3775 schedule_callbacks (connection, signal_data_array, message, sender);
3778 /* collect subscribers not matching on sender */
3779 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3780 if (signal_data_array != NULL)
3781 schedule_callbacks (connection, signal_data_array, message, sender);
3784 /* ---------------------------------------------------------------------------------------------------- */
3786 /* only called from finalize(), removes all subscriptions */
3788 purge_all_signal_subscriptions (GDBusConnection *connection)
3790 GHashTableIter iter;
3793 GArray *subscribers;
3796 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3797 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3798 while (g_hash_table_iter_next (&iter, &key, NULL))
3800 guint subscription_id = GPOINTER_TO_UINT (key);
3801 g_array_append_val (ids, subscription_id);
3804 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3805 for (n = 0; n < ids->len; n++)
3807 guint subscription_id = g_array_index (ids, guint, n);
3808 unsubscribe_id_internal (connection,
3812 g_array_free (ids, TRUE);
3814 /* call GDestroyNotify without lock held */
3815 for (n = 0; n < subscribers->len; n++)
3817 SignalSubscriber *subscriber;
3818 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3819 call_destroy_notify (subscriber->context,
3820 subscriber->user_data_free_func,
3821 subscriber->user_data);
3822 g_main_context_unref (subscriber->context);
3825 g_array_free (subscribers, TRUE);
3828 /* ---------------------------------------------------------------------------------------------------- */
3830 static GDBusInterfaceVTable *
3831 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3833 /* Don't waste memory by copying padding - remember to update this
3834 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3836 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3840 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3845 /* ---------------------------------------------------------------------------------------------------- */
3847 static GDBusSubtreeVTable *
3848 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3850 /* Don't waste memory by copying padding - remember to update this
3851 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3853 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3857 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3862 /* ---------------------------------------------------------------------------------------------------- */
3864 struct ExportedObject
3867 GDBusConnection *connection;
3869 /* maps gchar* -> ExportedInterface* */
3870 GHashTable *map_if_name_to_ei;
3873 /* only called with lock held */
3875 exported_object_free (ExportedObject *eo)
3877 g_free (eo->object_path);
3878 g_hash_table_unref (eo->map_if_name_to_ei);
3887 gchar *interface_name;
3888 GDBusInterfaceVTable *vtable;
3889 GDBusInterfaceInfo *interface_info;
3891 GMainContext *context;
3893 GDestroyNotify user_data_free_func;
3894 } ExportedInterface;
3896 /* called with lock held */
3898 exported_interface_free (ExportedInterface *ei)
3900 g_dbus_interface_info_cache_release (ei->interface_info);
3901 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3903 call_destroy_notify (ei->context,
3904 ei->user_data_free_func,
3907 g_main_context_unref (ei->context);
3909 g_free (ei->interface_name);
3910 _g_dbus_interface_vtable_free (ei->vtable);
3914 /* ---------------------------------------------------------------------------------------------------- */
3916 /* Convenience function to check if @registration_id (if not zero) or
3917 * @subtree_registration_id (if not zero) has been unregistered. If
3918 * so, returns %TRUE.
3920 * May be called by any thread. Caller must *not* hold lock.
3923 has_object_been_unregistered (GDBusConnection *connection,
3924 guint registration_id,
3925 guint subtree_registration_id)
3929 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3933 CONNECTION_LOCK (connection);
3934 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3935 GUINT_TO_POINTER (registration_id)) == NULL)
3939 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3940 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3944 CONNECTION_UNLOCK (connection);
3949 /* ---------------------------------------------------------------------------------------------------- */
3953 GDBusConnection *connection;
3954 GDBusMessage *message;
3956 const gchar *property_name;
3957 const GDBusInterfaceVTable *vtable;
3958 GDBusInterfaceInfo *interface_info;
3959 const GDBusPropertyInfo *property_info;
3960 guint registration_id;
3961 guint subtree_registration_id;
3965 property_data_free (PropertyData *data)
3967 g_object_unref (data->connection);
3968 g_object_unref (data->message);
3972 /* called in thread where object was registered - no locks held */
3974 invoke_get_property_in_idle_cb (gpointer _data)
3976 PropertyData *data = _data;
3979 GDBusMessage *reply;
3981 if (has_object_been_unregistered (data->connection,
3982 data->registration_id,
3983 data->subtree_registration_id))
3985 reply = g_dbus_message_new_method_error (data->message,
3986 "org.freedesktop.DBus.Error.UnknownMethod",
3987 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
3988 g_dbus_message_get_path (data->message));
3989 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
3990 g_object_unref (reply);
3995 value = data->vtable->get_property (data->connection,
3996 g_dbus_message_get_sender (data->message),
3997 g_dbus_message_get_path (data->message),
3998 data->interface_info->name,
3999 data->property_name,
4006 g_assert_no_error (error);
4008 g_variant_take_ref (value);
4009 reply = g_dbus_message_new_method_reply (data->message);
4010 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4011 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4012 g_variant_unref (value);
4013 g_object_unref (reply);
4017 gchar *dbus_error_name;
4018 g_assert (error != NULL);
4019 dbus_error_name = g_dbus_error_encode_gerror (error);
4020 reply = g_dbus_message_new_method_error_literal (data->message,
4023 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4024 g_free (dbus_error_name);
4025 g_error_free (error);
4026 g_object_unref (reply);
4033 /* called in thread where object was registered - no locks held */
4035 invoke_set_property_in_idle_cb (gpointer _data)
4037 PropertyData *data = _data;
4039 GDBusMessage *reply;
4045 g_variant_get (g_dbus_message_get_body (data->message),
4051 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4052 * of the given value is wrong
4054 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4056 reply = g_dbus_message_new_method_error (data->message,
4057 "org.freedesktop.DBus.Error.InvalidArgs",
4058 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4059 data->property_info->name,
4060 data->property_info->signature,
4061 g_variant_get_type_string (value));
4065 if (!data->vtable->set_property (data->connection,
4066 g_dbus_message_get_sender (data->message),
4067 g_dbus_message_get_path (data->message),
4068 data->interface_info->name,
4069 data->property_name,
4074 gchar *dbus_error_name;
4075 g_assert (error != NULL);
4076 dbus_error_name = g_dbus_error_encode_gerror (error);
4077 reply = g_dbus_message_new_method_error_literal (data->message,
4080 g_free (dbus_error_name);
4081 g_error_free (error);
4085 reply = g_dbus_message_new_method_reply (data->message);
4089 g_assert (reply != NULL);
4090 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4091 g_object_unref (reply);
4092 g_variant_unref (value);
4097 /* called in any thread with connection's lock held */
4099 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4100 GDBusMessage *message,
4101 guint registration_id,
4102 guint subtree_registration_id,
4104 GDBusInterfaceInfo *interface_info,
4105 const GDBusInterfaceVTable *vtable,
4106 GMainContext *main_context,
4110 const char *interface_name;
4111 const char *property_name;
4112 const GDBusPropertyInfo *property_info;
4113 GSource *idle_source;
4114 PropertyData *property_data;
4115 GDBusMessage *reply;
4120 g_variant_get (g_dbus_message_get_body (message),
4125 g_variant_get (g_dbus_message_get_body (message),
4134 if (vtable == NULL || vtable->get_property == NULL)
4139 if (vtable == NULL || vtable->set_property == NULL)
4143 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4145 property_info = NULL;
4147 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4148 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4149 if (property_info == NULL)
4151 reply = g_dbus_message_new_method_error (message,
4152 "org.freedesktop.DBus.Error.InvalidArgs",
4153 _("No such property `%s'"),
4155 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4156 g_object_unref (reply);
4161 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4163 reply = g_dbus_message_new_method_error (message,
4164 "org.freedesktop.DBus.Error.InvalidArgs",
4165 _("Property `%s' is not readable"),
4167 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4168 g_object_unref (reply);
4172 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4174 reply = g_dbus_message_new_method_error (message,
4175 "org.freedesktop.DBus.Error.InvalidArgs",
4176 _("Property `%s' is not writable"),
4178 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4179 g_object_unref (reply);
4184 /* ok, got the property info - call user code in an idle handler */
4185 property_data = g_new0 (PropertyData, 1);
4186 property_data->connection = g_object_ref (connection);
4187 property_data->message = g_object_ref (message);
4188 property_data->user_data = user_data;
4189 property_data->property_name = property_name;
4190 property_data->vtable = vtable;
4191 property_data->interface_info = interface_info;
4192 property_data->property_info = property_info;
4193 property_data->registration_id = registration_id;
4194 property_data->subtree_registration_id = subtree_registration_id;
4196 idle_source = g_idle_source_new ();
4197 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4198 g_source_set_callback (idle_source,
4199 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4201 (GDestroyNotify) property_data_free);
4202 g_source_attach (idle_source, main_context);
4203 g_source_unref (idle_source);
4211 /* called in GDBusWorker thread with connection's lock held */
4213 handle_getset_property (GDBusConnection *connection,
4215 GDBusMessage *message,
4218 ExportedInterface *ei;
4220 const char *interface_name;
4221 const char *property_name;
4226 g_variant_get (g_dbus_message_get_body (message),
4231 g_variant_get (g_dbus_message_get_body (message),
4237 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4238 * no such interface registered
4240 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4243 GDBusMessage *reply;
4244 reply = g_dbus_message_new_method_error (message,
4245 "org.freedesktop.DBus.Error.InvalidArgs",
4246 _("No such interface `%s'"),
4248 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4249 g_object_unref (reply);
4254 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4267 /* ---------------------------------------------------------------------------------------------------- */
4271 GDBusConnection *connection;
4272 GDBusMessage *message;
4274 const GDBusInterfaceVTable *vtable;
4275 GDBusInterfaceInfo *interface_info;
4276 guint registration_id;
4277 guint subtree_registration_id;
4278 } PropertyGetAllData;
4281 property_get_all_data_free (PropertyData *data)
4283 g_object_unref (data->connection);
4284 g_object_unref (data->message);
4288 /* called in thread where object was registered - no locks held */
4290 invoke_get_all_properties_in_idle_cb (gpointer _data)
4292 PropertyGetAllData *data = _data;
4293 GVariantBuilder builder;
4294 GDBusMessage *reply;
4297 if (has_object_been_unregistered (data->connection,
4298 data->registration_id,
4299 data->subtree_registration_id))
4301 reply = g_dbus_message_new_method_error (data->message,
4302 "org.freedesktop.DBus.Error.UnknownMethod",
4303 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4304 g_dbus_message_get_path (data->message));
4305 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4306 g_object_unref (reply);
4310 /* TODO: Right now we never fail this call - we just omit values if
4311 * a get_property() call is failing.
4313 * We could fail the whole call if just a single get_property() call
4314 * returns an error. We need clarification in the D-Bus spec about this.
4316 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4317 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4318 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4320 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4323 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4326 value = data->vtable->get_property (data->connection,
4327 g_dbus_message_get_sender (data->message),
4328 g_dbus_message_get_path (data->message),
4329 data->interface_info->name,
4330 property_info->name,
4337 g_variant_take_ref (value);
4338 g_variant_builder_add (&builder,
4340 property_info->name,
4342 g_variant_unref (value);
4344 g_variant_builder_close (&builder);
4346 reply = g_dbus_message_new_method_reply (data->message);
4347 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4348 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4349 g_object_unref (reply);
4355 /* called in any thread with connection's lock held */
4357 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4358 GDBusMessage *message,
4359 guint registration_id,
4360 guint subtree_registration_id,
4361 GDBusInterfaceInfo *interface_info,
4362 const GDBusInterfaceVTable *vtable,
4363 GMainContext *main_context,
4367 const char *interface_name;
4368 GSource *idle_source;
4369 PropertyGetAllData *property_get_all_data;
4373 g_variant_get (g_dbus_message_get_body (message),
4377 if (vtable == NULL || vtable->get_property == NULL)
4380 /* ok, got the property info - call user in an idle handler */
4381 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4382 property_get_all_data->connection = g_object_ref (connection);
4383 property_get_all_data->message = g_object_ref (message);
4384 property_get_all_data->user_data = user_data;
4385 property_get_all_data->vtable = vtable;
4386 property_get_all_data->interface_info = interface_info;
4387 property_get_all_data->registration_id = registration_id;
4388 property_get_all_data->subtree_registration_id = subtree_registration_id;
4390 idle_source = g_idle_source_new ();
4391 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4392 g_source_set_callback (idle_source,
4393 invoke_get_all_properties_in_idle_cb,
4394 property_get_all_data,
4395 (GDestroyNotify) property_get_all_data_free);
4396 g_source_attach (idle_source, main_context);
4397 g_source_unref (idle_source);
4405 /* called in GDBusWorker thread with connection's lock held */
4407 handle_get_all_properties (GDBusConnection *connection,
4409 GDBusMessage *message)
4411 ExportedInterface *ei;
4413 const char *interface_name;
4417 g_variant_get (g_dbus_message_get_body (message),
4421 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4422 * no such interface registered
4424 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4427 GDBusMessage *reply;
4428 reply = g_dbus_message_new_method_error (message,
4429 "org.freedesktop.DBus.Error.InvalidArgs",
4430 _("No such interface"),
4432 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4433 g_object_unref (reply);
4438 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4450 /* ---------------------------------------------------------------------------------------------------- */
4452 static const gchar introspect_header[] =
4453 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4454 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4455 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4458 static const gchar introspect_tail[] =
4461 static const gchar introspect_properties_interface[] =
4462 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4463 " <method name=\"Get\">\n"
4464 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4465 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4466 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4468 " <method name=\"GetAll\">\n"
4469 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4470 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4472 " <method name=\"Set\">\n"
4473 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4474 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4475 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4477 " <signal name=\"PropertiesChanged\">\n"
4478 " <arg type=\"s\" name=\"interface_name\"/>\n"
4479 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4480 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4484 static const gchar introspect_introspectable_interface[] =
4485 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4486 " <method name=\"Introspect\">\n"
4487 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4490 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4491 " <method name=\"Ping\"/>\n"
4492 " <method name=\"GetMachineId\">\n"
4493 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4498 introspect_append_header (GString *s)
4500 g_string_append (s, introspect_header);
4504 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4506 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4512 begin = object_path + path_len;
4513 end = strchr (begin, '/');
4515 s = g_strndup (begin, end - begin);
4517 s = g_strdup (begin);
4519 if (g_hash_table_lookup (set, s) == NULL)
4520 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4526 /* TODO: we want a nicer public interface for this */
4527 /* called in any thread with connection's lock held */
4529 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4534 GHashTableIter hash_iter;
4535 const gchar *object_path;
4541 CONNECTION_ENSURE_LOCK (connection);
4543 path_len = strlen (path);
4547 set = g_hash_table_new (g_str_hash, g_str_equal);
4549 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4550 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4551 maybe_add_path (path, path_len, object_path, set);
4553 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4554 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4555 maybe_add_path (path, path_len, object_path, set);
4557 p = g_ptr_array_new ();
4558 keys = g_hash_table_get_keys (set);
4559 for (l = keys; l != NULL; l = l->next)
4560 g_ptr_array_add (p, l->data);
4561 g_hash_table_unref (set);
4564 g_ptr_array_add (p, NULL);
4565 ret = (gchar **) g_ptr_array_free (p, FALSE);
4569 /* called in any thread with connection's lock not held */
4571 g_dbus_connection_list_registered (GDBusConnection *connection,
4575 CONNECTION_LOCK (connection);
4576 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4577 CONNECTION_UNLOCK (connection);
4581 /* called in GDBusWorker thread with connection's lock held */
4583 handle_introspect (GDBusConnection *connection,
4585 GDBusMessage *message)
4589 GDBusMessage *reply;
4590 GHashTableIter hash_iter;
4591 ExportedInterface *ei;
4594 /* first the header with the standard interfaces */
4595 s = g_string_sized_new (sizeof (introspect_header) +
4596 sizeof (introspect_properties_interface) +
4597 sizeof (introspect_introspectable_interface) +
4598 sizeof (introspect_tail));
4599 introspect_append_header (s);
4600 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4601 "org.freedesktop.DBus.Properties"))
4602 g_string_append (s, introspect_properties_interface);
4604 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4605 "org.freedesktop.DBus.Introspectable"))
4606 g_string_append (s, introspect_introspectable_interface);
4608 /* then include the registered interfaces */
4609 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4610 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4611 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4613 /* finally include nodes registered below us */
4614 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4615 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4616 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4617 g_strfreev (registered);
4618 g_string_append (s, introspect_tail);
4620 reply = g_dbus_message_new_method_reply (message);
4621 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4622 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4623 g_object_unref (reply);
4624 g_string_free (s, TRUE);
4629 /* called in thread where object was registered - no locks held */
4631 call_in_idle_cb (gpointer user_data)
4633 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4634 GDBusInterfaceVTable *vtable;
4635 guint registration_id;
4636 guint subtree_registration_id;
4638 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4639 g_assert (vtable != NULL && vtable->method_call != NULL);
4641 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4642 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4644 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4646 subtree_registration_id))
4648 GDBusMessage *reply;
4649 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4650 "org.freedesktop.DBus.Error.UnknownMethod",
4651 _("No such interface `%s' on object at path %s"),
4652 g_dbus_method_invocation_get_interface_name (invocation),
4653 g_dbus_method_invocation_get_object_path (invocation));
4654 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4655 g_object_unref (reply);
4659 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4660 g_dbus_method_invocation_get_sender (invocation),
4661 g_dbus_method_invocation_get_object_path (invocation),
4662 g_dbus_method_invocation_get_interface_name (invocation),
4663 g_dbus_method_invocation_get_method_name (invocation),
4664 g_dbus_method_invocation_get_parameters (invocation),
4665 g_object_ref (invocation),
4666 g_dbus_method_invocation_get_user_data (invocation));
4672 /* called in GDBusWorker thread with connection's lock held */
4674 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4675 GDBusMessage *message,
4676 guint registration_id,
4677 guint subtree_registration_id,
4678 GDBusInterfaceInfo *interface_info,
4679 const GDBusInterfaceVTable *vtable,
4680 GMainContext *main_context,
4683 GDBusMethodInvocation *invocation;
4684 const GDBusMethodInfo *method_info;
4685 GDBusMessage *reply;
4686 GVariant *parameters;
4687 GSource *idle_source;
4689 GVariantType *in_type;
4693 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4694 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4696 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4697 * error to the caller
4699 if (method_info == NULL)
4701 reply = g_dbus_message_new_method_error (message,
4702 "org.freedesktop.DBus.Error.UnknownMethod",
4703 _("No such method `%s'"),
4704 g_dbus_message_get_member (message));
4705 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4706 g_object_unref (reply);
4711 parameters = g_dbus_message_get_body (message);
4712 if (parameters == NULL)
4714 parameters = g_variant_new ("()");
4715 g_variant_ref_sink (parameters);
4719 g_variant_ref (parameters);
4722 /* Check that the incoming args are of the right type - if they are not, return
4723 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4725 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4726 if (!g_variant_is_of_type (parameters, in_type))
4730 type_string = g_variant_type_dup_string (in_type);
4732 reply = g_dbus_message_new_method_error (message,
4733 "org.freedesktop.DBus.Error.InvalidArgs",
4734 _("Type of message, `%s', does not match expected type `%s'"),
4735 g_variant_get_type_string (parameters),
4737 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4738 g_variant_type_free (in_type);
4739 g_variant_unref (parameters);
4740 g_object_unref (reply);
4741 g_free (type_string);
4745 g_variant_type_free (in_type);
4747 /* schedule the call in idle */
4748 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4749 g_dbus_message_get_path (message),
4750 g_dbus_message_get_interface (message),
4751 g_dbus_message_get_member (message),
4757 g_variant_unref (parameters);
4759 /* TODO: would be nicer with a real MethodData like we already
4760 * have PropertyData and PropertyGetAllData... */
4761 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4762 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4763 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4765 idle_source = g_idle_source_new ();
4766 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4767 g_source_set_callback (idle_source,
4771 g_source_attach (idle_source, main_context);
4772 g_source_unref (idle_source);
4780 /* ---------------------------------------------------------------------------------------------------- */
4782 /* called in GDBusWorker thread with connection's lock held */
4784 obj_message_func (GDBusConnection *connection,
4786 GDBusMessage *message)
4788 const gchar *interface_name;
4789 const gchar *member;
4790 const gchar *signature;
4795 interface_name = g_dbus_message_get_interface (message);
4796 member = g_dbus_message_get_member (message);
4797 signature = g_dbus_message_get_signature (message);
4799 /* see if we have an interface for handling this call */
4800 if (interface_name != NULL)
4802 ExportedInterface *ei;
4803 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4806 /* we do - invoke the handler in idle in the right thread */
4808 /* handle no vtable or handler being present */
4809 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4812 handled = validate_and_maybe_schedule_method_call (connection,
4824 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4825 g_strcmp0 (member, "Introspect") == 0 &&
4826 g_strcmp0 (signature, "") == 0)
4828 handled = handle_introspect (connection, eo, message);
4831 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4832 g_strcmp0 (member, "Get") == 0 &&
4833 g_strcmp0 (signature, "ss") == 0)
4835 handled = handle_getset_property (connection, eo, message, TRUE);
4838 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4839 g_strcmp0 (member, "Set") == 0 &&
4840 g_strcmp0 (signature, "ssv") == 0)
4842 handled = handle_getset_property (connection, eo, message, FALSE);
4845 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4846 g_strcmp0 (member, "GetAll") == 0 &&
4847 g_strcmp0 (signature, "s") == 0)
4849 handled = handle_get_all_properties (connection, eo, message);
4858 * g_dbus_connection_register_object:
4859 * @connection: A #GDBusConnection.
4860 * @object_path: The object path to register at.
4861 * @interface_info: Introspection data for the interface.
4862 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4863 * @user_data: (allow-none): Data to pass to functions in @vtable.
4864 * @user_data_free_func: Function to call when the object path is unregistered.
4865 * @error: Return location for error or %NULL.
4867 * Registers callbacks for exported objects at @object_path with the
4868 * D-Bus interface that is described in @interface_info.
4870 * Calls to functions in @vtable (and @user_data_free_func) will
4871 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4872 * loop</link> of the thread you are calling this method from.
4874 * Note that all #GVariant values passed to functions in @vtable will match
4875 * the signature given in @interface_info - if a remote caller passes
4876 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4877 * is returned to the remote caller.
4879 * Additionally, if the remote caller attempts to invoke methods or
4880 * access properties not mentioned in @interface_info the
4881 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4882 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4883 * are returned to the caller.
4885 * It is considered a programming error if the
4886 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4887 * #GVariant of incorrect type.
4889 * If an existing callback is already registered at @object_path and
4890 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4892 * GDBus automatically implements the standard D-Bus interfaces
4893 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4894 * and org.freedesktop.Peer, so you don't have to implement those for
4895 * the objects you export. You <emphasis>can</emphasis> implement
4896 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4897 * and setting of properties asynchronously.
4899 * Note that the reference count on @interface_info will be
4900 * incremented by 1 (unless allocated statically, e.g. if the
4901 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4902 * as the object is exported. Also note that @vtable will be copied.
4904 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4906 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4907 * that can be used with g_dbus_connection_unregister_object() .
4912 g_dbus_connection_register_object (GDBusConnection *connection,
4913 const gchar *object_path,
4914 GDBusInterfaceInfo *interface_info,
4915 const GDBusInterfaceVTable *vtable,
4917 GDestroyNotify user_data_free_func,
4921 ExportedInterface *ei;
4924 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4925 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4926 g_return_val_if_fail (interface_info != NULL, 0);
4927 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4928 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4929 g_return_val_if_fail (check_initialized (connection), 0);
4933 CONNECTION_LOCK (connection);
4935 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4938 eo = g_new0 (ExportedObject, 1);
4939 eo->object_path = g_strdup (object_path);
4940 eo->connection = connection;
4941 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4944 (GDestroyNotify) exported_interface_free);
4945 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4948 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
4954 _("An object is already exported for the interface %s at %s"),
4955 interface_info->name,
4960 ei = g_new0 (ExportedInterface, 1);
4961 ei->id = _global_registration_id++; /* TODO: overflow etc. */
4963 ei->user_data = user_data;
4964 ei->user_data_free_func = user_data_free_func;
4965 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
4966 ei->interface_info = g_dbus_interface_info_ref (interface_info);
4967 g_dbus_interface_info_cache_build (ei->interface_info);
4968 ei->interface_name = g_strdup (interface_info->name);
4969 ei->context = g_main_context_ref_thread_default ();
4971 g_hash_table_insert (eo->map_if_name_to_ei,
4972 (gpointer) ei->interface_name,
4974 g_hash_table_insert (connection->map_id_to_ei,
4975 GUINT_TO_POINTER (ei->id),
4981 CONNECTION_UNLOCK (connection);
4987 * g_dbus_connection_unregister_object:
4988 * @connection: A #GDBusConnection.
4989 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
4991 * Unregisters an object.
4993 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
4998 g_dbus_connection_unregister_object (GDBusConnection *connection,
4999 guint registration_id)
5001 ExportedInterface *ei;
5005 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5006 g_return_val_if_fail (check_initialized (connection), FALSE);
5010 CONNECTION_LOCK (connection);
5012 ei = g_hash_table_lookup (connection->map_id_to_ei,
5013 GUINT_TO_POINTER (registration_id));
5019 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5020 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5021 /* unregister object path if we have no more exported interfaces */
5022 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5023 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5029 CONNECTION_UNLOCK (connection);
5034 /* ---------------------------------------------------------------------------------------------------- */
5037 * g_dbus_connection_emit_signal:
5038 * @connection: A #GDBusConnection.
5039 * @destination_bus_name: (allow-none): The unique bus name for the destination
5040 * for the signal or %NULL to emit to all listeners.
5041 * @object_path: Path of remote object.
5042 * @interface_name: D-Bus interface to emit a signal on.
5043 * @signal_name: The name of the signal to emit.
5044 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5045 * or %NULL if not passing parameters.
5046 * @error: Return location for error or %NULL.
5050 * If the parameters GVariant is floating, it is consumed.
5052 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5054 * Returns: %TRUE unless @error is set.
5059 g_dbus_connection_emit_signal (GDBusConnection *connection,
5060 const gchar *destination_bus_name,
5061 const gchar *object_path,
5062 const gchar *interface_name,
5063 const gchar *signal_name,
5064 GVariant *parameters,
5067 GDBusMessage *message;
5073 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5074 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5075 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5076 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5077 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5078 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5079 g_return_val_if_fail (check_initialized (connection), FALSE);
5081 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5083 _g_dbus_debug_print_lock ();
5084 g_print ("========================================================================\n"
5085 "GDBus-debug:Emission:\n"
5086 " >>>> SIGNAL EMISSION %s.%s()\n"
5088 " destination %s\n",
5089 interface_name, signal_name,
5091 destination_bus_name != NULL ? destination_bus_name : "(none)");
5092 _g_dbus_debug_print_unlock ();
5095 message = g_dbus_message_new_signal (object_path,
5099 if (destination_bus_name != NULL)
5100 g_dbus_message_set_header (message,
5101 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5102 g_variant_new_string (destination_bus_name));
5104 if (parameters != NULL)
5105 g_dbus_message_set_body (message, parameters);
5107 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5108 g_object_unref (message);
5114 add_call_flags (GDBusMessage *message,
5115 GDBusCallFlags flags)
5117 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5118 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5122 decode_method_reply (GDBusMessage *reply,
5123 const gchar *method_name,
5124 const GVariantType *reply_type,
5125 GUnixFDList **out_fd_list,
5131 switch (g_dbus_message_get_message_type (reply))
5133 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5134 result = g_dbus_message_get_body (reply);
5137 result = g_variant_new ("()");
5138 g_variant_ref_sink (result);
5142 g_variant_ref (result);
5145 if (!g_variant_is_of_type (result, reply_type))
5147 gchar *type_string = g_variant_type_dup_string (reply_type);
5151 G_IO_ERROR_INVALID_ARGUMENT,
5152 _("Method `%s' returned type `%s', but expected `%s'"),
5153 method_name, g_variant_get_type_string (result), type_string);
5155 g_variant_unref (result);
5156 g_free (type_string);
5163 if (out_fd_list != NULL)
5165 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5166 if (*out_fd_list != NULL)
5167 g_object_ref (*out_fd_list);
5173 case G_DBUS_MESSAGE_TYPE_ERROR:
5174 g_dbus_message_to_gerror (reply, error);
5178 g_assert_not_reached ();
5188 GSimpleAsyncResult *simple;
5189 GVariantType *reply_type;
5190 gchar *method_name; /* for error message */
5194 GUnixFDList *fd_list;
5198 call_state_free (CallState *state)
5200 g_variant_type_free (state->reply_type);
5201 g_free (state->method_name);
5203 if (state->value != NULL)
5204 g_variant_unref (state->value);
5205 if (state->fd_list != NULL)
5206 g_object_unref (state->fd_list);
5207 g_slice_free (CallState, state);
5210 /* called in any thread, with the connection's lock not held */
5212 g_dbus_connection_call_done (GObject *source,
5213 GAsyncResult *result,
5216 GSimpleAsyncResult *simple;
5217 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5218 CallState *state = user_data;
5220 GDBusMessage *reply;
5223 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5227 if (G_UNLIKELY (_g_dbus_debug_call ()))
5229 _g_dbus_debug_print_lock ();
5230 g_print ("========================================================================\n"
5231 "GDBus-debug:Call:\n"
5232 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5238 g_print ("SUCCESS\n");
5242 g_print ("FAILED: %s\n",
5245 _g_dbus_debug_print_unlock ();
5249 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5251 simple = state->simple; /* why? because state is freed before we unref simple.. */
5254 g_simple_async_result_take_error (state->simple, error);
5255 g_simple_async_result_complete (state->simple);
5256 call_state_free (state);
5260 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5261 g_simple_async_result_complete (state->simple);
5262 g_object_unref (reply);
5264 g_object_unref (simple);
5267 /* called in any thread, with the connection's lock not held */
5269 g_dbus_connection_call_internal (GDBusConnection *connection,
5270 const gchar *bus_name,
5271 const gchar *object_path,
5272 const gchar *interface_name,
5273 const gchar *method_name,
5274 GVariant *parameters,
5275 const GVariantType *reply_type,
5276 GDBusCallFlags flags,
5278 GUnixFDList *fd_list,
5279 GCancellable *cancellable,
5280 GAsyncReadyCallback callback,
5283 GDBusMessage *message;
5286 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5287 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5288 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5289 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5290 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5291 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5292 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5293 g_return_if_fail (check_initialized (connection));
5295 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5297 g_return_if_fail (fd_list == NULL);
5300 state = g_slice_new0 (CallState);
5301 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5302 callback, user_data,
5303 g_dbus_connection_call_internal);
5304 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5306 if (reply_type == NULL)
5307 reply_type = G_VARIANT_TYPE_ANY;
5309 state->reply_type = g_variant_type_copy (reply_type);
5311 message = g_dbus_message_new_method_call (bus_name,
5315 add_call_flags (message, flags);
5316 if (parameters != NULL)
5317 g_dbus_message_set_body (message, parameters);
5320 if (fd_list != NULL)
5321 g_dbus_message_set_unix_fd_list (message, fd_list);
5324 g_dbus_connection_send_message_with_reply (connection,
5326 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5330 g_dbus_connection_call_done,
5333 if (G_UNLIKELY (_g_dbus_debug_call ()))
5335 _g_dbus_debug_print_lock ();
5336 g_print ("========================================================================\n"
5337 "GDBus-debug:Call:\n"
5338 " >>>> ASYNC %s.%s()\n"
5340 " owned by name %s (serial %d)\n",
5344 bus_name != NULL ? bus_name : "(none)",
5346 _g_dbus_debug_print_unlock ();
5349 if (message != NULL)
5350 g_object_unref (message);
5353 /* called in any thread, with the connection's lock not held */
5355 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5356 GUnixFDList **out_fd_list,
5360 GSimpleAsyncResult *simple;
5363 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5364 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5365 g_dbus_connection_call_internal), NULL);
5366 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5368 simple = G_SIMPLE_ASYNC_RESULT (res);
5370 if (g_simple_async_result_propagate_error (simple, error))
5373 state = g_simple_async_result_get_op_res_gpointer (simple);
5374 if (out_fd_list != NULL)
5375 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5376 return g_variant_ref (state->value);
5379 /* called in any user thread, with the connection's lock not held */
5381 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5382 const gchar *bus_name,
5383 const gchar *object_path,
5384 const gchar *interface_name,
5385 const gchar *method_name,
5386 GVariant *parameters,
5387 const GVariantType *reply_type,
5388 GDBusCallFlags flags,
5390 GUnixFDList *fd_list,
5391 GUnixFDList **out_fd_list,
5392 GCancellable *cancellable,
5395 GDBusMessage *message;
5396 GDBusMessage *reply;
5398 GError *local_error;
5399 GDBusSendMessageFlags send_flags;
5405 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5406 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5407 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5408 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5409 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5410 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5411 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5413 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5415 g_return_val_if_fail (fd_list == NULL, NULL);
5417 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5419 if (!(flags & CALL_FLAGS_INITIALIZING))
5420 g_return_val_if_fail (check_initialized (connection), FALSE);
5422 if (reply_type == NULL)
5423 reply_type = G_VARIANT_TYPE_ANY;
5425 message = g_dbus_message_new_method_call (bus_name,
5429 add_call_flags (message, flags);
5430 if (parameters != NULL)
5431 g_dbus_message_set_body (message, parameters);
5434 if (fd_list != NULL)
5435 g_dbus_message_set_unix_fd_list (message, fd_list);
5438 if (G_UNLIKELY (_g_dbus_debug_call ()))
5440 _g_dbus_debug_print_lock ();
5441 g_print ("========================================================================\n"
5442 "GDBus-debug:Call:\n"
5443 " >>>> SYNC %s.%s()\n"
5445 " owned by name %s\n",
5449 bus_name != NULL ? bus_name : "(none)");
5450 _g_dbus_debug_print_unlock ();
5455 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5457 /* translate from one flavour of flags to another... */
5458 if (flags & CALL_FLAGS_INITIALIZING)
5459 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5461 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5465 NULL, /* volatile guint32 *out_serial */
5469 if (G_UNLIKELY (_g_dbus_debug_call ()))
5471 _g_dbus_debug_print_lock ();
5472 g_print ("========================================================================\n"
5473 "GDBus-debug:Call:\n"
5474 " <<<< SYNC COMPLETE %s.%s()\n"
5480 g_print ("SUCCESS\n");
5484 g_print ("FAILED: %s\n",
5485 local_error->message);
5487 _g_dbus_debug_print_unlock ();
5493 *error = local_error;
5495 g_error_free (local_error);
5499 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5502 if (message != NULL)
5503 g_object_unref (message);
5505 g_object_unref (reply);
5510 /* ---------------------------------------------------------------------------------------------------- */
5513 * g_dbus_connection_call:
5514 * @connection: A #GDBusConnection.
5515 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5516 * @connection is not a message bus connection.
5517 * @object_path: Path of remote object.
5518 * @interface_name: D-Bus interface to invoke method on.
5519 * @method_name: The name of the method to invoke.
5520 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5521 * or %NULL if not passing parameters.
5522 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5523 * @flags: Flags from the #GDBusCallFlags enumeration.
5524 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5525 * timeout or %G_MAXINT for no timeout.
5526 * @cancellable: A #GCancellable or %NULL.
5527 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5528 * satisfied or %NULL if you don't * care about the result of the
5529 * method invocation.
5530 * @user_data: The data to pass to @callback.
5532 * Asynchronously invokes the @method_name method on the
5533 * @interface_name D-Bus interface on the remote object at
5534 * @object_path owned by @bus_name.
5536 * If @connection is closed then the operation will fail with
5537 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5538 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5539 * not compatible with the D-Bus protocol, the operation fails with
5540 * %G_IO_ERROR_INVALID_ARGUMENT.
5542 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5543 * error will be raised if it does not match. Said another way, if you give a @reply_type
5544 * then any non-%NULL return value will be of this type.
5546 * If the @parameters #GVariant is floating, it is consumed. This allows
5547 * convenient 'inline' use of g_variant_new(), e.g.:
5549 * g_dbus_connection_call (connection,
5550 * "org.freedesktop.StringThings",
5551 * "/org/freedesktop/StringThings",
5552 * "org.freedesktop.StringThings",
5554 * g_variant_new ("(ss)",
5558 * G_DBUS_CALL_FLAGS_NONE,
5561 * (GAsyncReadyCallback) two_strings_done,
5565 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5566 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5567 * of the thread you are calling this method from. You can then call
5568 * g_dbus_connection_call_finish() to get the result of the operation.
5569 * See g_dbus_connection_call_sync() for the synchronous version of this
5575 g_dbus_connection_call (GDBusConnection *connection,
5576 const gchar *bus_name,
5577 const gchar *object_path,
5578 const gchar *interface_name,
5579 const gchar *method_name,
5580 GVariant *parameters,
5581 const GVariantType *reply_type,
5582 GDBusCallFlags flags,
5584 GCancellable *cancellable,
5585 GAsyncReadyCallback callback,
5588 g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, cancellable, callback, user_data);
5592 * g_dbus_connection_call_finish:
5593 * @connection: A #GDBusConnection.
5594 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5595 * @error: Return location for error or %NULL.
5597 * Finishes an operation started with g_dbus_connection_call().
5599 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5600 * return values. Free with g_variant_unref().
5605 g_dbus_connection_call_finish (GDBusConnection *connection,
5609 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5613 * g_dbus_connection_call_sync:
5614 * @connection: A #GDBusConnection.
5615 * @bus_name: A unique or well-known bus name.
5616 * @object_path: Path of remote object.
5617 * @interface_name: D-Bus interface to invoke method on.
5618 * @method_name: The name of the method to invoke.
5619 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5620 * or %NULL if not passing parameters.
5621 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5622 * @flags: Flags from the #GDBusCallFlags enumeration.
5623 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5624 * timeout or %G_MAXINT for no timeout.
5625 * @cancellable: A #GCancellable or %NULL.
5626 * @error: Return location for error or %NULL.
5628 * Synchronously invokes the @method_name method on the
5629 * @interface_name D-Bus interface on the remote object at
5630 * @object_path owned by @bus_name.
5632 * If @connection is closed then the operation will fail with
5633 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5634 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5635 * contains a value not compatible with the D-Bus protocol, the operation
5636 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5638 * If @reply_type is non-%NULL then the reply will be checked for having
5639 * this type and an error will be raised if it does not match. Said
5640 * another way, if you give a @reply_type then any non-%NULL return
5641 * value will be of this type.
5643 * If the @parameters #GVariant is floating, it is consumed.
5644 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5646 * g_dbus_connection_call_sync (connection,
5647 * "org.freedesktop.StringThings",
5648 * "/org/freedesktop/StringThings",
5649 * "org.freedesktop.StringThings",
5651 * g_variant_new ("(ss)",
5655 * G_DBUS_CALL_FLAGS_NONE,
5661 * The calling thread is blocked until a reply is received. See
5662 * g_dbus_connection_call() for the asynchronous version of
5665 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5666 * return values. Free with g_variant_unref().
5671 g_dbus_connection_call_sync (GDBusConnection *connection,
5672 const gchar *bus_name,
5673 const gchar *object_path,
5674 const gchar *interface_name,
5675 const gchar *method_name,
5676 GVariant *parameters,
5677 const GVariantType *reply_type,
5678 GDBusCallFlags flags,
5680 GCancellable *cancellable,
5683 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, NULL, NULL, cancellable, error);
5686 /* ---------------------------------------------------------------------------------------------------- */
5691 * g_dbus_connection_call_with_unix_fd_list:
5692 * @connection: A #GDBusConnection.
5693 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5694 * @connection is not a message bus connection.
5695 * @object_path: Path of remote object.
5696 * @interface_name: D-Bus interface to invoke method on.
5697 * @method_name: The name of the method to invoke.
5698 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5699 * or %NULL if not passing parameters.
5700 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5701 * @flags: Flags from the #GDBusCallFlags enumeration.
5702 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5703 * timeout or %G_MAXINT for no timeout.
5704 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5705 * @cancellable: A #GCancellable or %NULL.
5706 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5707 * satisfied or %NULL if you don't * care about the result of the
5708 * method invocation.
5709 * @user_data: The data to pass to @callback.
5711 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5713 * This method is only available on UNIX.
5718 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5719 const gchar *bus_name,
5720 const gchar *object_path,
5721 const gchar *interface_name,
5722 const gchar *method_name,
5723 GVariant *parameters,
5724 const GVariantType *reply_type,
5725 GDBusCallFlags flags,
5727 GUnixFDList *fd_list,
5728 GCancellable *cancellable,
5729 GAsyncReadyCallback callback,
5732 g_dbus_connection_call_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, cancellable, callback, user_data);
5736 * g_dbus_connection_call_with_unix_fd_list_finish:
5737 * @connection: A #GDBusConnection.
5738 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5739 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5740 * @error: Return location for error or %NULL.
5742 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5744 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5745 * return values. Free with g_variant_unref().
5750 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5751 GUnixFDList **out_fd_list,
5755 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5759 * g_dbus_connection_call_with_unix_fd_list_sync:
5760 * @connection: A #GDBusConnection.
5761 * @bus_name: A unique or well-known bus name.
5762 * @object_path: Path of remote object.
5763 * @interface_name: D-Bus interface to invoke method on.
5764 * @method_name: The name of the method to invoke.
5765 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5766 * or %NULL if not passing parameters.
5767 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5768 * @flags: Flags from the #GDBusCallFlags enumeration.
5769 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5770 * timeout or %G_MAXINT for no timeout.
5771 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5772 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5773 * @cancellable: A #GCancellable or %NULL.
5774 * @error: Return location for error or %NULL.
5776 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5778 * This method is only available on UNIX.
5780 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5781 * return values. Free with g_variant_unref().
5786 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5787 const gchar *bus_name,
5788 const gchar *object_path,
5789 const gchar *interface_name,
5790 const gchar *method_name,
5791 GVariant *parameters,
5792 const GVariantType *reply_type,
5793 GDBusCallFlags flags,
5795 GUnixFDList *fd_list,
5796 GUnixFDList **out_fd_list,
5797 GCancellable *cancellable,
5800 return g_dbus_connection_call_sync_internal (connection, bus_name, object_path, interface_name, method_name, parameters, reply_type, flags, timeout_msec, fd_list, out_fd_list, cancellable, error);
5803 #endif /* G_OS_UNIX */
5805 /* ---------------------------------------------------------------------------------------------------- */
5807 struct ExportedSubtree
5811 GDBusConnection *connection;
5812 GDBusSubtreeVTable *vtable;
5813 GDBusSubtreeFlags flags;
5815 GMainContext *context;
5817 GDestroyNotify user_data_free_func;
5821 exported_subtree_free (ExportedSubtree *es)
5823 call_destroy_notify (es->context,
5824 es->user_data_free_func,
5827 g_main_context_unref (es->context);
5829 _g_dbus_subtree_vtable_free (es->vtable);
5830 g_free (es->object_path);
5834 /* called without lock held in the thread where the caller registered
5838 handle_subtree_introspect (GDBusConnection *connection,
5839 ExportedSubtree *es,
5840 GDBusMessage *message)
5844 GDBusMessage *reply;
5847 const gchar *sender;
5848 const gchar *requested_object_path;
5849 const gchar *requested_node;
5850 GDBusInterfaceInfo **interfaces;
5852 gchar **subnode_paths;
5853 gboolean has_properties_interface;
5854 gboolean has_introspectable_interface;
5858 requested_object_path = g_dbus_message_get_path (message);
5859 sender = g_dbus_message_get_sender (message);
5860 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5862 s = g_string_new (NULL);
5863 introspect_append_header (s);
5865 /* Strictly we don't need the children in dynamic mode, but we avoid the
5866 * conditionals to preserve code clarity
5868 children = es->vtable->enumerate (es->connection,
5875 requested_node = strrchr (requested_object_path, '/') + 1;
5877 /* Assert existence of object if we are not dynamic */
5878 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5879 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5884 requested_node = NULL;
5887 interfaces = es->vtable->introspect (es->connection,
5892 if (interfaces != NULL)
5894 has_properties_interface = FALSE;
5895 has_introspectable_interface = FALSE;
5897 for (n = 0; interfaces[n] != NULL; n++)
5899 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5900 has_properties_interface = TRUE;
5901 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5902 has_introspectable_interface = TRUE;
5904 if (!has_properties_interface)
5905 g_string_append (s, introspect_properties_interface);
5906 if (!has_introspectable_interface)
5907 g_string_append (s, introspect_introspectable_interface);
5909 for (n = 0; interfaces[n] != NULL; n++)
5911 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5912 g_dbus_interface_info_unref (interfaces[n]);
5914 g_free (interfaces);
5917 /* then include <node> entries from the Subtree for the root */
5920 for (n = 0; children != NULL && children[n] != NULL; n++)
5921 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5924 /* finally include nodes registered below us */
5925 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5926 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5927 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5928 g_strfreev (subnode_paths);
5930 g_string_append (s, "</node>\n");
5932 reply = g_dbus_message_new_method_reply (message);
5933 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5934 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5935 g_object_unref (reply);
5940 g_string_free (s, TRUE);
5941 g_strfreev (children);
5945 /* called without lock held in the thread where the caller registered
5949 handle_subtree_method_invocation (GDBusConnection *connection,
5950 ExportedSubtree *es,
5951 GDBusMessage *message)
5954 const gchar *sender;
5955 const gchar *interface_name;
5956 const gchar *member;
5957 const gchar *signature;
5958 const gchar *requested_object_path;
5959 const gchar *requested_node;
5961 GDBusInterfaceInfo *interface_info;
5962 const GDBusInterfaceVTable *interface_vtable;
5963 gpointer interface_user_data;
5965 GDBusInterfaceInfo **interfaces;
5966 gboolean is_property_get;
5967 gboolean is_property_set;
5968 gboolean is_property_get_all;
5973 requested_object_path = g_dbus_message_get_path (message);
5974 sender = g_dbus_message_get_sender (message);
5975 interface_name = g_dbus_message_get_interface (message);
5976 member = g_dbus_message_get_member (message);
5977 signature = g_dbus_message_get_signature (message);
5978 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5980 is_property_get = FALSE;
5981 is_property_set = FALSE;
5982 is_property_get_all = FALSE;
5983 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
5985 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
5986 is_property_get = TRUE;
5987 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
5988 is_property_set = TRUE;
5989 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
5990 is_property_get_all = TRUE;
5995 requested_node = strrchr (requested_object_path, '/') + 1;
5997 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
5999 /* We don't want to dispatch to unenumerated
6000 * nodes, so ensure that the child exists.
6005 children = es->vtable->enumerate (es->connection,
6010 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6011 g_strfreev (children);
6019 requested_node = NULL;
6022 /* get introspection data for the node */
6023 interfaces = es->vtable->introspect (es->connection,
6025 requested_object_path,
6029 if (interfaces == NULL)
6032 interface_info = NULL;
6033 for (n = 0; interfaces[n] != NULL; n++)
6035 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6036 interface_info = interfaces[n];
6039 /* dispatch the call if the user wants to handle it */
6040 if (interface_info != NULL)
6042 /* figure out where to dispatch the method call */
6043 interface_user_data = NULL;
6044 interface_vtable = es->vtable->dispatch (es->connection,
6049 &interface_user_data,
6051 if (interface_vtable == NULL)
6054 CONNECTION_LOCK (connection);
6055 handled = validate_and_maybe_schedule_method_call (es->connection,
6062 interface_user_data);
6063 CONNECTION_UNLOCK (connection);
6065 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6066 else if (is_property_get || is_property_set || is_property_get_all)
6068 if (is_property_get)
6069 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6070 else if (is_property_set)
6071 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6072 else if (is_property_get_all)
6073 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6075 g_assert_not_reached ();
6077 /* see if the object supports this interface at all */
6078 for (n = 0; interfaces[n] != NULL; n++)
6080 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6081 interface_info = interfaces[n];
6084 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6085 * claims it won't support the interface
6087 if (interface_info == NULL)
6089 GDBusMessage *reply;
6090 reply = g_dbus_message_new_method_error (message,
6091 "org.freedesktop.DBus.Error.InvalidArgs",
6092 _("No such interface `%s'"),
6094 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6095 g_object_unref (reply);
6100 /* figure out where to dispatch the property get/set/getall calls */
6101 interface_user_data = NULL;
6102 interface_vtable = es->vtable->dispatch (es->connection,
6107 &interface_user_data,
6109 if (interface_vtable == NULL)
6111 g_warning ("The subtree introspection function indicates that '%s' "
6112 "is a valid interface name, but calling the dispatch "
6113 "function on that interface gave us NULL", interface_name);
6117 if (is_property_get || is_property_set)
6119 CONNECTION_LOCK (connection);
6120 handled = validate_and_maybe_schedule_property_getset (es->connection,
6128 interface_user_data);
6129 CONNECTION_UNLOCK (connection);
6131 else if (is_property_get_all)
6133 CONNECTION_LOCK (connection);
6134 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6141 interface_user_data);
6142 CONNECTION_UNLOCK (connection);
6147 if (interfaces != NULL)
6149 for (n = 0; interfaces[n] != NULL; n++)
6150 g_dbus_interface_info_unref (interfaces[n]);
6151 g_free (interfaces);
6159 GDBusMessage *message;
6160 ExportedSubtree *es;
6161 } SubtreeDeferredData;
6164 subtree_deferred_data_free (SubtreeDeferredData *data)
6166 g_object_unref (data->message);
6170 /* called without lock held in the thread where the caller registered the subtree */
6172 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6174 SubtreeDeferredData *data = _data;
6179 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6180 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6181 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6182 handled = handle_subtree_introspect (data->es->connection,
6186 handled = handle_subtree_method_invocation (data->es->connection,
6192 CONNECTION_LOCK (data->es->connection);
6193 handled = handle_generic_unlocked (data->es->connection, data->message);
6194 CONNECTION_UNLOCK (data->es->connection);
6197 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6200 GDBusMessage *reply;
6201 reply = g_dbus_message_new_method_error (data->message,
6202 "org.freedesktop.DBus.Error.UnknownMethod",
6203 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6204 g_dbus_message_get_member (data->message),
6205 g_dbus_message_get_interface (data->message),
6206 g_dbus_message_get_signature (data->message));
6207 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6208 g_object_unref (reply);
6214 /* called in GDBusWorker thread with connection's lock held */
6216 subtree_message_func (GDBusConnection *connection,
6217 ExportedSubtree *es,
6218 GDBusMessage *message)
6220 GSource *idle_source;
6221 SubtreeDeferredData *data;
6223 data = g_new0 (SubtreeDeferredData, 1);
6224 data->message = g_object_ref (message);
6227 /* defer this call to an idle handler in the right thread */
6228 idle_source = g_idle_source_new ();
6229 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6230 g_source_set_callback (idle_source,
6231 process_subtree_vtable_message_in_idle_cb,
6233 (GDestroyNotify) subtree_deferred_data_free);
6234 g_source_attach (idle_source, es->context);
6235 g_source_unref (idle_source);
6237 /* since we own the entire subtree, handlers for objects not in the subtree have been
6238 * tried already by libdbus-1 - so we just need to ensure that we're always going
6239 * to reply to the message
6245 * g_dbus_connection_register_subtree:
6246 * @connection: A #GDBusConnection.
6247 * @object_path: The object path to register the subtree at.
6248 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6249 * @flags: Flags used to fine tune the behavior of the subtree.
6250 * @user_data: Data to pass to functions in @vtable.
6251 * @user_data_free_func: Function to call when the subtree is unregistered.
6252 * @error: Return location for error or %NULL.
6254 * Registers a whole subtree of <quote>dynamic</quote> objects.
6256 * The @enumerate and @introspection functions in @vtable are used to
6257 * convey, to remote callers, what nodes exist in the subtree rooted
6260 * When handling remote calls into any node in the subtree, first the
6261 * @enumerate function is used to check if the node exists. If the node exists
6262 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6263 * the @introspection function is used to check if the node supports the
6264 * requested method. If so, the @dispatch function is used to determine
6265 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6266 * #gpointer will be used to call into the interface vtable for processing
6269 * All calls into user-provided code will be invoked in the <link
6270 * linkend="g-main-context-push-thread-default">thread-default main
6271 * loop</link> of the thread you are calling this method from.
6273 * If an existing subtree is already registered at @object_path or
6274 * then @error is set to #G_IO_ERROR_EXISTS.
6276 * Note that it is valid to register regular objects (using
6277 * g_dbus_connection_register_object()) in a subtree registered with
6278 * g_dbus_connection_register_subtree() - if so, the subtree handler
6279 * is tried as the last resort. One way to think about a subtree
6280 * handler is to consider it a <quote>fallback handler</quote>
6281 * for object paths not registered via g_dbus_connection_register_object()
6282 * or other bindings.
6284 * Note that @vtable will be copied so you cannot change it after
6287 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6289 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6290 * that can be used with g_dbus_connection_unregister_subtree() .
6295 g_dbus_connection_register_subtree (GDBusConnection *connection,
6296 const gchar *object_path,
6297 const GDBusSubtreeVTable *vtable,
6298 GDBusSubtreeFlags flags,
6300 GDestroyNotify user_data_free_func,
6304 ExportedSubtree *es;
6306 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6307 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6308 g_return_val_if_fail (vtable != NULL, 0);
6309 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6310 g_return_val_if_fail (check_initialized (connection), 0);
6314 CONNECTION_LOCK (connection);
6316 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6322 _("A subtree is already exported for %s"),
6327 es = g_new0 (ExportedSubtree, 1);
6328 es->object_path = g_strdup (object_path);
6329 es->connection = connection;
6331 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6333 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6334 es->user_data = user_data;
6335 es->user_data_free_func = user_data_free_func;
6336 es->context = g_main_context_ref_thread_default ();
6338 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6339 g_hash_table_insert (connection->map_id_to_es,
6340 GUINT_TO_POINTER (es->id),
6346 CONNECTION_UNLOCK (connection);
6351 /* ---------------------------------------------------------------------------------------------------- */
6354 * g_dbus_connection_unregister_subtree:
6355 * @connection: A #GDBusConnection.
6356 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6358 * Unregisters a subtree.
6360 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6365 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6366 guint registration_id)
6368 ExportedSubtree *es;
6371 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6372 g_return_val_if_fail (check_initialized (connection), FALSE);
6376 CONNECTION_LOCK (connection);
6378 es = g_hash_table_lookup (connection->map_id_to_es,
6379 GUINT_TO_POINTER (registration_id));
6383 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6384 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6389 CONNECTION_UNLOCK (connection);
6394 /* ---------------------------------------------------------------------------------------------------- */
6396 /* may be called in any thread, with connection's lock held */
6398 handle_generic_ping_unlocked (GDBusConnection *connection,
6399 const gchar *object_path,
6400 GDBusMessage *message)
6402 GDBusMessage *reply;
6403 reply = g_dbus_message_new_method_reply (message);
6404 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6405 g_object_unref (reply);
6408 /* may be called in any thread, with connection's lock held */
6410 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6411 const gchar *object_path,
6412 GDBusMessage *message)
6414 GDBusMessage *reply;
6417 if (connection->machine_id == NULL)
6422 connection->machine_id = _g_dbus_get_machine_id (&error);
6423 if (connection->machine_id == NULL)
6425 reply = g_dbus_message_new_method_error_literal (message,
6426 "org.freedesktop.DBus.Error.Failed",
6428 g_error_free (error);
6434 reply = g_dbus_message_new_method_reply (message);
6435 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6437 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6438 g_object_unref (reply);
6441 /* may be called in any thread, with connection's lock held */
6443 handle_generic_introspect_unlocked (GDBusConnection *connection,
6444 const gchar *object_path,
6445 GDBusMessage *message)
6450 GDBusMessage *reply;
6452 /* first the header */
6453 s = g_string_new (NULL);
6454 introspect_append_header (s);
6456 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6457 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6458 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6459 g_strfreev (registered);
6460 g_string_append (s, "</node>\n");
6462 reply = g_dbus_message_new_method_reply (message);
6463 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6464 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6465 g_object_unref (reply);
6466 g_string_free (s, TRUE);
6469 /* may be called in any thread, with connection's lock held */
6471 handle_generic_unlocked (GDBusConnection *connection,
6472 GDBusMessage *message)
6475 const gchar *interface_name;
6476 const gchar *member;
6477 const gchar *signature;
6480 CONNECTION_ENSURE_LOCK (connection);
6484 interface_name = g_dbus_message_get_interface (message);
6485 member = g_dbus_message_get_member (message);
6486 signature = g_dbus_message_get_signature (message);
6487 path = g_dbus_message_get_path (message);
6489 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6490 g_strcmp0 (member, "Introspect") == 0 &&
6491 g_strcmp0 (signature, "") == 0)
6493 handle_generic_introspect_unlocked (connection, path, message);
6496 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6497 g_strcmp0 (member, "Ping") == 0 &&
6498 g_strcmp0 (signature, "") == 0)
6500 handle_generic_ping_unlocked (connection, path, message);
6503 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6504 g_strcmp0 (member, "GetMachineId") == 0 &&
6505 g_strcmp0 (signature, "") == 0)
6507 handle_generic_get_machine_id_unlocked (connection, path, message);
6514 /* ---------------------------------------------------------------------------------------------------- */
6516 /* called in GDBusWorker thread with connection's lock held */
6518 distribute_method_call (GDBusConnection *connection,
6519 GDBusMessage *message)
6521 GDBusMessage *reply;
6523 ExportedSubtree *es;
6524 const gchar *object_path;
6525 const gchar *interface_name;
6526 const gchar *member;
6528 gchar *subtree_path;
6531 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6533 interface_name = g_dbus_message_get_interface (message);
6534 member = g_dbus_message_get_member (message);
6535 path = g_dbus_message_get_path (message);
6536 subtree_path = g_strdup (path);
6537 needle = strrchr (subtree_path, '/');
6538 if (needle != NULL && needle != subtree_path)
6544 g_free (subtree_path);
6545 subtree_path = NULL;
6549 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6551 _g_dbus_debug_print_lock ();
6552 g_print ("========================================================================\n"
6553 "GDBus-debug:Incoming:\n"
6554 " <<<< METHOD INVOCATION %s.%s()\n"
6556 " invoked by name %s\n"
6558 interface_name, member,
6560 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6561 g_dbus_message_get_serial (message));
6562 _g_dbus_debug_print_unlock ();
6565 object_path = g_dbus_message_get_path (message);
6566 g_assert (object_path != NULL);
6568 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6571 if (obj_message_func (connection, eo, message))
6575 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6578 if (subtree_message_func (connection, es, message))
6582 if (subtree_path != NULL)
6584 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6587 if (subtree_message_func (connection, es, message))
6592 if (handle_generic_unlocked (connection, message))
6595 /* if we end up here, the message has not been not handled - so return an error saying this */
6596 reply = g_dbus_message_new_method_error (message,
6597 "org.freedesktop.DBus.Error.UnknownMethod",
6598 _("No such interface `%s' on object at path %s"),
6601 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6602 g_object_unref (reply);
6605 g_free (subtree_path);
6608 /* ---------------------------------------------------------------------------------------------------- */
6610 /* Called in any user thread, with the message_bus_lock held. */
6611 static GDBusConnection **
6612 message_bus_get_singleton (GBusType bus_type,
6615 GDBusConnection **ret;
6616 const gchar *starter_bus;
6622 case G_BUS_TYPE_SESSION:
6623 ret = &the_session_bus;
6626 case G_BUS_TYPE_SYSTEM:
6627 ret = &the_system_bus;
6630 case G_BUS_TYPE_STARTER:
6631 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6632 if (g_strcmp0 (starter_bus, "session") == 0)
6634 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6637 else if (g_strcmp0 (starter_bus, "system") == 0)
6639 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6644 if (starter_bus != NULL)
6648 G_IO_ERROR_INVALID_ARGUMENT,
6649 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6650 " - unknown value `%s'"),
6655 g_set_error_literal (error,
6657 G_IO_ERROR_INVALID_ARGUMENT,
6658 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6659 "variable is not set"));
6665 g_assert_not_reached ();
6673 /* Called in any user thread, without holding locks. */
6674 static GDBusConnection *
6675 get_uninitialized_connection (GBusType bus_type,
6676 GCancellable *cancellable,
6679 GDBusConnection **singleton;
6680 GDBusConnection *ret;
6684 G_LOCK (message_bus_lock);
6685 singleton = message_bus_get_singleton (bus_type, error);
6686 if (singleton == NULL)
6689 if (*singleton == NULL)
6692 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6693 if (address == NULL)
6695 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6697 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6698 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6699 "exit-on-close", TRUE,
6705 ret = g_object_ref (*singleton);
6708 g_assert (ret != NULL);
6711 G_UNLOCK (message_bus_lock);
6717 * @bus_type: A #GBusType.
6718 * @cancellable: A #GCancellable or %NULL.
6719 * @error: Return location for error or %NULL.
6721 * Synchronously connects to the message bus specified by @bus_type.
6722 * Note that the returned object may shared with other callers,
6723 * e.g. if two separate parts of a process calls this function with
6724 * the same @bus_type, they will share the same object.
6726 * This is a synchronous failable function. See g_bus_get() and
6727 * g_bus_get_finish() for the asynchronous version.
6729 * The returned object is a singleton, that is, shared with other
6730 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6731 * event that you need a private message bus connection, use
6732 * g_dbus_address_get_for_bus_sync() and
6733 * g_dbus_connection_new_for_address().
6735 * Note that the returned #GDBusConnection object will (usually) have
6736 * the #GDBusConnection:exit-on-close property set to %TRUE.
6738 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6743 g_bus_get_sync (GBusType bus_type,
6744 GCancellable *cancellable,
6747 GDBusConnection *connection;
6749 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6751 connection = get_uninitialized_connection (bus_type, cancellable, error);
6752 if (connection == NULL)
6755 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6757 g_object_unref (connection);
6766 bus_get_async_initable_cb (GObject *source_object,
6770 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6774 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6778 g_assert (error != NULL);
6779 g_simple_async_result_take_error (simple, error);
6780 g_object_unref (source_object);
6784 g_simple_async_result_set_op_res_gpointer (simple,
6788 g_simple_async_result_complete_in_idle (simple);
6789 g_object_unref (simple);
6794 * @bus_type: A #GBusType.
6795 * @cancellable: A #GCancellable or %NULL.
6796 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6797 * @user_data: The data to pass to @callback.
6799 * Asynchronously connects to the message bus specified by @bus_type.
6801 * When the operation is finished, @callback will be invoked. You can
6802 * then call g_bus_get_finish() to get the result of the operation.
6804 * This is a asynchronous failable function. See g_bus_get_sync() for
6805 * the synchronous version.
6810 g_bus_get (GBusType bus_type,
6811 GCancellable *cancellable,
6812 GAsyncReadyCallback callback,
6815 GDBusConnection *connection;
6816 GSimpleAsyncResult *simple;
6819 simple = g_simple_async_result_new (NULL,
6825 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6826 if (connection == NULL)
6828 g_assert (error != NULL);
6829 g_simple_async_result_take_error (simple, error);
6830 g_simple_async_result_complete_in_idle (simple);
6831 g_object_unref (simple);
6835 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6838 bus_get_async_initable_cb,
6845 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6846 * @error: Return location for error or %NULL.
6848 * Finishes an operation started with g_bus_get().
6850 * The returned object is a singleton, that is, shared with other
6851 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6852 * event that you need a private message bus connection, use
6853 * g_dbus_address_get_for_bus_sync() and
6854 * g_dbus_connection_new_for_address().
6856 * Note that the returned #GDBusConnection object will (usually) have
6857 * the #GDBusConnection:exit-on-close property set to %TRUE.
6859 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6864 g_bus_get_finish (GAsyncResult *res,
6867 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6869 GDBusConnection *ret;
6871 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6873 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6877 if (g_simple_async_result_propagate_error (simple, error))
6880 object = g_simple_async_result_get_op_res_gpointer (simple);
6881 g_assert (object != NULL);
6882 ret = g_object_ref (G_DBUS_CONNECTION (object));
6888 /* ---------------------------------------------------------------------------------------------------- */