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,
333 FLAG_EXIT_ON_CLOSE = 1 << 1,
340 * The #GDBusConnection structure contains only private data and
341 * should only be accessed using the provided API.
345 struct _GDBusConnection
348 GObject parent_instance;
350 /* ------------------------------------------------------------------------ */
351 /* -- General object state ------------------------------------------------ */
352 /* ------------------------------------------------------------------------ */
354 /* General-purpose lock for most fields */
357 /* A lock used in the init() method of the GInitable interface - see comments
358 * in initable_init() for why a separate lock is needed.
360 * If you need both @lock and @init_lock, you must take @init_lock first.
364 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
365 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
369 /* The underlying stream used for communication
370 * Read-only after initable_init(), so it may be read if you either
371 * hold @init_lock or check for initialization first.
375 /* The object used for authentication (if any).
376 * Read-only after initable_init(), so it may be read if you either
377 * hold @init_lock or check for initialization first.
381 /* Last serial used. Protected by @lock. */
384 /* The object used to send/receive messages.
385 * Read-only after initable_init(), so it may be read if you either
386 * hold @init_lock or check for initialization first.
390 /* If connected to a message bus, this contains the unique name assigned to
391 * us by the bus (e.g. ":1.42").
392 * Read-only after initable_init(), so it may be read if you either
393 * hold @init_lock or check for initialization first.
395 gchar *bus_unique_name;
397 /* The GUID returned by the other side if we authenticed as a client or
398 * the GUID to use if authenticating as a server.
399 * Read-only after initable_init(), so it may be read if you either
400 * hold @init_lock or check for initialization first.
404 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
405 * Inspect @initialization_error to see whether it succeeded or failed.
407 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
409 * FLAG_CLOSED is the closed property. It may be read at any time, but
410 * may only be written while holding @lock.
412 volatile gint atomic_flags;
414 /* If the connection could not be established during initable_init(),
415 * this GError will be set.
416 * Read-only after initable_init(), so it may be read if you either
417 * hold @init_lock or check for initialization first.
419 GError *initialization_error;
421 /* The result of g_main_context_ref_thread_default() when the object
422 * was created (the GObject _init() function) - this is used for delivery
423 * of the :closed GObject signal.
425 * Only set in the GObject init function, so no locks are needed.
427 GMainContext *main_context_at_construction;
429 /* Read-only construct properties, no locks needed */
431 GDBusConnectionFlags flags;
433 /* Map used for managing method replies, protected by @lock */
434 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
436 /* Maps used for managing signal subscription, protected by @lock */
437 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
438 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
439 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
441 /* Maps used for managing exported objects and subtrees,
444 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
445 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
446 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
447 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
449 /* Structure used for message filters, protected by @lock */
452 /* Capabilities negotiated during authentication
453 * Read-only after initable_init(), so it may be read without holding a
454 * lock, if you check for initialization first.
456 GDBusCapabilityFlags capabilities;
458 /* Protected by @init_lock */
459 GDBusAuthObserver *authentication_observer;
461 /* Read-only after initable_init(), so it may be read if you either
462 * hold @init_lock or check for initialization first.
464 GCredentials *credentials;
466 /* set to TRUE when finalizing */
470 typedef struct ExportedObject ExportedObject;
471 static void exported_object_free (ExportedObject *eo);
473 typedef struct ExportedSubtree ExportedSubtree;
474 static void exported_subtree_free (ExportedSubtree *es);
492 PROP_CAPABILITY_FLAGS,
493 PROP_AUTHENTICATION_OBSERVER,
496 static void distribute_signals (GDBusConnection *connection,
497 GDBusMessage *message);
499 static void distribute_method_call (GDBusConnection *connection,
500 GDBusMessage *message);
502 static gboolean handle_generic_unlocked (GDBusConnection *connection,
503 GDBusMessage *message);
506 static void purge_all_signal_subscriptions (GDBusConnection *connection);
507 static void purge_all_filters (GDBusConnection *connection);
509 #define _G_ENSURE_LOCK(name) do { \
510 if (G_UNLIKELY (G_TRYLOCK(name))) \
512 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
513 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
517 static guint signals[LAST_SIGNAL] = { 0 };
519 static void initable_iface_init (GInitableIface *initable_iface);
520 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
522 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
523 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
524 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
528 * Check that all members of @connection that can only be accessed after
529 * the connection is initialized can safely be accessed. If not,
530 * log a critical warning. This function is a memory barrier.
532 * Returns: %TRUE if initialized
535 check_initialized (GDBusConnection *connection)
537 /* The access to @atomic_flags isn't conditional, so that this function
538 * provides a memory barrier for thread-safety even if checks are disabled.
539 * (If you don't want this stricter guarantee, you can call
540 * g_return_if_fail (check_initialized (c)).)
542 * This isn't strictly necessary now that we've decided use of an
543 * uninitialized GDBusConnection is undefined behaviour, but it seems
544 * better to be as deterministic as is feasible.
546 * (Anything that could suffer a crash from seeing undefined values
547 * must have a race condition - thread A initializes the connection while
548 * thread B calls a method without initialization, hoping that thread A will
549 * win the race - so its behaviour is undefined anyway.)
551 gint flags = g_atomic_int_get (&connection->atomic_flags);
553 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
555 /* We can safely access this, due to the memory barrier above */
556 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
562 MAY_BE_UNINITIALIZED = (1<<1)
563 } CheckUnclosedFlags;
566 * Check the same thing as check_initialized(), and also that the
567 * connection is not closed. If the connection is uninitialized,
568 * raise a critical warning (it's programmer error); if it's closed,
569 * raise a recoverable GError (it's a runtime error).
571 * This function is a memory barrier.
573 * Returns: %TRUE if initialized and not closed
576 check_unclosed (GDBusConnection *connection,
577 CheckUnclosedFlags check,
580 /* check_initialized() is effectively inlined, so we don't waste time
581 * doing two memory barriers
583 gint flags = g_atomic_int_get (&connection->atomic_flags);
585 if (!(check & MAY_BE_UNINITIALIZED))
587 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
588 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
591 if (flags & FLAG_CLOSED)
593 g_set_error_literal (error,
596 _("The connection is closed"));
603 static GHashTable *alive_connections = NULL;
606 g_dbus_connection_dispose (GObject *object)
608 GDBusConnection *connection = G_DBUS_CONNECTION (object);
610 G_LOCK (message_bus_lock);
611 if (connection == the_session_bus)
613 the_session_bus = NULL;
615 else if (connection == the_system_bus)
617 the_system_bus = NULL;
619 CONNECTION_LOCK (connection);
620 if (connection->worker != NULL)
622 _g_dbus_worker_stop (connection->worker);
623 connection->worker = NULL;
624 if (alive_connections != NULL)
625 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
629 if (alive_connections != NULL)
630 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
632 CONNECTION_UNLOCK (connection);
633 G_UNLOCK (message_bus_lock);
635 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
636 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
640 g_dbus_connection_finalize (GObject *object)
642 GDBusConnection *connection = G_DBUS_CONNECTION (object);
644 connection->finalizing = TRUE;
646 purge_all_signal_subscriptions (connection);
648 purge_all_filters (connection);
649 g_ptr_array_unref (connection->filters);
651 if (connection->authentication_observer != NULL)
652 g_object_unref (connection->authentication_observer);
654 if (connection->auth != NULL)
655 g_object_unref (connection->auth);
657 if (connection->credentials)
658 g_object_unref (connection->credentials);
660 if (connection->stream != NULL)
662 g_object_unref (connection->stream);
663 connection->stream = NULL;
666 g_free (connection->address);
668 g_free (connection->guid);
669 g_free (connection->bus_unique_name);
671 if (connection->initialization_error != NULL)
672 g_error_free (connection->initialization_error);
674 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
676 g_hash_table_unref (connection->map_rule_to_signal_data);
677 g_hash_table_unref (connection->map_id_to_signal_data);
678 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
680 g_hash_table_unref (connection->map_id_to_ei);
681 g_hash_table_unref (connection->map_object_path_to_eo);
682 g_hash_table_unref (connection->map_id_to_es);
683 g_hash_table_unref (connection->map_object_path_to_es);
685 g_main_context_unref (connection->main_context_at_construction);
687 g_free (connection->machine_id);
689 g_mutex_clear (&connection->init_lock);
690 g_mutex_clear (&connection->lock);
692 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
695 /* called in any user thread, with the connection's lock not held */
697 g_dbus_connection_get_property (GObject *object,
702 GDBusConnection *connection = G_DBUS_CONNECTION (object);
707 g_value_set_object (value, g_dbus_connection_get_stream (connection));
711 g_value_set_string (value, g_dbus_connection_get_guid (connection));
714 case PROP_UNIQUE_NAME:
715 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
719 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
722 case PROP_EXIT_ON_CLOSE:
723 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
726 case PROP_CAPABILITY_FLAGS:
727 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
731 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
736 /* called in any user thread, with the connection's lock not held */
738 g_dbus_connection_set_property (GObject *object,
743 GDBusConnection *connection = G_DBUS_CONNECTION (object);
748 connection->stream = g_value_dup_object (value);
752 connection->guid = g_value_dup_string (value);
756 connection->address = g_value_dup_string (value);
760 connection->flags = g_value_get_flags (value);
763 case PROP_EXIT_ON_CLOSE:
764 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
767 case PROP_AUTHENTICATION_OBSERVER:
768 connection->authentication_observer = g_value_dup_object (value);
772 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
777 /* Base-class implementation of GDBusConnection::closed.
779 * Called in a user thread, by the main context that was thread-default when
780 * the object was constructed.
783 g_dbus_connection_real_closed (GDBusConnection *connection,
784 gboolean remote_peer_vanished,
787 gint flags = g_atomic_int_get (&connection->atomic_flags);
789 /* Because atomic int access is a memory barrier, we can safely read
790 * initialization_error without a lock, as long as we do it afterwards.
792 if (remote_peer_vanished &&
793 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
794 (flags & FLAG_INITIALIZED) != 0 &&
795 connection->initialization_error == NULL)
799 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
802 g_quark_to_string (error->domain), error->code);
806 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
813 g_dbus_connection_class_init (GDBusConnectionClass *klass)
815 GObjectClass *gobject_class;
817 gobject_class = G_OBJECT_CLASS (klass);
819 gobject_class->finalize = g_dbus_connection_finalize;
820 gobject_class->dispose = g_dbus_connection_dispose;
821 gobject_class->set_property = g_dbus_connection_set_property;
822 gobject_class->get_property = g_dbus_connection_get_property;
824 klass->closed = g_dbus_connection_real_closed;
827 * GDBusConnection:stream:
829 * The underlying #GIOStream used for I/O.
831 * If this is passed on construction and is a #GSocketConnection,
832 * then the corresponding #GSocket will be put into non-blocking mode.
834 * While the #GDBusConnection is active, it will interact with this
835 * stream from a worker thread, so it is not safe to interact with
836 * the stream directly.
840 g_object_class_install_property (gobject_class,
842 g_param_spec_object ("stream",
844 P_("The underlying streams used for I/O"),
848 G_PARAM_CONSTRUCT_ONLY |
849 G_PARAM_STATIC_NAME |
850 G_PARAM_STATIC_BLURB |
851 G_PARAM_STATIC_NICK));
854 * GDBusConnection:address:
856 * A D-Bus address specifying potential endpoints that can be used
857 * when establishing the connection.
861 g_object_class_install_property (gobject_class,
863 g_param_spec_string ("address",
865 P_("D-Bus address specifying potential socket endpoints"),
868 G_PARAM_CONSTRUCT_ONLY |
869 G_PARAM_STATIC_NAME |
870 G_PARAM_STATIC_BLURB |
871 G_PARAM_STATIC_NICK));
874 * GDBusConnection:flags:
876 * Flags from the #GDBusConnectionFlags enumeration.
880 g_object_class_install_property (gobject_class,
882 g_param_spec_flags ("flags",
885 G_TYPE_DBUS_CONNECTION_FLAGS,
886 G_DBUS_CONNECTION_FLAGS_NONE,
888 G_PARAM_CONSTRUCT_ONLY |
889 G_PARAM_STATIC_NAME |
890 G_PARAM_STATIC_BLURB |
891 G_PARAM_STATIC_NICK));
894 * GDBusConnection:guid:
896 * The GUID of the peer performing the role of server when
899 * If you are constructing a #GDBusConnection and pass
900 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
901 * #GDBusConnection:flags property then you MUST also set this
902 * property to a valid guid.
904 * If you are constructing a #GDBusConnection and pass
905 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
906 * #GDBusConnection:flags property you will be able to read the GUID
907 * of the other peer here after the connection has been successfully
912 g_object_class_install_property (gobject_class,
914 g_param_spec_string ("guid",
916 P_("GUID of the server peer"),
920 G_PARAM_CONSTRUCT_ONLY |
921 G_PARAM_STATIC_NAME |
922 G_PARAM_STATIC_BLURB |
923 G_PARAM_STATIC_NICK));
926 * GDBusConnection:unique-name:
928 * The unique name as assigned by the message bus or %NULL if the
929 * connection is not open or not a message bus connection.
933 g_object_class_install_property (gobject_class,
935 g_param_spec_string ("unique-name",
937 P_("Unique name of bus connection"),
940 G_PARAM_STATIC_NAME |
941 G_PARAM_STATIC_BLURB |
942 G_PARAM_STATIC_NICK));
945 * GDBusConnection:closed:
947 * A boolean specifying whether the connection has been closed.
951 g_object_class_install_property (gobject_class,
953 g_param_spec_boolean ("closed",
955 P_("Whether the connection is closed"),
958 G_PARAM_STATIC_NAME |
959 G_PARAM_STATIC_BLURB |
960 G_PARAM_STATIC_NICK));
963 * GDBusConnection:exit-on-close:
965 * A boolean specifying whether the process will be terminated (by
966 * calling <literal>raise(SIGTERM)</literal>) if the connection
967 * is closed by the remote peer.
971 g_object_class_install_property (gobject_class,
973 g_param_spec_boolean ("exit-on-close",
975 P_("Whether the process is terminated when the connection is closed"),
979 G_PARAM_STATIC_NAME |
980 G_PARAM_STATIC_BLURB |
981 G_PARAM_STATIC_NICK));
984 * GDBusConnection:capabilities:
986 * Flags from the #GDBusCapabilityFlags enumeration
987 * representing connection features negotiated with the other peer.
991 g_object_class_install_property (gobject_class,
992 PROP_CAPABILITY_FLAGS,
993 g_param_spec_flags ("capabilities",
996 G_TYPE_DBUS_CAPABILITY_FLAGS,
997 G_DBUS_CAPABILITY_FLAGS_NONE,
999 G_PARAM_STATIC_NAME |
1000 G_PARAM_STATIC_BLURB |
1001 G_PARAM_STATIC_NICK));
1004 * GDBusConnection:authentication-observer:
1006 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1010 g_object_class_install_property (gobject_class,
1011 PROP_AUTHENTICATION_OBSERVER,
1012 g_param_spec_object ("authentication-observer",
1013 P_("Authentication Observer"),
1014 P_("Object used to assist in the authentication process"),
1015 G_TYPE_DBUS_AUTH_OBSERVER,
1017 G_PARAM_CONSTRUCT_ONLY |
1018 G_PARAM_STATIC_NAME |
1019 G_PARAM_STATIC_BLURB |
1020 G_PARAM_STATIC_NICK));
1023 * GDBusConnection::closed:
1024 * @connection: The #GDBusConnection emitting the signal.
1025 * @remote_peer_vanished: %TRUE if @connection is closed because the
1026 * remote peer closed its end of the connection.
1027 * @error: A #GError with more details about the event or %NULL.
1029 * Emitted when the connection is closed.
1031 * The cause of this event can be
1034 * If g_dbus_connection_close() is called. In this case
1035 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1036 * </para></listitem>
1038 * If the remote peer closes the connection. In this case
1039 * @remote_peer_vanished is set to %TRUE and @error is set.
1040 * </para></listitem>
1042 * If the remote peer sends invalid or malformed data. In this
1043 * case @remote_peer_vanished is set to %FALSE and @error
1045 * </para></listitem>
1048 * Upon receiving this signal, you should give up your reference to
1049 * @connection. You are guaranteed that this signal is emitted only
1054 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1055 G_TYPE_DBUS_CONNECTION,
1057 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1068 g_dbus_connection_init (GDBusConnection *connection)
1070 g_mutex_init (&connection->lock);
1071 g_mutex_init (&connection->init_lock);
1073 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1075 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1077 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1079 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1082 (GDestroyNotify) g_ptr_array_unref);
1084 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1087 (GDestroyNotify) exported_object_free);
1089 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1092 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1095 (GDestroyNotify) exported_subtree_free);
1097 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1100 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1102 connection->filters = g_ptr_array_new ();
1106 * g_dbus_connection_get_stream:
1107 * @connection: a #GDBusConnection
1109 * Gets the underlying stream used for IO.
1111 * While the #GDBusConnection is active, it will interact with this
1112 * stream from a worker thread, so it is not safe to interact with
1113 * the stream directly.
1115 * Returns: (transfer none): the stream used for IO
1120 g_dbus_connection_get_stream (GDBusConnection *connection)
1122 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1124 /* do not use g_return_val_if_fail(), we want the memory barrier */
1125 if (!check_initialized (connection))
1128 return connection->stream;
1132 * g_dbus_connection_start_message_processing:
1133 * @connection: A #GDBusConnection.
1135 * If @connection was created with
1136 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1137 * starts processing messages. Does nothing on if @connection wasn't
1138 * created with this flag or if the method has already been called.
1143 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1145 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1147 /* do not use g_return_val_if_fail(), we want the memory barrier */
1148 if (!check_initialized (connection))
1151 g_assert (connection->worker != NULL);
1152 _g_dbus_worker_unfreeze (connection->worker);
1156 * g_dbus_connection_is_closed:
1157 * @connection: A #GDBusConnection.
1159 * Gets whether @connection is closed.
1161 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1166 g_dbus_connection_is_closed (GDBusConnection *connection)
1170 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1172 flags = g_atomic_int_get (&connection->atomic_flags);
1174 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1178 * g_dbus_connection_get_capabilities:
1179 * @connection: A #GDBusConnection.
1181 * Gets the capabilities negotiated with the remote peer
1183 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1187 GDBusCapabilityFlags
1188 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1190 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1192 /* do not use g_return_val_if_fail(), we want the memory barrier */
1193 if (!check_initialized (connection))
1194 return G_DBUS_CAPABILITY_FLAGS_NONE;
1196 return connection->capabilities;
1199 /* ---------------------------------------------------------------------------------------------------- */
1201 /* Called in a temporary thread without holding locks. */
1203 flush_in_thread_func (GSimpleAsyncResult *res,
1205 GCancellable *cancellable)
1210 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1213 g_simple_async_result_take_error (res, error);
1217 * g_dbus_connection_flush:
1218 * @connection: A #GDBusConnection.
1219 * @cancellable: A #GCancellable or %NULL.
1220 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1221 * satisfied or %NULL if you don't care about the result.
1222 * @user_data: The data to pass to @callback.
1224 * Asynchronously flushes @connection, that is, writes all queued
1225 * outgoing message to the transport and then flushes the transport
1226 * (using g_output_stream_flush_async()). This is useful in programs
1227 * that wants to emit a D-Bus signal and then exit
1228 * immediately. Without flushing the connection, there is no guarantee
1229 * that the message has been sent to the networking buffers in the OS
1232 * This is an asynchronous method. When the operation is finished,
1233 * @callback will be invoked in the <link
1234 * linkend="g-main-context-push-thread-default">thread-default main
1235 * loop</link> of the thread you are calling this method from. You can
1236 * then call g_dbus_connection_flush_finish() to get the result of the
1237 * operation. See g_dbus_connection_flush_sync() for the synchronous
1243 g_dbus_connection_flush (GDBusConnection *connection,
1244 GCancellable *cancellable,
1245 GAsyncReadyCallback callback,
1248 GSimpleAsyncResult *simple;
1250 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1252 simple = g_simple_async_result_new (G_OBJECT (connection),
1255 g_dbus_connection_flush);
1256 g_simple_async_result_run_in_thread (simple,
1257 flush_in_thread_func,
1260 g_object_unref (simple);
1264 * g_dbus_connection_flush_finish:
1265 * @connection: A #GDBusConnection.
1266 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1267 * @error: Return location for error or %NULL.
1269 * Finishes an operation started with g_dbus_connection_flush().
1271 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1276 g_dbus_connection_flush_finish (GDBusConnection *connection,
1280 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1285 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1286 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1287 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1289 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1291 if (g_simple_async_result_propagate_error (simple, error))
1301 * g_dbus_connection_flush_sync:
1302 * @connection: A #GDBusConnection.
1303 * @cancellable: A #GCancellable or %NULL.
1304 * @error: Return location for error or %NULL.
1306 * Synchronously flushes @connection. The calling thread is blocked
1307 * until this is done. See g_dbus_connection_flush() for the
1308 * asynchronous version of this method and more details about what it
1311 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1316 g_dbus_connection_flush_sync (GDBusConnection *connection,
1317 GCancellable *cancellable,
1322 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1323 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1327 /* This is only a best-effort attempt to see whether the connection is
1328 * closed, so it doesn't need the lock. If the connection closes just
1329 * after this check, but before scheduling the flush operation, the
1330 * result will be more or less the same as if the connection closed while
1331 * the flush operation was pending - it'll fail with either CLOSED or
1334 if (!check_unclosed (connection, 0, error))
1337 g_assert (connection->worker != NULL);
1339 ret = _g_dbus_worker_flush_sync (connection->worker,
1347 /* ---------------------------------------------------------------------------------------------------- */
1351 GDBusConnection *connection;
1353 gboolean remote_peer_vanished;
1357 emit_closed_data_free (EmitClosedData *data)
1359 g_object_unref (data->connection);
1360 if (data->error != NULL)
1361 g_error_free (data->error);
1365 /* Called in a user thread that has acquired the main context that was
1366 * thread-default when the object was constructed
1369 emit_closed_in_idle (gpointer user_data)
1371 EmitClosedData *data = user_data;
1374 g_object_notify (G_OBJECT (data->connection), "closed");
1375 g_signal_emit (data->connection,
1376 signals[CLOSED_SIGNAL],
1378 data->remote_peer_vanished,
1384 /* Can be called from any thread, must hold lock.
1385 * FLAG_CLOSED must already have been set.
1388 schedule_closed_unlocked (GDBusConnection *connection,
1389 gboolean remote_peer_vanished,
1392 GSource *idle_source;
1393 EmitClosedData *data;
1395 CONNECTION_ENSURE_LOCK (connection);
1397 data = g_new0 (EmitClosedData, 1);
1398 data->connection = g_object_ref (connection);
1399 data->remote_peer_vanished = remote_peer_vanished;
1400 data->error = error != NULL ? g_error_copy (error) : NULL;
1402 idle_source = g_idle_source_new ();
1403 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1404 g_source_set_callback (idle_source,
1405 emit_closed_in_idle,
1407 (GDestroyNotify) emit_closed_data_free);
1408 g_source_attach (idle_source, connection->main_context_at_construction);
1409 g_source_unref (idle_source);
1412 /* ---------------------------------------------------------------------------------------------------- */
1415 * g_dbus_connection_close:
1416 * @connection: A #GDBusConnection.
1417 * @cancellable: A #GCancellable or %NULL.
1418 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1419 * satisfied or %NULL if you don't care about the result.
1420 * @user_data: The data to pass to @callback.
1422 * Closes @connection. Note that this never causes the process to
1423 * exit (this might only happen if the other end of a shared message
1424 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1426 * Once the connection is closed, operations such as sending a message
1427 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1428 * will not automatically flush the connection so queued messages may
1429 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1431 * If @connection is already closed, this method fails with
1432 * %G_IO_ERROR_CLOSED.
1434 * When @connection has been closed, the #GDBusConnection::closed
1435 * signal is emitted in the <link
1436 * linkend="g-main-context-push-thread-default">thread-default main
1437 * loop</link> of the thread that @connection was constructed in.
1439 * This is an asynchronous method. When the operation is finished,
1440 * @callback will be invoked in the <link
1441 * linkend="g-main-context-push-thread-default">thread-default main
1442 * loop</link> of the thread you are calling this method from. You can
1443 * then call g_dbus_connection_close_finish() to get the result of the
1444 * operation. See g_dbus_connection_close_sync() for the synchronous
1450 g_dbus_connection_close (GDBusConnection *connection,
1451 GCancellable *cancellable,
1452 GAsyncReadyCallback callback,
1455 GSimpleAsyncResult *simple;
1457 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1459 /* do not use g_return_val_if_fail(), we want the memory barrier */
1460 if (!check_initialized (connection))
1463 g_assert (connection->worker != NULL);
1465 simple = g_simple_async_result_new (G_OBJECT (connection),
1468 g_dbus_connection_close);
1469 _g_dbus_worker_close (connection->worker, cancellable, simple);
1470 g_object_unref (simple);
1474 * g_dbus_connection_close_finish:
1475 * @connection: A #GDBusConnection.
1476 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1477 * @error: Return location for error or %NULL.
1479 * Finishes an operation started with g_dbus_connection_close().
1481 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1486 g_dbus_connection_close_finish (GDBusConnection *connection,
1490 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1495 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1496 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1497 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1499 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1501 if (g_simple_async_result_propagate_error (simple, error))
1512 GAsyncResult *result;
1515 /* Can be called by any thread, without the connection lock */
1517 sync_close_cb (GObject *source_object,
1521 SyncCloseData *data = user_data;
1523 data->result = g_object_ref (res);
1524 g_main_loop_quit (data->loop);
1528 * g_dbus_connection_close_sync:
1529 * @connection: A #GDBusConnection.
1530 * @cancellable: A #GCancellable or %NULL.
1531 * @error: Return location for error or %NULL.
1533 * Synchronously closees @connection. The calling thread is blocked
1534 * until this is done. See g_dbus_connection_close() for the
1535 * asynchronous version of this method and more details about what it
1538 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1543 g_dbus_connection_close_sync (GDBusConnection *connection,
1544 GCancellable *cancellable,
1549 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1550 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1554 if (check_unclosed (connection, 0, error))
1556 GMainContext *context;
1559 context = g_main_context_new ();
1560 g_main_context_push_thread_default (context);
1561 data.loop = g_main_loop_new (context, TRUE);
1564 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1565 g_main_loop_run (data.loop);
1566 ret = g_dbus_connection_close_finish (connection, data.result, error);
1568 g_object_unref (data.result);
1569 g_main_loop_unref (data.loop);
1570 g_main_context_pop_thread_default (context);
1571 g_main_context_unref (context);
1577 /* ---------------------------------------------------------------------------------------------------- */
1579 /* Can be called by any thread, with the connection lock held */
1581 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1582 GDBusMessage *message,
1583 GDBusSendMessageFlags flags,
1584 volatile guint32 *out_serial,
1589 guint32 serial_to_use;
1592 CONNECTION_ENSURE_LOCK (connection);
1594 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1595 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1597 /* TODO: check all necessary headers are present */
1602 if (out_serial != NULL)
1605 /* If we're in initable_init(), don't check for being initialized, to avoid
1606 * chicken-and-egg problems. initable_init() is responsible for setting up
1607 * our prerequisites (mainly connection->worker), and only calling us
1608 * from its own thread (so no memory barrier is needed).
1610 if (!check_unclosed (connection,
1611 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1615 blob = g_dbus_message_to_blob (message,
1617 connection->capabilities,
1622 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1623 serial_to_use = g_dbus_message_get_serial (message);
1625 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1630 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1633 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1636 g_assert_not_reached ();
1641 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1642 blob_size, serial_to_use, connection);
1643 g_printerr ("----\n");
1644 hexdump (blob, blob_size);
1645 g_printerr ("----\n");
1648 /* TODO: use connection->auth to encode the blob */
1650 if (out_serial != NULL)
1651 *out_serial = serial_to_use;
1653 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1654 g_dbus_message_set_serial (message, serial_to_use);
1656 g_dbus_message_lock (message);
1657 _g_dbus_worker_send_message (connection->worker,
1661 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1672 * g_dbus_connection_send_message:
1673 * @connection: A #GDBusConnection.
1674 * @message: A #GDBusMessage
1675 * @flags: Flags affecting how the message is sent.
1676 * @out_serial: (out) (allow-none): Return location for serial number assigned
1677 * to @message when sending it or %NULL.
1678 * @error: Return location for error or %NULL.
1680 * Asynchronously sends @message to the peer represented by @connection.
1682 * Unless @flags contain the
1683 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1684 * will be assigned by @connection and set on @message via
1685 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1686 * serial number used will be written to this location prior to
1687 * submitting the message to the underlying transport.
1689 * If @connection is closed then the operation will fail with
1690 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1691 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1693 * See <xref linkend="gdbus-server"/> and <xref
1694 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1695 * low-level API to send and receive UNIX file descriptors.
1697 * Note that @message must be unlocked, unless @flags contain the
1698 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1700 * Returns: %TRUE if the message was well-formed and queued for
1701 * transmission, %FALSE if @error is set.
1706 g_dbus_connection_send_message (GDBusConnection *connection,
1707 GDBusMessage *message,
1708 GDBusSendMessageFlags flags,
1709 volatile guint32 *out_serial,
1714 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1715 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1716 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1717 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1719 CONNECTION_LOCK (connection);
1720 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1721 CONNECTION_UNLOCK (connection);
1725 /* ---------------------------------------------------------------------------------------------------- */
1729 volatile gint ref_count;
1730 GDBusConnection *connection;
1732 GSimpleAsyncResult *simple;
1734 GMainContext *main_context;
1736 GCancellable *cancellable;
1738 gulong cancellable_handler_id;
1740 GSource *timeout_source;
1745 /* Can be called from any thread with or without lock held */
1746 static SendMessageData *
1747 send_message_data_ref (SendMessageData *data)
1749 g_atomic_int_inc (&data->ref_count);
1753 /* Can be called from any thread with or without lock held */
1755 send_message_data_unref (SendMessageData *data)
1757 if (g_atomic_int_dec_and_test (&data->ref_count))
1759 g_assert (data->timeout_source == NULL);
1760 g_assert (data->simple == NULL);
1761 g_assert (data->cancellable_handler_id == 0);
1762 g_object_unref (data->connection);
1763 if (data->cancellable != NULL)
1764 g_object_unref (data->cancellable);
1765 g_main_context_unref (data->main_context);
1770 /* ---------------------------------------------------------------------------------------------------- */
1772 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1774 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1776 CONNECTION_ENSURE_LOCK (data->connection);
1778 g_assert (!data->delivered);
1780 data->delivered = TRUE;
1782 g_simple_async_result_complete_in_idle (data->simple);
1783 g_object_unref (data->simple);
1784 data->simple = NULL;
1786 if (data->timeout_source != NULL)
1788 g_source_destroy (data->timeout_source);
1789 data->timeout_source = NULL;
1791 if (data->cancellable_handler_id > 0)
1793 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1794 data->cancellable_handler_id = 0;
1799 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1800 GUINT_TO_POINTER (data->serial)));
1803 send_message_data_unref (data);
1806 /* ---------------------------------------------------------------------------------------------------- */
1808 /* Can be called from any thread with lock held */
1810 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1811 GDBusMessage *reply)
1813 if (data->delivered)
1816 g_simple_async_result_set_op_res_gpointer (data->simple,
1817 g_object_ref (reply),
1820 send_message_with_reply_deliver (data, TRUE);
1826 /* ---------------------------------------------------------------------------------------------------- */
1828 /* Called from a user thread, lock is not held */
1830 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1832 SendMessageData *data = user_data;
1834 CONNECTION_LOCK (data->connection);
1835 if (data->delivered)
1838 g_simple_async_result_set_error (data->simple,
1840 G_IO_ERROR_CANCELLED,
1841 _("Operation was cancelled"));
1843 send_message_with_reply_deliver (data, TRUE);
1846 CONNECTION_UNLOCK (data->connection);
1850 /* Can be called from any thread with or without lock held */
1852 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1855 SendMessageData *data = user_data;
1856 GSource *idle_source;
1858 /* postpone cancellation to idle handler since we may be called directly
1859 * via g_cancellable_connect() (e.g. holding lock)
1861 idle_source = g_idle_source_new ();
1862 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1863 g_source_set_callback (idle_source,
1864 send_message_with_reply_cancelled_idle_cb,
1865 send_message_data_ref (data),
1866 (GDestroyNotify) send_message_data_unref);
1867 g_source_attach (idle_source, data->main_context);
1868 g_source_unref (idle_source);
1871 /* ---------------------------------------------------------------------------------------------------- */
1873 /* Called from a user thread, lock is not held */
1875 send_message_with_reply_timeout_cb (gpointer user_data)
1877 SendMessageData *data = user_data;
1879 CONNECTION_LOCK (data->connection);
1880 if (data->delivered)
1883 g_simple_async_result_set_error (data->simple,
1885 G_IO_ERROR_TIMED_OUT,
1886 _("Timeout was reached"));
1888 send_message_with_reply_deliver (data, TRUE);
1891 CONNECTION_UNLOCK (data->connection);
1896 /* ---------------------------------------------------------------------------------------------------- */
1898 /* Called from a user thread, connection's lock is held */
1900 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1901 GDBusMessage *message,
1902 GDBusSendMessageFlags flags,
1904 volatile guint32 *out_serial,
1905 GCancellable *cancellable,
1906 GAsyncReadyCallback callback,
1909 GSimpleAsyncResult *simple;
1910 SendMessageData *data;
1912 volatile guint32 serial;
1916 if (out_serial == NULL)
1917 out_serial = &serial;
1919 if (timeout_msec == -1)
1920 timeout_msec = 25 * 1000;
1922 simple = g_simple_async_result_new (G_OBJECT (connection),
1925 g_dbus_connection_send_message_with_reply);
1927 if (g_cancellable_is_cancelled (cancellable))
1929 g_simple_async_result_set_error (simple,
1931 G_IO_ERROR_CANCELLED,
1932 _("Operation was cancelled"));
1933 g_simple_async_result_complete_in_idle (simple);
1934 g_object_unref (simple);
1939 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1941 g_simple_async_result_take_error (simple, error);
1942 g_simple_async_result_complete_in_idle (simple);
1943 g_object_unref (simple);
1947 data = g_new0 (SendMessageData, 1);
1948 data->ref_count = 1;
1949 data->connection = g_object_ref (connection);
1950 data->simple = simple;
1951 data->serial = *out_serial;
1952 data->main_context = g_main_context_ref_thread_default ();
1954 if (cancellable != NULL)
1956 data->cancellable = g_object_ref (cancellable);
1957 data->cancellable_handler_id = g_cancellable_connect (cancellable,
1958 G_CALLBACK (send_message_with_reply_cancelled_cb),
1959 send_message_data_ref (data),
1960 (GDestroyNotify) send_message_data_unref);
1961 g_object_set_data_full (G_OBJECT (simple),
1963 g_object_ref (cancellable),
1964 (GDestroyNotify) g_object_unref);
1967 if (timeout_msec != G_MAXINT)
1969 data->timeout_source = g_timeout_source_new (timeout_msec);
1970 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
1971 g_source_set_callback (data->timeout_source,
1972 send_message_with_reply_timeout_cb,
1973 send_message_data_ref (data),
1974 (GDestroyNotify) send_message_data_unref);
1975 g_source_attach (data->timeout_source, data->main_context);
1976 g_source_unref (data->timeout_source);
1979 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
1980 GUINT_TO_POINTER (*out_serial),
1988 * g_dbus_connection_send_message_with_reply:
1989 * @connection: A #GDBusConnection.
1990 * @message: A #GDBusMessage.
1991 * @flags: Flags affecting how the message is sent.
1992 * @timeout_msec: The timeout in milliseconds, -1 to use the default
1993 * timeout or %G_MAXINT for no timeout.
1994 * @out_serial: (out) (allow-none): Return location for serial number assigned
1995 * to @message when sending it or %NULL.
1996 * @cancellable: A #GCancellable or %NULL.
1997 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1998 * satisfied or %NULL if you don't care about the result.
1999 * @user_data: The data to pass to @callback.
2001 * Asynchronously sends @message to the peer represented by @connection.
2003 * Unless @flags contain the
2004 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2005 * will be assigned by @connection and set on @message via
2006 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2007 * serial number used will be written to this location prior to
2008 * submitting the message to the underlying transport.
2010 * If @connection is closed then the operation will fail with
2011 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2012 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2013 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2015 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2016 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2017 * of the thread you are calling this method from. You can then call
2018 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2019 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2021 * Note that @message must be unlocked, unless @flags contain the
2022 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2024 * See <xref linkend="gdbus-server"/> and <xref
2025 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2026 * low-level API to send and receive UNIX file descriptors.
2031 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2032 GDBusMessage *message,
2033 GDBusSendMessageFlags flags,
2035 volatile guint32 *out_serial,
2036 GCancellable *cancellable,
2037 GAsyncReadyCallback callback,
2040 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2041 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2042 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2043 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2045 CONNECTION_LOCK (connection);
2046 g_dbus_connection_send_message_with_reply_unlocked (connection,
2054 CONNECTION_UNLOCK (connection);
2058 * g_dbus_connection_send_message_with_reply_finish:
2059 * @connection: a #GDBusConnection
2060 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2061 * @error: Return location for error or %NULL.
2063 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2065 * Note that @error is only set if a local in-process error
2066 * occurred. That is to say that the returned #GDBusMessage object may
2067 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2068 * g_dbus_message_to_gerror() to transcode this to a #GError.
2070 * See <xref linkend="gdbus-server"/> and <xref
2071 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2072 * low-level API to send and receive UNIX file descriptors.
2074 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2079 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2083 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2084 GDBusMessage *reply;
2085 GCancellable *cancellable;
2087 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2088 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2092 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2094 if (g_simple_async_result_propagate_error (simple, error))
2097 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2098 cancellable = g_object_get_data (G_OBJECT (simple), "cancellable");
2099 if (cancellable != NULL && g_cancellable_is_cancelled (cancellable))
2101 g_object_unref (reply);
2103 g_set_error_literal (error,
2105 G_IO_ERROR_CANCELLED,
2106 _("Operation was cancelled"));
2112 /* ---------------------------------------------------------------------------------------------------- */
2117 GMainContext *context;
2119 } SendMessageSyncData;
2121 /* Called from a user thread, lock is not held */
2123 send_message_with_reply_sync_cb (GDBusConnection *connection,
2127 SendMessageSyncData *data = user_data;
2128 data->res = g_object_ref (res);
2129 g_main_loop_quit (data->loop);
2133 * g_dbus_connection_send_message_with_reply_sync:
2134 * @connection: A #GDBusConnection.
2135 * @message: A #GDBusMessage.
2136 * @flags: Flags affecting how the message is sent.
2137 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2138 * timeout or %G_MAXINT for no timeout.
2139 * @out_serial: (out) (allow-none): Return location for serial number assigned
2140 * to @message when sending it or %NULL.
2141 * @cancellable: A #GCancellable or %NULL.
2142 * @error: Return location for error or %NULL.
2144 * Synchronously sends @message to the peer represented by @connection
2145 * and blocks the calling thread until a reply is received or the
2146 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2147 * for the asynchronous version of this method.
2149 * Unless @flags contain the
2150 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2151 * will be assigned by @connection and set on @message via
2152 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2153 * serial number used will be written to this location prior to
2154 * submitting the message to the underlying transport.
2156 * If @connection is closed then the operation will fail with
2157 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2158 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2159 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2161 * Note that @error is only set if a local in-process error
2162 * occurred. That is to say that the returned #GDBusMessage object may
2163 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2164 * g_dbus_message_to_gerror() to transcode this to a #GError.
2166 * See <xref linkend="gdbus-server"/> and <xref
2167 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2168 * low-level API to send and receive UNIX file descriptors.
2170 * Note that @message must be unlocked, unless @flags contain the
2171 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2173 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2178 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2179 GDBusMessage *message,
2180 GDBusSendMessageFlags flags,
2182 volatile guint32 *out_serial,
2183 GCancellable *cancellable,
2186 SendMessageSyncData *data;
2187 GDBusMessage *reply;
2189 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2190 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2191 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2192 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2193 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2195 data = g_new0 (SendMessageSyncData, 1);
2196 data->context = g_main_context_new ();
2197 data->loop = g_main_loop_new (data->context, FALSE);
2199 g_main_context_push_thread_default (data->context);
2201 g_dbus_connection_send_message_with_reply (connection,
2207 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2209 g_main_loop_run (data->loop);
2210 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2214 g_main_context_pop_thread_default (data->context);
2216 g_main_context_unref (data->context);
2217 g_main_loop_unref (data->loop);
2218 g_object_unref (data->res);
2224 /* ---------------------------------------------------------------------------------------------------- */
2228 GDBusMessageFilterFunction func;
2235 GDBusMessageFilterFunction filter_function;
2237 GDestroyNotify user_data_free_func;
2240 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2242 on_worker_message_received (GDBusWorker *worker,
2243 GDBusMessage *message,
2246 GDBusConnection *connection;
2247 FilterCallback *filters;
2252 G_LOCK (message_bus_lock);
2253 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2256 G_UNLOCK (message_bus_lock);
2259 connection = G_DBUS_CONNECTION (user_data);
2260 g_object_ref (connection);
2261 G_UNLOCK (message_bus_lock);
2263 //g_debug ("in on_worker_message_received");
2265 g_object_ref (message);
2266 g_dbus_message_lock (message);
2268 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2270 /* First collect the set of callback functions */
2271 CONNECTION_LOCK (connection);
2272 num_filters = connection->filters->len;
2273 filters = g_new0 (FilterCallback, num_filters);
2274 for (n = 0; n < num_filters; n++)
2276 FilterData *data = connection->filters->pdata[n];
2277 filters[n].func = data->filter_function;
2278 filters[n].user_data = data->user_data;
2280 CONNECTION_UNLOCK (connection);
2282 /* then call the filters in order (without holding the lock) */
2283 for (n = 0; n < num_filters; n++)
2285 message = filters[n].func (connection,
2288 filters[n].user_data);
2289 if (message == NULL)
2291 g_dbus_message_lock (message);
2294 /* Standard dispatch unless the filter ate the message - no need to
2295 * do anything if the message was altered
2297 if (message != NULL)
2299 GDBusMessageType message_type;
2301 message_type = g_dbus_message_get_message_type (message);
2302 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2304 guint32 reply_serial;
2305 SendMessageData *send_message_data;
2307 reply_serial = g_dbus_message_get_reply_serial (message);
2308 CONNECTION_LOCK (connection);
2309 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2310 GUINT_TO_POINTER (reply_serial));
2311 if (send_message_data != NULL)
2313 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2314 send_message_data_deliver_reply_unlocked (send_message_data, message);
2318 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2320 CONNECTION_UNLOCK (connection);
2322 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2324 CONNECTION_LOCK (connection);
2325 distribute_signals (connection, message);
2326 CONNECTION_UNLOCK (connection);
2328 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2330 CONNECTION_LOCK (connection);
2331 distribute_method_call (connection, message);
2332 CONNECTION_UNLOCK (connection);
2336 if (message != NULL)
2337 g_object_unref (message);
2338 g_object_unref (connection);
2342 /* Called in GDBusWorker's thread, lock is not held */
2343 static GDBusMessage *
2344 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2345 GDBusMessage *message,
2348 GDBusConnection *connection;
2349 FilterCallback *filters;
2354 G_LOCK (message_bus_lock);
2355 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2358 G_UNLOCK (message_bus_lock);
2361 connection = G_DBUS_CONNECTION (user_data);
2362 g_object_ref (connection);
2363 G_UNLOCK (message_bus_lock);
2365 //g_debug ("in on_worker_message_about_to_be_sent");
2367 /* First collect the set of callback functions */
2368 CONNECTION_LOCK (connection);
2369 num_filters = connection->filters->len;
2370 filters = g_new0 (FilterCallback, num_filters);
2371 for (n = 0; n < num_filters; n++)
2373 FilterData *data = connection->filters->pdata[n];
2374 filters[n].func = data->filter_function;
2375 filters[n].user_data = data->user_data;
2377 CONNECTION_UNLOCK (connection);
2379 /* then call the filters in order (without holding the lock) */
2380 for (n = 0; n < num_filters; n++)
2382 g_dbus_message_lock (message);
2383 message = filters[n].func (connection,
2386 filters[n].user_data);
2387 if (message == NULL)
2391 g_object_unref (connection);
2397 /* called with connection lock held, in GDBusWorker thread */
2399 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2401 SendMessageData *data = value;
2403 if (data->delivered)
2406 g_simple_async_result_set_error (data->simple,
2409 _("The connection is closed"));
2411 /* Ask send_message_with_reply_deliver not to remove the element from the
2412 * hash table - we're in the middle of a foreach; that would be unsafe.
2413 * Instead, return TRUE from this function so that it gets removed safely.
2415 send_message_with_reply_deliver (data, FALSE);
2419 /* Called in GDBusWorker's thread - we must not block - without lock held */
2421 on_worker_closed (GDBusWorker *worker,
2422 gboolean remote_peer_vanished,
2426 GDBusConnection *connection;
2428 guint old_atomic_flags;
2430 G_LOCK (message_bus_lock);
2431 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2434 G_UNLOCK (message_bus_lock);
2437 connection = G_DBUS_CONNECTION (user_data);
2438 g_object_ref (connection);
2439 G_UNLOCK (message_bus_lock);
2441 //g_debug ("in on_worker_closed: %s", error->message);
2443 CONNECTION_LOCK (connection);
2444 /* Even though this is atomic, we do it inside the lock to avoid breaking
2445 * assumptions in remove_match_rule(). We'd need the lock in a moment
2446 * anyway, so, no loss.
2448 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2450 if (!(old_atomic_flags & FLAG_CLOSED))
2452 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2453 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2455 CONNECTION_UNLOCK (connection);
2457 g_object_unref (connection);
2460 /* ---------------------------------------------------------------------------------------------------- */
2462 /* Determines the biggest set of capabilities we can support on this
2465 * Called with the init_lock held.
2467 static GDBusCapabilityFlags
2468 get_offered_capabilities_max (GDBusConnection *connection)
2470 GDBusCapabilityFlags ret;
2471 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2473 if (G_IS_UNIX_CONNECTION (connection->stream))
2474 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2479 /* Called in a user thread, lock is not held */
2481 initable_init (GInitable *initable,
2482 GCancellable *cancellable,
2485 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2488 /* This method needs to be idempotent to work with the singleton
2489 * pattern. See the docs for g_initable_init(). We implement this by
2492 * Unfortunately we can't use the main lock since the on_worker_*()
2493 * callbacks above needs the lock during initialization (for message
2494 * bus connections we do a synchronous Hello() call on the bus).
2496 g_mutex_lock (&connection->init_lock);
2500 /* Make this a no-op if we're already initialized (successfully or
2503 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2505 ret = (connection->initialization_error == NULL);
2509 /* Because of init_lock, we can't get here twice in different threads */
2510 g_assert (connection->initialization_error == NULL);
2512 /* The user can pass multiple (but mutally exclusive) construct
2515 * - stream (of type GIOStream)
2516 * - address (of type gchar*)
2518 * At the end of the day we end up with a non-NULL GIOStream
2519 * object in connection->stream.
2521 if (connection->address != NULL)
2523 g_assert (connection->stream == NULL);
2525 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2526 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2528 g_set_error_literal (error,
2530 G_IO_ERROR_INVALID_ARGUMENT,
2531 _("Unsupported flags encountered when constructing a client-side connection"));
2535 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2536 NULL, /* TODO: out_guid */
2538 &connection->initialization_error);
2539 if (connection->stream == NULL)
2542 else if (connection->stream != NULL)
2548 g_assert_not_reached ();
2551 /* Authenticate the connection */
2552 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2554 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2555 g_assert (connection->guid != NULL);
2556 connection->auth = _g_dbus_auth_new (connection->stream);
2557 if (!_g_dbus_auth_run_server (connection->auth,
2558 connection->authentication_observer,
2560 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2561 get_offered_capabilities_max (connection),
2562 &connection->capabilities,
2563 &connection->credentials,
2565 &connection->initialization_error))
2568 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2570 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2571 g_assert (connection->guid == NULL);
2572 connection->auth = _g_dbus_auth_new (connection->stream);
2573 connection->guid = _g_dbus_auth_run_client (connection->auth,
2574 get_offered_capabilities_max (connection),
2575 &connection->capabilities,
2577 &connection->initialization_error);
2578 if (connection->guid == NULL)
2582 if (connection->authentication_observer != NULL)
2584 g_object_unref (connection->authentication_observer);
2585 connection->authentication_observer = NULL;
2588 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2590 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2593 /* We want all IO operations to be non-blocking since they happen in
2594 * the worker thread which is shared by _all_ connections.
2596 if (G_IS_SOCKET_CONNECTION (connection->stream))
2598 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2602 G_LOCK (message_bus_lock);
2603 if (alive_connections == NULL)
2604 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2605 g_hash_table_insert (alive_connections, connection, connection);
2606 G_UNLOCK (message_bus_lock);
2608 connection->worker = _g_dbus_worker_new (connection->stream,
2609 connection->capabilities,
2610 (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING),
2611 on_worker_message_received,
2612 on_worker_message_about_to_be_sent,
2616 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2617 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2619 GVariant *hello_result;
2621 /* we could lift this restriction by adding code in gdbusprivate.c */
2622 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2624 g_set_error_literal (&connection->initialization_error,
2627 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2631 hello_result = g_dbus_connection_call_sync (connection,
2632 "org.freedesktop.DBus", /* name */
2633 "/org/freedesktop/DBus", /* path */
2634 "org.freedesktop.DBus", /* interface */
2636 NULL, /* parameters */
2637 G_VARIANT_TYPE ("(s)"),
2638 CALL_FLAGS_INITIALIZING,
2640 NULL, /* TODO: cancellable */
2641 &connection->initialization_error);
2642 if (hello_result == NULL)
2645 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2646 g_variant_unref (hello_result);
2647 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2654 g_assert (connection->initialization_error != NULL);
2655 g_propagate_error (error, g_error_copy (connection->initialization_error));
2658 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2659 g_mutex_unlock (&connection->init_lock);
2665 initable_iface_init (GInitableIface *initable_iface)
2667 initable_iface->init = initable_init;
2670 /* ---------------------------------------------------------------------------------------------------- */
2673 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2678 /* ---------------------------------------------------------------------------------------------------- */
2681 * g_dbus_connection_new:
2682 * @stream: A #GIOStream.
2683 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2684 * @flags: Flags describing how to make the connection.
2685 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2686 * @cancellable: A #GCancellable or %NULL.
2687 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2688 * @user_data: The data to pass to @callback.
2690 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2691 * with the end represented by @stream.
2693 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2694 * will be put into non-blocking mode.
2696 * The D-Bus connection will interact with @stream from a worker thread.
2697 * As a result, the caller should not interact with @stream after this
2698 * method has been called, except by calling g_object_unref() on it.
2700 * If @observer is not %NULL it may be used to control the
2701 * authentication process.
2703 * When the operation is finished, @callback will be invoked. You can
2704 * then call g_dbus_connection_new_finish() to get the result of the
2707 * This is a asynchronous failable constructor. See
2708 * g_dbus_connection_new_sync() for the synchronous
2714 g_dbus_connection_new (GIOStream *stream,
2716 GDBusConnectionFlags flags,
2717 GDBusAuthObserver *observer,
2718 GCancellable *cancellable,
2719 GAsyncReadyCallback callback,
2722 g_return_if_fail (G_IS_IO_STREAM (stream));
2723 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2731 "authentication-observer", observer,
2736 * g_dbus_connection_new_finish:
2737 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2738 * @error: Return location for error or %NULL.
2740 * Finishes an operation started with g_dbus_connection_new().
2742 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2747 g_dbus_connection_new_finish (GAsyncResult *res,
2751 GObject *source_object;
2753 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2754 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2756 source_object = g_async_result_get_source_object (res);
2757 g_assert (source_object != NULL);
2758 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2761 g_object_unref (source_object);
2763 return G_DBUS_CONNECTION (object);
2769 * g_dbus_connection_new_sync:
2770 * @stream: A #GIOStream.
2771 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2772 * @flags: Flags describing how to make the connection.
2773 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2774 * @cancellable: A #GCancellable or %NULL.
2775 * @error: Return location for error or %NULL.
2777 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2778 * with the end represented by @stream.
2780 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2781 * will be put into non-blocking mode.
2783 * The D-Bus connection will interact with @stream from a worker thread.
2784 * As a result, the caller should not interact with @stream after this
2785 * method has been called, except by calling g_object_unref() on it.
2787 * If @observer is not %NULL it may be used to control the
2788 * authentication process.
2790 * This is a synchronous failable constructor. See
2791 * g_dbus_connection_new() for the asynchronous version.
2793 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2798 g_dbus_connection_new_sync (GIOStream *stream,
2800 GDBusConnectionFlags flags,
2801 GDBusAuthObserver *observer,
2802 GCancellable *cancellable,
2805 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2806 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2807 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2813 "authentication-observer", observer,
2817 /* ---------------------------------------------------------------------------------------------------- */
2820 * g_dbus_connection_new_for_address:
2821 * @address: A D-Bus address.
2822 * @flags: Flags describing how to make the connection.
2823 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2824 * @cancellable: A #GCancellable or %NULL.
2825 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2826 * @user_data: The data to pass to @callback.
2828 * Asynchronously connects and sets up a D-Bus client connection for
2829 * exchanging D-Bus messages with an endpoint specified by @address
2830 * which must be in the D-Bus address format.
2832 * This constructor can only be used to initiate client-side
2833 * connections - use g_dbus_connection_new() if you need to act as the
2834 * server. In particular, @flags cannot contain the
2835 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2836 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2838 * When the operation is finished, @callback will be invoked. You can
2839 * then call g_dbus_connection_new_finish() to get the result of the
2842 * If @observer is not %NULL it may be used to control the
2843 * authentication process.
2845 * This is a asynchronous failable constructor. See
2846 * g_dbus_connection_new_for_address_sync() for the synchronous
2852 g_dbus_connection_new_for_address (const gchar *address,
2853 GDBusConnectionFlags flags,
2854 GDBusAuthObserver *observer,
2855 GCancellable *cancellable,
2856 GAsyncReadyCallback callback,
2859 g_return_if_fail (address != NULL);
2860 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2867 "authentication-observer", observer,
2872 * g_dbus_connection_new_for_address_finish:
2873 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2874 * @error: Return location for error or %NULL.
2876 * Finishes an operation started with g_dbus_connection_new_for_address().
2878 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2883 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2887 GObject *source_object;
2889 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2890 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2892 source_object = g_async_result_get_source_object (res);
2893 g_assert (source_object != NULL);
2894 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2897 g_object_unref (source_object);
2899 return G_DBUS_CONNECTION (object);
2905 * g_dbus_connection_new_for_address_sync:
2906 * @address: A D-Bus address.
2907 * @flags: Flags describing how to make the connection.
2908 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2909 * @cancellable: A #GCancellable or %NULL.
2910 * @error: Return location for error or %NULL.
2912 * Synchronously connects and sets up a D-Bus client connection for
2913 * exchanging D-Bus messages with an endpoint specified by @address
2914 * which must be in the D-Bus address format.
2916 * This constructor can only be used to initiate client-side
2917 * connections - use g_dbus_connection_new_sync() if you need to act
2918 * as the server. In particular, @flags cannot contain the
2919 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2920 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2922 * This is a synchronous failable constructor. See
2923 * g_dbus_connection_new_for_address() for the asynchronous version.
2925 * If @observer is not %NULL it may be used to control the
2926 * authentication process.
2928 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2933 g_dbus_connection_new_for_address_sync (const gchar *address,
2934 GDBusConnectionFlags flags,
2935 GDBusAuthObserver *observer,
2936 GCancellable *cancellable,
2939 g_return_val_if_fail (address != NULL, NULL);
2940 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2941 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2946 "authentication-observer", observer,
2950 /* ---------------------------------------------------------------------------------------------------- */
2953 * g_dbus_connection_set_exit_on_close:
2954 * @connection: A #GDBusConnection.
2955 * @exit_on_close: Whether the process should be terminated
2956 * when @connection is closed by the remote peer.
2958 * Sets whether the process should be terminated when @connection is
2959 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2962 * Note that this function should be used with care. Most modern UNIX
2963 * desktops tie the notion of a user session the session bus, and expect
2964 * all of a users applications to quit when their bus connection goes away.
2965 * If you are setting @exit_on_close to %FALSE for the shared session
2966 * bus connection, you should make sure that your application exits
2967 * when the user session ends.
2972 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
2973 gboolean exit_on_close)
2975 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2978 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
2980 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
2985 * g_dbus_connection_get_exit_on_close:
2986 * @connection: A #GDBusConnection.
2988 * Gets whether the process is terminated when @connection is
2989 * closed by the remote peer. See
2990 * #GDBusConnection:exit-on-close for more details.
2992 * Returns: Whether the process is terminated when @connection is
2993 * closed by the remote peer.
2998 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3000 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3002 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3009 * g_dbus_connection_get_guid:
3010 * @connection: A #GDBusConnection.
3012 * The GUID of the peer performing the role of server when
3013 * authenticating. See #GDBusConnection:guid for more details.
3015 * Returns: The GUID. Do not free this string, it is owned by
3021 g_dbus_connection_get_guid (GDBusConnection *connection)
3023 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3024 return connection->guid;
3028 * g_dbus_connection_get_unique_name:
3029 * @connection: A #GDBusConnection.
3031 * Gets the unique name of @connection as assigned by the message
3032 * bus. This can also be used to figure out if @connection is a
3033 * message bus connection.
3035 * Returns: The unique name or %NULL if @connection is not a message
3036 * bus connection. Do not free this string, it is owned by
3042 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3044 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3046 /* do not use g_return_val_if_fail(), we want the memory barrier */
3047 if (!check_initialized (connection))
3050 return connection->bus_unique_name;
3054 * g_dbus_connection_get_peer_credentials:
3055 * @connection: A #GDBusConnection.
3057 * Gets the credentials of the authenticated peer. This will always
3058 * return %NULL unless @connection acted as a server
3059 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3060 * when set up and the client passed credentials as part of the
3061 * authentication process.
3063 * In a message bus setup, the message bus is always the server and
3064 * each application is a client. So this method will always return
3065 * %NULL for message bus clients.
3067 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3068 * this object, it is owned by @connection.
3073 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3075 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3077 /* do not use g_return_val_if_fail(), we want the memory barrier */
3078 if (!check_initialized (connection))
3081 return connection->credentials;
3084 /* ---------------------------------------------------------------------------------------------------- */
3086 static guint _global_filter_id = 1;
3089 * g_dbus_connection_add_filter:
3090 * @connection: A #GDBusConnection.
3091 * @filter_function: A filter function.
3092 * @user_data: User data to pass to @filter_function.
3093 * @user_data_free_func: Function to free @user_data with when filter
3094 * is removed or %NULL.
3096 * Adds a message filter. Filters are handlers that are run on all
3097 * incoming and outgoing messages, prior to standard dispatch. Filters
3098 * are run in the order that they were added. The same handler can be
3099 * added as a filter more than once, in which case it will be run more
3100 * than once. Filters added during a filter callback won't be run on
3101 * the message being processed. Filter functions are allowed to modify
3102 * and even drop messages.
3104 * Note that filters are run in a dedicated message handling thread so
3105 * they can't block and, generally, can't do anything but signal a
3106 * worker thread. Also note that filters are rarely needed - use API
3107 * such as g_dbus_connection_send_message_with_reply(),
3108 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3110 * If a filter consumes an incoming message the message is not
3111 * dispatched anywhere else - not even the standard dispatch machinery
3112 * (that API such as g_dbus_connection_signal_subscribe() and
3113 * g_dbus_connection_send_message_with_reply() relies on) will see the
3114 * message. Similary, if a filter consumes an outgoing message, the
3115 * message will not be sent to the other peer.
3117 * Returns: A filter identifier that can be used with
3118 * g_dbus_connection_remove_filter().
3123 g_dbus_connection_add_filter (GDBusConnection *connection,
3124 GDBusMessageFilterFunction filter_function,
3126 GDestroyNotify user_data_free_func)
3130 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3131 g_return_val_if_fail (filter_function != NULL, 0);
3132 g_return_val_if_fail (check_initialized (connection), 0);
3134 CONNECTION_LOCK (connection);
3135 data = g_new0 (FilterData, 1);
3136 data->id = _global_filter_id++; /* TODO: overflow etc. */
3137 data->filter_function = filter_function;
3138 data->user_data = user_data;
3139 data->user_data_free_func = user_data_free_func;
3140 g_ptr_array_add (connection->filters, data);
3141 CONNECTION_UNLOCK (connection);
3146 /* only called from finalize(), removes all filters */
3148 purge_all_filters (GDBusConnection *connection)
3151 for (n = 0; n < connection->filters->len; n++)
3153 FilterData *data = connection->filters->pdata[n];
3154 if (data->user_data_free_func != NULL)
3155 data->user_data_free_func (data->user_data);
3161 * g_dbus_connection_remove_filter:
3162 * @connection: a #GDBusConnection
3163 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3170 g_dbus_connection_remove_filter (GDBusConnection *connection,
3174 FilterData *to_destroy;
3176 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3177 g_return_if_fail (check_initialized (connection));
3179 CONNECTION_LOCK (connection);
3181 for (n = 0; n < connection->filters->len; n++)
3183 FilterData *data = connection->filters->pdata[n];
3184 if (data->id == filter_id)
3186 g_ptr_array_remove_index (connection->filters, n);
3191 CONNECTION_UNLOCK (connection);
3193 /* do free without holding lock */
3194 if (to_destroy != NULL)
3196 if (to_destroy->user_data_free_func != NULL)
3197 to_destroy->user_data_free_func (to_destroy->user_data);
3198 g_free (to_destroy);
3202 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3206 /* ---------------------------------------------------------------------------------------------------- */
3212 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3213 gchar *interface_name;
3217 GArray *subscribers;
3222 GDBusSignalCallback callback;
3224 GDestroyNotify user_data_free_func;
3226 GMainContext *context;
3230 signal_data_free (SignalData *signal_data)
3232 g_free (signal_data->rule);
3233 g_free (signal_data->sender);
3234 g_free (signal_data->sender_unique_name);
3235 g_free (signal_data->interface_name);
3236 g_free (signal_data->member);
3237 g_free (signal_data->object_path);
3238 g_free (signal_data->arg0);
3239 g_array_free (signal_data->subscribers, TRUE);
3240 g_free (signal_data);
3244 args_to_rule (const gchar *sender,
3245 const gchar *interface_name,
3246 const gchar *member,
3247 const gchar *object_path,
3253 rule = g_string_new ("type='signal'");
3255 g_string_prepend_c (rule, '-');
3257 g_string_append_printf (rule, ",sender='%s'", sender);
3258 if (interface_name != NULL)
3259 g_string_append_printf (rule, ",interface='%s'", interface_name);
3261 g_string_append_printf (rule, ",member='%s'", member);
3262 if (object_path != NULL)
3263 g_string_append_printf (rule, ",path='%s'", object_path);
3265 g_string_append_printf (rule, ",arg0='%s'", arg0);
3267 return g_string_free (rule, FALSE);
3270 static guint _global_subscriber_id = 1;
3271 static guint _global_registration_id = 1;
3272 static guint _global_subtree_registration_id = 1;
3274 /* ---------------------------------------------------------------------------------------------------- */
3276 /* Called in a user thread, lock is held */
3278 add_match_rule (GDBusConnection *connection,
3279 const gchar *match_rule)
3282 GDBusMessage *message;
3284 if (match_rule[0] == '-')
3287 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3288 "/org/freedesktop/DBus", /* path */
3289 "org.freedesktop.DBus", /* interface */
3291 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3293 if (!g_dbus_connection_send_message_unlocked (connection,
3295 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3299 g_critical ("Error while sending AddMatch() message: %s", error->message);
3300 g_error_free (error);
3302 g_object_unref (message);
3305 /* ---------------------------------------------------------------------------------------------------- */
3307 /* Called in a user thread, lock is held */
3309 remove_match_rule (GDBusConnection *connection,
3310 const gchar *match_rule)
3313 GDBusMessage *message;
3315 if (match_rule[0] == '-')
3318 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3319 "/org/freedesktop/DBus", /* path */
3320 "org.freedesktop.DBus", /* interface */
3322 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3325 if (!g_dbus_connection_send_message_unlocked (connection,
3327 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3331 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3332 * critical; but we're holding the lock, and our caller checked whether
3333 * we were already closed, so we can't get that error.
3335 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3336 g_error_free (error);
3338 g_object_unref (message);
3341 /* ---------------------------------------------------------------------------------------------------- */
3344 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3346 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3347 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3348 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3349 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3350 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3353 /* ---------------------------------------------------------------------------------------------------- */
3356 * g_dbus_connection_signal_subscribe:
3357 * @connection: A #GDBusConnection.
3358 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3359 * or %NULL to listen from all senders.
3360 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3361 * match on all interfaces.
3362 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3363 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3364 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3365 * to match on all kinds of arguments.
3366 * @flags: Flags describing how to subscribe to the signal (currently unused).
3367 * @callback: Callback to invoke when there is a signal matching the requested data.
3368 * @user_data: User data to pass to @callback.
3369 * @user_data_free_func: (allow-none): Function to free @user_data with when
3370 * subscription is removed or %NULL.
3372 * Subscribes to signals on @connection and invokes @callback with a
3373 * whenever the signal is received. Note that @callback
3374 * will be invoked in the <link
3375 * linkend="g-main-context-push-thread-default">thread-default main
3376 * loop</link> of the thread you are calling this method from.
3378 * If @connection is not a message bus connection, @sender must be
3381 * If @sender is a well-known name note that @callback is invoked with
3382 * the unique name for the owner of @sender, not the well-known name
3383 * as one would expect. This is because the message bus rewrites the
3384 * name. As such, to avoid certain race conditions, users should be
3385 * tracking the name owner of the well-known name and use that when
3386 * processing the received signal.
3388 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3393 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3394 const gchar *sender,
3395 const gchar *interface_name,
3396 const gchar *member,
3397 const gchar *object_path,
3399 GDBusSignalFlags flags,
3400 GDBusSignalCallback callback,
3402 GDestroyNotify user_data_free_func)
3405 SignalData *signal_data;
3406 SignalSubscriber subscriber;
3407 GPtrArray *signal_data_array;
3408 const gchar *sender_unique_name;
3410 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3411 * an OOM condition. We might want to change that but that would involve making
3412 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3413 * handle that. And there's really no sensible way of handling this short of retrying
3414 * to add the match rule... and then there's the little thing that, hey, maybe there's
3415 * a reason the bus in an OOM condition.
3417 * Doable, but not really sure it's worth it...
3420 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3421 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3422 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3423 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3424 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3425 g_return_val_if_fail (callback != NULL, 0);
3426 g_return_val_if_fail (check_initialized (connection), 0);
3428 CONNECTION_LOCK (connection);
3430 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3431 * with a '-' character to prefix the rule (which will otherwise be
3434 * This allows us to hash the rule and do our lifecycle tracking in
3435 * the usual way, but the '-' prevents the match rule from ever
3436 * actually being send to the bus (either for add or remove).
3438 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3439 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3441 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3442 sender_unique_name = sender;
3444 sender_unique_name = "";
3446 subscriber.callback = callback;
3447 subscriber.user_data = user_data;
3448 subscriber.user_data_free_func = user_data_free_func;
3449 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3450 subscriber.context = g_main_context_ref_thread_default ();
3452 /* see if we've already have this rule */
3453 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3454 if (signal_data != NULL)
3456 g_array_append_val (signal_data->subscribers, subscriber);
3461 signal_data = g_new0 (SignalData, 1);
3462 signal_data->rule = rule;
3463 signal_data->sender = g_strdup (sender);
3464 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3465 signal_data->interface_name = g_strdup (interface_name);
3466 signal_data->member = g_strdup (member);
3467 signal_data->object_path = g_strdup (object_path);
3468 signal_data->arg0 = g_strdup (arg0);
3469 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3470 g_array_append_val (signal_data->subscribers, subscriber);
3472 g_hash_table_insert (connection->map_rule_to_signal_data,
3476 /* Add the match rule to the bus...
3478 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3479 * always send such messages to us.
3481 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3483 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3484 add_match_rule (connection, signal_data->rule);
3487 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3488 signal_data->sender_unique_name);
3489 if (signal_data_array == NULL)
3491 signal_data_array = g_ptr_array_new ();
3492 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3493 g_strdup (signal_data->sender_unique_name),
3496 g_ptr_array_add (signal_data_array, signal_data);
3499 g_hash_table_insert (connection->map_id_to_signal_data,
3500 GUINT_TO_POINTER (subscriber.id),
3503 CONNECTION_UNLOCK (connection);
3505 return subscriber.id;
3508 /* ---------------------------------------------------------------------------------------------------- */
3510 /* called in any thread */
3511 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3513 unsubscribe_id_internal (GDBusConnection *connection,
3514 guint subscription_id,
3515 GArray *out_removed_subscribers)
3517 SignalData *signal_data;
3518 GPtrArray *signal_data_array;
3521 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3522 GUINT_TO_POINTER (subscription_id));
3523 if (signal_data == NULL)
3525 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3529 for (n = 0; n < signal_data->subscribers->len; n++)
3531 SignalSubscriber *subscriber;
3533 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3534 if (subscriber->id != subscription_id)
3537 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3538 GUINT_TO_POINTER (subscription_id)));
3539 g_array_append_val (out_removed_subscribers, *subscriber);
3540 g_array_remove_index (signal_data->subscribers, n);
3542 if (signal_data->subscribers->len == 0)
3544 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3546 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3547 signal_data->sender_unique_name);
3548 g_warn_if_fail (signal_data_array != NULL);
3549 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3551 if (signal_data_array->len == 0)
3553 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3554 signal_data->sender_unique_name));
3557 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3558 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3559 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3560 !g_dbus_connection_is_closed (connection) &&
3561 !connection->finalizing)
3563 /* The check for g_dbus_connection_is_closed() means that
3564 * sending the RemoveMatch message can't fail with
3565 * G_IO_ERROR_CLOSED, because we're holding the lock,
3566 * so on_worker_closed() can't happen between the check we just
3567 * did, and releasing the lock later.
3569 remove_match_rule (connection, signal_data->rule);
3572 signal_data_free (signal_data);
3578 g_assert_not_reached ();
3585 * g_dbus_connection_signal_unsubscribe:
3586 * @connection: A #GDBusConnection.
3587 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3589 * Unsubscribes from signals.
3594 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3595 guint subscription_id)
3597 GArray *subscribers;
3600 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3601 g_return_if_fail (check_initialized (connection));
3603 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3605 CONNECTION_LOCK (connection);
3606 unsubscribe_id_internal (connection,
3609 CONNECTION_UNLOCK (connection);
3612 g_assert (subscribers->len == 0 || subscribers->len == 1);
3614 /* call GDestroyNotify without lock held */
3615 for (n = 0; n < subscribers->len; n++)
3617 SignalSubscriber *subscriber;
3618 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3619 call_destroy_notify (subscriber->context,
3620 subscriber->user_data_free_func,
3621 subscriber->user_data);
3622 g_main_context_unref (subscriber->context);
3625 g_array_free (subscribers, TRUE);
3628 /* ---------------------------------------------------------------------------------------------------- */
3632 guint subscription_id;
3633 GDBusSignalCallback callback;
3635 GDBusMessage *message;
3636 GDBusConnection *connection;
3637 const gchar *sender;
3639 const gchar *interface;
3640 const gchar *member;
3643 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3647 emit_signal_instance_in_idle_cb (gpointer data)
3649 SignalInstance *signal_instance = data;
3650 GVariant *parameters;
3651 gboolean has_subscription;
3653 parameters = g_dbus_message_get_body (signal_instance->message);
3654 if (parameters == NULL)
3656 parameters = g_variant_new ("()");
3657 g_variant_ref_sink (parameters);
3661 g_variant_ref_sink (parameters);
3665 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3666 signal_instance->subscription_id,
3667 signal_instance->sender,
3668 signal_instance->path,
3669 signal_instance->interface,
3670 signal_instance->member,
3671 g_variant_print (parameters, TRUE));
3674 /* Careful here, don't do the callback if we no longer has the subscription */
3675 CONNECTION_LOCK (signal_instance->connection);
3676 has_subscription = FALSE;
3677 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3678 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3679 has_subscription = TRUE;
3680 CONNECTION_UNLOCK (signal_instance->connection);
3682 if (has_subscription)
3683 signal_instance->callback (signal_instance->connection,
3684 signal_instance->sender,
3685 signal_instance->path,
3686 signal_instance->interface,
3687 signal_instance->member,
3689 signal_instance->user_data);
3691 g_variant_unref (parameters);
3697 signal_instance_free (SignalInstance *signal_instance)
3699 g_object_unref (signal_instance->message);
3700 g_object_unref (signal_instance->connection);
3701 g_free (signal_instance);
3704 /* called in GDBusWorker thread WITH lock held */
3706 schedule_callbacks (GDBusConnection *connection,
3707 GPtrArray *signal_data_array,
3708 GDBusMessage *message,
3709 const gchar *sender)
3712 const gchar *interface;
3713 const gchar *member;
3722 interface = g_dbus_message_get_interface (message);
3723 member = g_dbus_message_get_member (message);
3724 path = g_dbus_message_get_path (message);
3725 arg0 = g_dbus_message_get_arg0 (message);
3728 g_print ("In schedule_callbacks:\n"
3730 " interface = `%s'\n"
3741 /* TODO: if this is slow, then we can change signal_data_array into
3742 * map_object_path_to_signal_data_array or something.
3744 for (n = 0; n < signal_data_array->len; n++)
3746 SignalData *signal_data = signal_data_array->pdata[n];
3748 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3751 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3754 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3757 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3760 for (m = 0; m < signal_data->subscribers->len; m++)
3762 SignalSubscriber *subscriber;
3763 GSource *idle_source;
3764 SignalInstance *signal_instance;
3766 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3768 signal_instance = g_new0 (SignalInstance, 1);
3769 signal_instance->subscription_id = subscriber->id;
3770 signal_instance->callback = subscriber->callback;
3771 signal_instance->user_data = subscriber->user_data;
3772 signal_instance->message = g_object_ref (message);
3773 signal_instance->connection = g_object_ref (connection);
3774 signal_instance->sender = sender;
3775 signal_instance->path = path;
3776 signal_instance->interface = interface;
3777 signal_instance->member = member;
3779 idle_source = g_idle_source_new ();
3780 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3781 g_source_set_callback (idle_source,
3782 emit_signal_instance_in_idle_cb,
3784 (GDestroyNotify) signal_instance_free);
3785 g_source_attach (idle_source, subscriber->context);
3786 g_source_unref (idle_source);
3791 /* called in GDBusWorker thread with lock held */
3793 distribute_signals (GDBusConnection *connection,
3794 GDBusMessage *message)
3796 GPtrArray *signal_data_array;
3797 const gchar *sender;
3799 sender = g_dbus_message_get_sender (message);
3801 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3803 _g_dbus_debug_print_lock ();
3804 g_print ("========================================================================\n"
3805 "GDBus-debug:Signal:\n"
3806 " <<<< RECEIVED SIGNAL %s.%s\n"
3808 " sent by name %s\n",
3809 g_dbus_message_get_interface (message),
3810 g_dbus_message_get_member (message),
3811 g_dbus_message_get_path (message),
3812 sender != NULL ? sender : "(none)");
3813 _g_dbus_debug_print_unlock ();
3816 /* collect subscribers that match on sender */
3819 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3820 if (signal_data_array != NULL)
3821 schedule_callbacks (connection, signal_data_array, message, sender);
3824 /* collect subscribers not matching on sender */
3825 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3826 if (signal_data_array != NULL)
3827 schedule_callbacks (connection, signal_data_array, message, sender);
3830 /* ---------------------------------------------------------------------------------------------------- */
3832 /* only called from finalize(), removes all subscriptions */
3834 purge_all_signal_subscriptions (GDBusConnection *connection)
3836 GHashTableIter iter;
3839 GArray *subscribers;
3842 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3843 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3844 while (g_hash_table_iter_next (&iter, &key, NULL))
3846 guint subscription_id = GPOINTER_TO_UINT (key);
3847 g_array_append_val (ids, subscription_id);
3850 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3851 for (n = 0; n < ids->len; n++)
3853 guint subscription_id = g_array_index (ids, guint, n);
3854 unsubscribe_id_internal (connection,
3858 g_array_free (ids, TRUE);
3860 /* call GDestroyNotify without lock held */
3861 for (n = 0; n < subscribers->len; n++)
3863 SignalSubscriber *subscriber;
3864 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3865 call_destroy_notify (subscriber->context,
3866 subscriber->user_data_free_func,
3867 subscriber->user_data);
3868 g_main_context_unref (subscriber->context);
3871 g_array_free (subscribers, TRUE);
3874 /* ---------------------------------------------------------------------------------------------------- */
3876 static GDBusInterfaceVTable *
3877 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3879 /* Don't waste memory by copying padding - remember to update this
3880 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3882 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3886 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3891 /* ---------------------------------------------------------------------------------------------------- */
3893 static GDBusSubtreeVTable *
3894 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3896 /* Don't waste memory by copying padding - remember to update this
3897 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3899 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3903 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3908 /* ---------------------------------------------------------------------------------------------------- */
3910 struct ExportedObject
3913 GDBusConnection *connection;
3915 /* maps gchar* -> ExportedInterface* */
3916 GHashTable *map_if_name_to_ei;
3919 /* only called with lock held */
3921 exported_object_free (ExportedObject *eo)
3923 g_free (eo->object_path);
3924 g_hash_table_unref (eo->map_if_name_to_ei);
3933 gchar *interface_name;
3934 GDBusInterfaceVTable *vtable;
3935 GDBusInterfaceInfo *interface_info;
3937 GMainContext *context;
3939 GDestroyNotify user_data_free_func;
3940 } ExportedInterface;
3942 /* called with lock held */
3944 exported_interface_free (ExportedInterface *ei)
3946 g_dbus_interface_info_cache_release (ei->interface_info);
3947 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3949 call_destroy_notify (ei->context,
3950 ei->user_data_free_func,
3953 g_main_context_unref (ei->context);
3955 g_free (ei->interface_name);
3956 _g_dbus_interface_vtable_free (ei->vtable);
3960 /* ---------------------------------------------------------------------------------------------------- */
3962 /* Convenience function to check if @registration_id (if not zero) or
3963 * @subtree_registration_id (if not zero) has been unregistered. If
3964 * so, returns %TRUE.
3966 * May be called by any thread. Caller must *not* hold lock.
3969 has_object_been_unregistered (GDBusConnection *connection,
3970 guint registration_id,
3971 guint subtree_registration_id)
3975 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3979 CONNECTION_LOCK (connection);
3980 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
3981 GUINT_TO_POINTER (registration_id)) == NULL)
3985 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
3986 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
3990 CONNECTION_UNLOCK (connection);
3995 /* ---------------------------------------------------------------------------------------------------- */
3999 GDBusConnection *connection;
4000 GDBusMessage *message;
4002 const gchar *property_name;
4003 const GDBusInterfaceVTable *vtable;
4004 GDBusInterfaceInfo *interface_info;
4005 const GDBusPropertyInfo *property_info;
4006 guint registration_id;
4007 guint subtree_registration_id;
4011 property_data_free (PropertyData *data)
4013 g_object_unref (data->connection);
4014 g_object_unref (data->message);
4018 /* called in thread where object was registered - no locks held */
4020 invoke_get_property_in_idle_cb (gpointer _data)
4022 PropertyData *data = _data;
4025 GDBusMessage *reply;
4027 if (has_object_been_unregistered (data->connection,
4028 data->registration_id,
4029 data->subtree_registration_id))
4031 reply = g_dbus_message_new_method_error (data->message,
4032 "org.freedesktop.DBus.Error.UnknownMethod",
4033 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4034 g_dbus_message_get_path (data->message));
4035 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4036 g_object_unref (reply);
4041 value = data->vtable->get_property (data->connection,
4042 g_dbus_message_get_sender (data->message),
4043 g_dbus_message_get_path (data->message),
4044 data->interface_info->name,
4045 data->property_name,
4052 g_assert_no_error (error);
4054 g_variant_take_ref (value);
4055 reply = g_dbus_message_new_method_reply (data->message);
4056 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4057 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4058 g_variant_unref (value);
4059 g_object_unref (reply);
4063 gchar *dbus_error_name;
4064 g_assert (error != NULL);
4065 dbus_error_name = g_dbus_error_encode_gerror (error);
4066 reply = g_dbus_message_new_method_error_literal (data->message,
4069 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4070 g_free (dbus_error_name);
4071 g_error_free (error);
4072 g_object_unref (reply);
4079 /* called in thread where object was registered - no locks held */
4081 invoke_set_property_in_idle_cb (gpointer _data)
4083 PropertyData *data = _data;
4085 GDBusMessage *reply;
4091 g_variant_get (g_dbus_message_get_body (data->message),
4097 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4098 * of the given value is wrong
4100 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4102 reply = g_dbus_message_new_method_error (data->message,
4103 "org.freedesktop.DBus.Error.InvalidArgs",
4104 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4105 data->property_info->name,
4106 data->property_info->signature,
4107 g_variant_get_type_string (value));
4111 if (!data->vtable->set_property (data->connection,
4112 g_dbus_message_get_sender (data->message),
4113 g_dbus_message_get_path (data->message),
4114 data->interface_info->name,
4115 data->property_name,
4120 gchar *dbus_error_name;
4121 g_assert (error != NULL);
4122 dbus_error_name = g_dbus_error_encode_gerror (error);
4123 reply = g_dbus_message_new_method_error_literal (data->message,
4126 g_free (dbus_error_name);
4127 g_error_free (error);
4131 reply = g_dbus_message_new_method_reply (data->message);
4135 g_assert (reply != NULL);
4136 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4137 g_object_unref (reply);
4138 g_variant_unref (value);
4143 /* called in any thread with connection's lock held */
4145 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4146 GDBusMessage *message,
4147 guint registration_id,
4148 guint subtree_registration_id,
4150 GDBusInterfaceInfo *interface_info,
4151 const GDBusInterfaceVTable *vtable,
4152 GMainContext *main_context,
4156 const char *interface_name;
4157 const char *property_name;
4158 const GDBusPropertyInfo *property_info;
4159 GSource *idle_source;
4160 PropertyData *property_data;
4161 GDBusMessage *reply;
4166 g_variant_get (g_dbus_message_get_body (message),
4171 g_variant_get (g_dbus_message_get_body (message),
4180 if (vtable == NULL || vtable->get_property == NULL)
4185 if (vtable == NULL || vtable->set_property == NULL)
4189 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4191 property_info = NULL;
4193 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4194 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4195 if (property_info == NULL)
4197 reply = g_dbus_message_new_method_error (message,
4198 "org.freedesktop.DBus.Error.InvalidArgs",
4199 _("No such property `%s'"),
4201 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4202 g_object_unref (reply);
4207 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4209 reply = g_dbus_message_new_method_error (message,
4210 "org.freedesktop.DBus.Error.InvalidArgs",
4211 _("Property `%s' is not readable"),
4213 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4214 g_object_unref (reply);
4218 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4220 reply = g_dbus_message_new_method_error (message,
4221 "org.freedesktop.DBus.Error.InvalidArgs",
4222 _("Property `%s' is not writable"),
4224 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4225 g_object_unref (reply);
4230 /* ok, got the property info - call user code in an idle handler */
4231 property_data = g_new0 (PropertyData, 1);
4232 property_data->connection = g_object_ref (connection);
4233 property_data->message = g_object_ref (message);
4234 property_data->user_data = user_data;
4235 property_data->property_name = property_name;
4236 property_data->vtable = vtable;
4237 property_data->interface_info = interface_info;
4238 property_data->property_info = property_info;
4239 property_data->registration_id = registration_id;
4240 property_data->subtree_registration_id = subtree_registration_id;
4242 idle_source = g_idle_source_new ();
4243 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4244 g_source_set_callback (idle_source,
4245 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4247 (GDestroyNotify) property_data_free);
4248 g_source_attach (idle_source, main_context);
4249 g_source_unref (idle_source);
4257 /* called in GDBusWorker thread with connection's lock held */
4259 handle_getset_property (GDBusConnection *connection,
4261 GDBusMessage *message,
4264 ExportedInterface *ei;
4266 const char *interface_name;
4267 const char *property_name;
4272 g_variant_get (g_dbus_message_get_body (message),
4277 g_variant_get (g_dbus_message_get_body (message),
4283 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4284 * no such interface registered
4286 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4289 GDBusMessage *reply;
4290 reply = g_dbus_message_new_method_error (message,
4291 "org.freedesktop.DBus.Error.InvalidArgs",
4292 _("No such interface `%s'"),
4294 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4295 g_object_unref (reply);
4300 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4313 /* ---------------------------------------------------------------------------------------------------- */
4317 GDBusConnection *connection;
4318 GDBusMessage *message;
4320 const GDBusInterfaceVTable *vtable;
4321 GDBusInterfaceInfo *interface_info;
4322 guint registration_id;
4323 guint subtree_registration_id;
4324 } PropertyGetAllData;
4327 property_get_all_data_free (PropertyData *data)
4329 g_object_unref (data->connection);
4330 g_object_unref (data->message);
4334 /* called in thread where object was registered - no locks held */
4336 invoke_get_all_properties_in_idle_cb (gpointer _data)
4338 PropertyGetAllData *data = _data;
4339 GVariantBuilder builder;
4340 GDBusMessage *reply;
4343 if (has_object_been_unregistered (data->connection,
4344 data->registration_id,
4345 data->subtree_registration_id))
4347 reply = g_dbus_message_new_method_error (data->message,
4348 "org.freedesktop.DBus.Error.UnknownMethod",
4349 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4350 g_dbus_message_get_path (data->message));
4351 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4352 g_object_unref (reply);
4356 /* TODO: Right now we never fail this call - we just omit values if
4357 * a get_property() call is failing.
4359 * We could fail the whole call if just a single get_property() call
4360 * returns an error. We need clarification in the D-Bus spec about this.
4362 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4363 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4364 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4366 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4369 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4372 value = data->vtable->get_property (data->connection,
4373 g_dbus_message_get_sender (data->message),
4374 g_dbus_message_get_path (data->message),
4375 data->interface_info->name,
4376 property_info->name,
4383 g_variant_take_ref (value);
4384 g_variant_builder_add (&builder,
4386 property_info->name,
4388 g_variant_unref (value);
4390 g_variant_builder_close (&builder);
4392 reply = g_dbus_message_new_method_reply (data->message);
4393 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4394 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4395 g_object_unref (reply);
4401 /* called in any thread with connection's lock held */
4403 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4404 GDBusMessage *message,
4405 guint registration_id,
4406 guint subtree_registration_id,
4407 GDBusInterfaceInfo *interface_info,
4408 const GDBusInterfaceVTable *vtable,
4409 GMainContext *main_context,
4413 const char *interface_name;
4414 GSource *idle_source;
4415 PropertyGetAllData *property_get_all_data;
4419 g_variant_get (g_dbus_message_get_body (message),
4423 if (vtable == NULL || vtable->get_property == NULL)
4426 /* ok, got the property info - call user in an idle handler */
4427 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4428 property_get_all_data->connection = g_object_ref (connection);
4429 property_get_all_data->message = g_object_ref (message);
4430 property_get_all_data->user_data = user_data;
4431 property_get_all_data->vtable = vtable;
4432 property_get_all_data->interface_info = interface_info;
4433 property_get_all_data->registration_id = registration_id;
4434 property_get_all_data->subtree_registration_id = subtree_registration_id;
4436 idle_source = g_idle_source_new ();
4437 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4438 g_source_set_callback (idle_source,
4439 invoke_get_all_properties_in_idle_cb,
4440 property_get_all_data,
4441 (GDestroyNotify) property_get_all_data_free);
4442 g_source_attach (idle_source, main_context);
4443 g_source_unref (idle_source);
4451 /* called in GDBusWorker thread with connection's lock held */
4453 handle_get_all_properties (GDBusConnection *connection,
4455 GDBusMessage *message)
4457 ExportedInterface *ei;
4459 const char *interface_name;
4463 g_variant_get (g_dbus_message_get_body (message),
4467 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4468 * no such interface registered
4470 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4473 GDBusMessage *reply;
4474 reply = g_dbus_message_new_method_error (message,
4475 "org.freedesktop.DBus.Error.InvalidArgs",
4476 _("No such interface"),
4478 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4479 g_object_unref (reply);
4484 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4496 /* ---------------------------------------------------------------------------------------------------- */
4498 static const gchar introspect_header[] =
4499 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4500 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4501 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4504 static const gchar introspect_tail[] =
4507 static const gchar introspect_properties_interface[] =
4508 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4509 " <method name=\"Get\">\n"
4510 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4511 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4512 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4514 " <method name=\"GetAll\">\n"
4515 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4516 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4518 " <method name=\"Set\">\n"
4519 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4520 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4521 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4523 " <signal name=\"PropertiesChanged\">\n"
4524 " <arg type=\"s\" name=\"interface_name\"/>\n"
4525 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4526 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4530 static const gchar introspect_introspectable_interface[] =
4531 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4532 " <method name=\"Introspect\">\n"
4533 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4536 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4537 " <method name=\"Ping\"/>\n"
4538 " <method name=\"GetMachineId\">\n"
4539 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4544 introspect_append_header (GString *s)
4546 g_string_append (s, introspect_header);
4550 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4552 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4558 begin = object_path + path_len;
4559 end = strchr (begin, '/');
4561 s = g_strndup (begin, end - begin);
4563 s = g_strdup (begin);
4565 if (g_hash_table_lookup (set, s) == NULL)
4566 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4572 /* TODO: we want a nicer public interface for this */
4573 /* called in any thread with connection's lock held */
4575 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4580 GHashTableIter hash_iter;
4581 const gchar *object_path;
4587 CONNECTION_ENSURE_LOCK (connection);
4589 path_len = strlen (path);
4593 set = g_hash_table_new (g_str_hash, g_str_equal);
4595 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4596 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4597 maybe_add_path (path, path_len, object_path, set);
4599 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4600 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4601 maybe_add_path (path, path_len, object_path, set);
4603 p = g_ptr_array_new ();
4604 keys = g_hash_table_get_keys (set);
4605 for (l = keys; l != NULL; l = l->next)
4606 g_ptr_array_add (p, l->data);
4607 g_hash_table_unref (set);
4610 g_ptr_array_add (p, NULL);
4611 ret = (gchar **) g_ptr_array_free (p, FALSE);
4615 /* called in any thread with connection's lock not held */
4617 g_dbus_connection_list_registered (GDBusConnection *connection,
4621 CONNECTION_LOCK (connection);
4622 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4623 CONNECTION_UNLOCK (connection);
4627 /* called in GDBusWorker thread with connection's lock held */
4629 handle_introspect (GDBusConnection *connection,
4631 GDBusMessage *message)
4635 GDBusMessage *reply;
4636 GHashTableIter hash_iter;
4637 ExportedInterface *ei;
4640 /* first the header with the standard interfaces */
4641 s = g_string_sized_new (sizeof (introspect_header) +
4642 sizeof (introspect_properties_interface) +
4643 sizeof (introspect_introspectable_interface) +
4644 sizeof (introspect_tail));
4645 introspect_append_header (s);
4646 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4647 "org.freedesktop.DBus.Properties"))
4648 g_string_append (s, introspect_properties_interface);
4650 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4651 "org.freedesktop.DBus.Introspectable"))
4652 g_string_append (s, introspect_introspectable_interface);
4654 /* then include the registered interfaces */
4655 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4656 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4657 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4659 /* finally include nodes registered below us */
4660 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4661 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4662 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4663 g_strfreev (registered);
4664 g_string_append (s, introspect_tail);
4666 reply = g_dbus_message_new_method_reply (message);
4667 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4668 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4669 g_object_unref (reply);
4670 g_string_free (s, TRUE);
4675 /* called in thread where object was registered - no locks held */
4677 call_in_idle_cb (gpointer user_data)
4679 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4680 GDBusInterfaceVTable *vtable;
4681 guint registration_id;
4682 guint subtree_registration_id;
4684 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4685 g_assert (vtable != NULL && vtable->method_call != NULL);
4687 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4688 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4690 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4692 subtree_registration_id))
4694 GDBusMessage *reply;
4695 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4696 "org.freedesktop.DBus.Error.UnknownMethod",
4697 _("No such interface `%s' on object at path %s"),
4698 g_dbus_method_invocation_get_interface_name (invocation),
4699 g_dbus_method_invocation_get_object_path (invocation));
4700 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4701 g_object_unref (reply);
4705 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4706 g_dbus_method_invocation_get_sender (invocation),
4707 g_dbus_method_invocation_get_object_path (invocation),
4708 g_dbus_method_invocation_get_interface_name (invocation),
4709 g_dbus_method_invocation_get_method_name (invocation),
4710 g_dbus_method_invocation_get_parameters (invocation),
4711 g_object_ref (invocation),
4712 g_dbus_method_invocation_get_user_data (invocation));
4718 /* called in GDBusWorker thread with connection's lock held */
4720 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4721 GDBusMessage *message,
4722 guint registration_id,
4723 guint subtree_registration_id,
4724 GDBusInterfaceInfo *interface_info,
4725 const GDBusInterfaceVTable *vtable,
4726 GMainContext *main_context,
4729 GDBusMethodInvocation *invocation;
4730 const GDBusMethodInfo *method_info;
4731 GDBusMessage *reply;
4732 GVariant *parameters;
4733 GSource *idle_source;
4735 GVariantType *in_type;
4739 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4740 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4742 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4743 * error to the caller
4745 if (method_info == NULL)
4747 reply = g_dbus_message_new_method_error (message,
4748 "org.freedesktop.DBus.Error.UnknownMethod",
4749 _("No such method `%s'"),
4750 g_dbus_message_get_member (message));
4751 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4752 g_object_unref (reply);
4757 parameters = g_dbus_message_get_body (message);
4758 if (parameters == NULL)
4760 parameters = g_variant_new ("()");
4761 g_variant_ref_sink (parameters);
4765 g_variant_ref (parameters);
4768 /* Check that the incoming args are of the right type - if they are not, return
4769 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4771 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4772 if (!g_variant_is_of_type (parameters, in_type))
4776 type_string = g_variant_type_dup_string (in_type);
4778 reply = g_dbus_message_new_method_error (message,
4779 "org.freedesktop.DBus.Error.InvalidArgs",
4780 _("Type of message, `%s', does not match expected type `%s'"),
4781 g_variant_get_type_string (parameters),
4783 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4784 g_variant_type_free (in_type);
4785 g_variant_unref (parameters);
4786 g_object_unref (reply);
4787 g_free (type_string);
4791 g_variant_type_free (in_type);
4793 /* schedule the call in idle */
4794 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4795 g_dbus_message_get_path (message),
4796 g_dbus_message_get_interface (message),
4797 g_dbus_message_get_member (message),
4803 g_variant_unref (parameters);
4805 /* TODO: would be nicer with a real MethodData like we already
4806 * have PropertyData and PropertyGetAllData... */
4807 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4808 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4809 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4811 idle_source = g_idle_source_new ();
4812 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4813 g_source_set_callback (idle_source,
4817 g_source_attach (idle_source, main_context);
4818 g_source_unref (idle_source);
4826 /* ---------------------------------------------------------------------------------------------------- */
4828 /* called in GDBusWorker thread with connection's lock held */
4830 obj_message_func (GDBusConnection *connection,
4832 GDBusMessage *message)
4834 const gchar *interface_name;
4835 const gchar *member;
4836 const gchar *signature;
4841 interface_name = g_dbus_message_get_interface (message);
4842 member = g_dbus_message_get_member (message);
4843 signature = g_dbus_message_get_signature (message);
4845 /* see if we have an interface for handling this call */
4846 if (interface_name != NULL)
4848 ExportedInterface *ei;
4849 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4852 /* we do - invoke the handler in idle in the right thread */
4854 /* handle no vtable or handler being present */
4855 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4858 handled = validate_and_maybe_schedule_method_call (connection,
4870 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4871 g_strcmp0 (member, "Introspect") == 0 &&
4872 g_strcmp0 (signature, "") == 0)
4874 handled = handle_introspect (connection, eo, message);
4877 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4878 g_strcmp0 (member, "Get") == 0 &&
4879 g_strcmp0 (signature, "ss") == 0)
4881 handled = handle_getset_property (connection, eo, message, TRUE);
4884 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4885 g_strcmp0 (member, "Set") == 0 &&
4886 g_strcmp0 (signature, "ssv") == 0)
4888 handled = handle_getset_property (connection, eo, message, FALSE);
4891 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4892 g_strcmp0 (member, "GetAll") == 0 &&
4893 g_strcmp0 (signature, "s") == 0)
4895 handled = handle_get_all_properties (connection, eo, message);
4904 * g_dbus_connection_register_object:
4905 * @connection: A #GDBusConnection.
4906 * @object_path: The object path to register at.
4907 * @interface_info: Introspection data for the interface.
4908 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4909 * @user_data: (allow-none): Data to pass to functions in @vtable.
4910 * @user_data_free_func: Function to call when the object path is unregistered.
4911 * @error: Return location for error or %NULL.
4913 * Registers callbacks for exported objects at @object_path with the
4914 * D-Bus interface that is described in @interface_info.
4916 * Calls to functions in @vtable (and @user_data_free_func) will
4917 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4918 * loop</link> of the thread you are calling this method from.
4920 * Note that all #GVariant values passed to functions in @vtable will match
4921 * the signature given in @interface_info - if a remote caller passes
4922 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4923 * is returned to the remote caller.
4925 * Additionally, if the remote caller attempts to invoke methods or
4926 * access properties not mentioned in @interface_info the
4927 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4928 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4929 * are returned to the caller.
4931 * It is considered a programming error if the
4932 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4933 * #GVariant of incorrect type.
4935 * If an existing callback is already registered at @object_path and
4936 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4938 * GDBus automatically implements the standard D-Bus interfaces
4939 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4940 * and org.freedesktop.Peer, so you don't have to implement those for
4941 * the objects you export. You <emphasis>can</emphasis> implement
4942 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4943 * and setting of properties asynchronously.
4945 * Note that the reference count on @interface_info will be
4946 * incremented by 1 (unless allocated statically, e.g. if the
4947 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4948 * as the object is exported. Also note that @vtable will be copied.
4950 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4952 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4953 * that can be used with g_dbus_connection_unregister_object() .
4958 g_dbus_connection_register_object (GDBusConnection *connection,
4959 const gchar *object_path,
4960 GDBusInterfaceInfo *interface_info,
4961 const GDBusInterfaceVTable *vtable,
4963 GDestroyNotify user_data_free_func,
4967 ExportedInterface *ei;
4970 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
4971 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
4972 g_return_val_if_fail (interface_info != NULL, 0);
4973 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
4974 g_return_val_if_fail (error == NULL || *error == NULL, 0);
4975 g_return_val_if_fail (check_initialized (connection), 0);
4979 CONNECTION_LOCK (connection);
4981 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
4984 eo = g_new0 (ExportedObject, 1);
4985 eo->object_path = g_strdup (object_path);
4986 eo->connection = connection;
4987 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
4990 (GDestroyNotify) exported_interface_free);
4991 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
4994 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5000 _("An object is already exported for the interface %s at %s"),
5001 interface_info->name,
5006 ei = g_new0 (ExportedInterface, 1);
5007 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5009 ei->user_data = user_data;
5010 ei->user_data_free_func = user_data_free_func;
5011 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5012 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5013 g_dbus_interface_info_cache_build (ei->interface_info);
5014 ei->interface_name = g_strdup (interface_info->name);
5015 ei->context = g_main_context_ref_thread_default ();
5017 g_hash_table_insert (eo->map_if_name_to_ei,
5018 (gpointer) ei->interface_name,
5020 g_hash_table_insert (connection->map_id_to_ei,
5021 GUINT_TO_POINTER (ei->id),
5027 CONNECTION_UNLOCK (connection);
5033 * g_dbus_connection_unregister_object:
5034 * @connection: A #GDBusConnection.
5035 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5037 * Unregisters an object.
5039 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5044 g_dbus_connection_unregister_object (GDBusConnection *connection,
5045 guint registration_id)
5047 ExportedInterface *ei;
5051 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5052 g_return_val_if_fail (check_initialized (connection), FALSE);
5056 CONNECTION_LOCK (connection);
5058 ei = g_hash_table_lookup (connection->map_id_to_ei,
5059 GUINT_TO_POINTER (registration_id));
5065 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5066 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5067 /* unregister object path if we have no more exported interfaces */
5068 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5069 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5075 CONNECTION_UNLOCK (connection);
5080 /* ---------------------------------------------------------------------------------------------------- */
5083 * g_dbus_connection_emit_signal:
5084 * @connection: A #GDBusConnection.
5085 * @destination_bus_name: (allow-none): The unique bus name for the destination
5086 * for the signal or %NULL to emit to all listeners.
5087 * @object_path: Path of remote object.
5088 * @interface_name: D-Bus interface to emit a signal on.
5089 * @signal_name: The name of the signal to emit.
5090 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5091 * or %NULL if not passing parameters.
5092 * @error: Return location for error or %NULL.
5096 * If the parameters GVariant is floating, it is consumed.
5098 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5100 * Returns: %TRUE unless @error is set.
5105 g_dbus_connection_emit_signal (GDBusConnection *connection,
5106 const gchar *destination_bus_name,
5107 const gchar *object_path,
5108 const gchar *interface_name,
5109 const gchar *signal_name,
5110 GVariant *parameters,
5113 GDBusMessage *message;
5119 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5120 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5121 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5122 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5123 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5124 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5125 g_return_val_if_fail (check_initialized (connection), FALSE);
5127 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5129 _g_dbus_debug_print_lock ();
5130 g_print ("========================================================================\n"
5131 "GDBus-debug:Emission:\n"
5132 " >>>> SIGNAL EMISSION %s.%s()\n"
5134 " destination %s\n",
5135 interface_name, signal_name,
5137 destination_bus_name != NULL ? destination_bus_name : "(none)");
5138 _g_dbus_debug_print_unlock ();
5141 message = g_dbus_message_new_signal (object_path,
5145 if (destination_bus_name != NULL)
5146 g_dbus_message_set_header (message,
5147 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5148 g_variant_new_string (destination_bus_name));
5150 if (parameters != NULL)
5151 g_dbus_message_set_body (message, parameters);
5153 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5154 g_object_unref (message);
5160 add_call_flags (GDBusMessage *message,
5161 GDBusCallFlags flags)
5163 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5164 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5168 decode_method_reply (GDBusMessage *reply,
5169 const gchar *method_name,
5170 const GVariantType *reply_type,
5171 GUnixFDList **out_fd_list,
5177 switch (g_dbus_message_get_message_type (reply))
5179 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5180 result = g_dbus_message_get_body (reply);
5183 result = g_variant_new ("()");
5184 g_variant_ref_sink (result);
5188 g_variant_ref (result);
5191 if (!g_variant_is_of_type (result, reply_type))
5193 gchar *type_string = g_variant_type_dup_string (reply_type);
5197 G_IO_ERROR_INVALID_ARGUMENT,
5198 _("Method `%s' returned type `%s', but expected `%s'"),
5199 method_name, g_variant_get_type_string (result), type_string);
5201 g_variant_unref (result);
5202 g_free (type_string);
5209 if (out_fd_list != NULL)
5211 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5212 if (*out_fd_list != NULL)
5213 g_object_ref (*out_fd_list);
5219 case G_DBUS_MESSAGE_TYPE_ERROR:
5220 g_dbus_message_to_gerror (reply, error);
5224 g_assert_not_reached ();
5234 GSimpleAsyncResult *simple;
5235 GVariantType *reply_type;
5236 gchar *method_name; /* for error message */
5240 GUnixFDList *fd_list;
5244 call_state_free (CallState *state)
5246 g_variant_type_free (state->reply_type);
5247 g_free (state->method_name);
5249 if (state->value != NULL)
5250 g_variant_unref (state->value);
5251 if (state->fd_list != NULL)
5252 g_object_unref (state->fd_list);
5253 g_slice_free (CallState, state);
5256 /* called in any thread, with the connection's lock not held */
5258 g_dbus_connection_call_done (GObject *source,
5259 GAsyncResult *result,
5262 GSimpleAsyncResult *simple;
5263 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5264 CallState *state = user_data;
5266 GDBusMessage *reply;
5269 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5273 if (G_UNLIKELY (_g_dbus_debug_call ()))
5275 _g_dbus_debug_print_lock ();
5276 g_print ("========================================================================\n"
5277 "GDBus-debug:Call:\n"
5278 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5284 g_print ("SUCCESS\n");
5288 g_print ("FAILED: %s\n",
5291 _g_dbus_debug_print_unlock ();
5295 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5297 simple = state->simple; /* why? because state is freed before we unref simple.. */
5300 g_simple_async_result_take_error (state->simple, error);
5301 g_simple_async_result_complete (state->simple);
5302 call_state_free (state);
5306 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5307 g_simple_async_result_complete (state->simple);
5308 g_object_unref (reply);
5310 g_object_unref (simple);
5313 /* called in any thread, with the connection's lock not held */
5315 g_dbus_connection_call_internal (GDBusConnection *connection,
5316 const gchar *bus_name,
5317 const gchar *object_path,
5318 const gchar *interface_name,
5319 const gchar *method_name,
5320 GVariant *parameters,
5321 const GVariantType *reply_type,
5322 GDBusCallFlags flags,
5324 GUnixFDList *fd_list,
5325 GCancellable *cancellable,
5326 GAsyncReadyCallback callback,
5329 GDBusMessage *message;
5332 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5333 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5334 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5335 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5336 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5337 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5338 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5339 g_return_if_fail (check_initialized (connection));
5341 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5343 g_return_if_fail (fd_list == NULL);
5346 state = g_slice_new0 (CallState);
5347 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5348 callback, user_data,
5349 g_dbus_connection_call_internal);
5350 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5352 if (reply_type == NULL)
5353 reply_type = G_VARIANT_TYPE_ANY;
5355 state->reply_type = g_variant_type_copy (reply_type);
5357 message = g_dbus_message_new_method_call (bus_name,
5361 add_call_flags (message, flags);
5362 if (parameters != NULL)
5363 g_dbus_message_set_body (message, parameters);
5366 if (fd_list != NULL)
5367 g_dbus_message_set_unix_fd_list (message, fd_list);
5370 g_dbus_connection_send_message_with_reply (connection,
5372 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5376 g_dbus_connection_call_done,
5379 if (G_UNLIKELY (_g_dbus_debug_call ()))
5381 _g_dbus_debug_print_lock ();
5382 g_print ("========================================================================\n"
5383 "GDBus-debug:Call:\n"
5384 " >>>> ASYNC %s.%s()\n"
5386 " owned by name %s (serial %d)\n",
5390 bus_name != NULL ? bus_name : "(none)",
5392 _g_dbus_debug_print_unlock ();
5395 if (message != NULL)
5396 g_object_unref (message);
5399 /* called in any thread, with the connection's lock not held */
5401 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5402 GUnixFDList **out_fd_list,
5406 GSimpleAsyncResult *simple;
5409 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5410 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5411 g_dbus_connection_call_internal), NULL);
5412 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5414 simple = G_SIMPLE_ASYNC_RESULT (res);
5416 if (g_simple_async_result_propagate_error (simple, error))
5419 state = g_simple_async_result_get_op_res_gpointer (simple);
5420 if (out_fd_list != NULL)
5421 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5422 return g_variant_ref (state->value);
5425 /* called in any user thread, with the connection's lock not held */
5427 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5428 const gchar *bus_name,
5429 const gchar *object_path,
5430 const gchar *interface_name,
5431 const gchar *method_name,
5432 GVariant *parameters,
5433 const GVariantType *reply_type,
5434 GDBusCallFlags flags,
5436 GUnixFDList *fd_list,
5437 GUnixFDList **out_fd_list,
5438 GCancellable *cancellable,
5441 GDBusMessage *message;
5442 GDBusMessage *reply;
5444 GError *local_error;
5445 GDBusSendMessageFlags send_flags;
5451 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5452 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5453 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5454 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5455 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5456 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5457 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5459 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5461 g_return_val_if_fail (fd_list == NULL, NULL);
5463 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5465 if (!(flags & CALL_FLAGS_INITIALIZING))
5466 g_return_val_if_fail (check_initialized (connection), FALSE);
5468 if (reply_type == NULL)
5469 reply_type = G_VARIANT_TYPE_ANY;
5471 message = g_dbus_message_new_method_call (bus_name,
5475 add_call_flags (message, flags);
5476 if (parameters != NULL)
5477 g_dbus_message_set_body (message, parameters);
5480 if (fd_list != NULL)
5481 g_dbus_message_set_unix_fd_list (message, fd_list);
5484 if (G_UNLIKELY (_g_dbus_debug_call ()))
5486 _g_dbus_debug_print_lock ();
5487 g_print ("========================================================================\n"
5488 "GDBus-debug:Call:\n"
5489 " >>>> SYNC %s.%s()\n"
5491 " owned by name %s\n",
5495 bus_name != NULL ? bus_name : "(none)");
5496 _g_dbus_debug_print_unlock ();
5501 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5503 /* translate from one flavour of flags to another... */
5504 if (flags & CALL_FLAGS_INITIALIZING)
5505 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5507 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5511 NULL, /* volatile guint32 *out_serial */
5515 if (G_UNLIKELY (_g_dbus_debug_call ()))
5517 _g_dbus_debug_print_lock ();
5518 g_print ("========================================================================\n"
5519 "GDBus-debug:Call:\n"
5520 " <<<< SYNC COMPLETE %s.%s()\n"
5526 g_print ("SUCCESS\n");
5530 g_print ("FAILED: %s\n",
5531 local_error->message);
5533 _g_dbus_debug_print_unlock ();
5539 *error = local_error;
5541 g_error_free (local_error);
5545 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5548 if (message != NULL)
5549 g_object_unref (message);
5551 g_object_unref (reply);
5556 /* ---------------------------------------------------------------------------------------------------- */
5559 * g_dbus_connection_call:
5560 * @connection: A #GDBusConnection.
5561 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5562 * @connection is not a message bus connection.
5563 * @object_path: Path of remote object.
5564 * @interface_name: D-Bus interface to invoke method on.
5565 * @method_name: The name of the method to invoke.
5566 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5567 * or %NULL if not passing parameters.
5568 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5569 * @flags: Flags from the #GDBusCallFlags enumeration.
5570 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5571 * timeout or %G_MAXINT for no timeout.
5572 * @cancellable: A #GCancellable or %NULL.
5573 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5574 * satisfied or %NULL if you don't * care about the result of the
5575 * method invocation.
5576 * @user_data: The data to pass to @callback.
5578 * Asynchronously invokes the @method_name method on the
5579 * @interface_name D-Bus interface on the remote object at
5580 * @object_path owned by @bus_name.
5582 * If @connection is closed then the operation will fail with
5583 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5584 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5585 * not compatible with the D-Bus protocol, the operation fails with
5586 * %G_IO_ERROR_INVALID_ARGUMENT.
5588 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5589 * error will be raised if it does not match. Said another way, if you give a @reply_type
5590 * then any non-%NULL return value will be of this type.
5592 * If the @parameters #GVariant is floating, it is consumed. This allows
5593 * convenient 'inline' use of g_variant_new(), e.g.:
5595 * g_dbus_connection_call (connection,
5596 * "org.freedesktop.StringThings",
5597 * "/org/freedesktop/StringThings",
5598 * "org.freedesktop.StringThings",
5600 * g_variant_new ("(ss)",
5604 * G_DBUS_CALL_FLAGS_NONE,
5607 * (GAsyncReadyCallback) two_strings_done,
5611 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5612 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5613 * of the thread you are calling this method from. You can then call
5614 * g_dbus_connection_call_finish() to get the result of the operation.
5615 * See g_dbus_connection_call_sync() for the synchronous version of this
5621 g_dbus_connection_call (GDBusConnection *connection,
5622 const gchar *bus_name,
5623 const gchar *object_path,
5624 const gchar *interface_name,
5625 const gchar *method_name,
5626 GVariant *parameters,
5627 const GVariantType *reply_type,
5628 GDBusCallFlags flags,
5630 GCancellable *cancellable,
5631 GAsyncReadyCallback callback,
5634 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);
5638 * g_dbus_connection_call_finish:
5639 * @connection: A #GDBusConnection.
5640 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5641 * @error: Return location for error or %NULL.
5643 * Finishes an operation started with g_dbus_connection_call().
5645 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5646 * return values. Free with g_variant_unref().
5651 g_dbus_connection_call_finish (GDBusConnection *connection,
5655 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5659 * g_dbus_connection_call_sync:
5660 * @connection: A #GDBusConnection.
5661 * @bus_name: A unique or well-known bus name.
5662 * @object_path: Path of remote object.
5663 * @interface_name: D-Bus interface to invoke method on.
5664 * @method_name: The name of the method to invoke.
5665 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5666 * or %NULL if not passing parameters.
5667 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5668 * @flags: Flags from the #GDBusCallFlags enumeration.
5669 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5670 * timeout or %G_MAXINT for no timeout.
5671 * @cancellable: A #GCancellable or %NULL.
5672 * @error: Return location for error or %NULL.
5674 * Synchronously invokes the @method_name method on the
5675 * @interface_name D-Bus interface on the remote object at
5676 * @object_path owned by @bus_name.
5678 * If @connection is closed then the operation will fail with
5679 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5680 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5681 * contains a value not compatible with the D-Bus protocol, the operation
5682 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5684 * If @reply_type is non-%NULL then the reply will be checked for having
5685 * this type and an error will be raised if it does not match. Said
5686 * another way, if you give a @reply_type then any non-%NULL return
5687 * value will be of this type.
5689 * If the @parameters #GVariant is floating, it is consumed.
5690 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5692 * g_dbus_connection_call_sync (connection,
5693 * "org.freedesktop.StringThings",
5694 * "/org/freedesktop/StringThings",
5695 * "org.freedesktop.StringThings",
5697 * g_variant_new ("(ss)",
5701 * G_DBUS_CALL_FLAGS_NONE,
5707 * The calling thread is blocked until a reply is received. See
5708 * g_dbus_connection_call() for the asynchronous version of
5711 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5712 * return values. Free with g_variant_unref().
5717 g_dbus_connection_call_sync (GDBusConnection *connection,
5718 const gchar *bus_name,
5719 const gchar *object_path,
5720 const gchar *interface_name,
5721 const gchar *method_name,
5722 GVariant *parameters,
5723 const GVariantType *reply_type,
5724 GDBusCallFlags flags,
5726 GCancellable *cancellable,
5729 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);
5732 /* ---------------------------------------------------------------------------------------------------- */
5737 * g_dbus_connection_call_with_unix_fd_list:
5738 * @connection: A #GDBusConnection.
5739 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5740 * @connection is not a message bus connection.
5741 * @object_path: Path of remote object.
5742 * @interface_name: D-Bus interface to invoke method on.
5743 * @method_name: The name of the method to invoke.
5744 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5745 * or %NULL if not passing parameters.
5746 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5747 * @flags: Flags from the #GDBusCallFlags enumeration.
5748 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5749 * timeout or %G_MAXINT for no timeout.
5750 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5751 * @cancellable: A #GCancellable or %NULL.
5752 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5753 * satisfied or %NULL if you don't * care about the result of the
5754 * method invocation.
5755 * @user_data: The data to pass to @callback.
5757 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5759 * This method is only available on UNIX.
5764 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5765 const gchar *bus_name,
5766 const gchar *object_path,
5767 const gchar *interface_name,
5768 const gchar *method_name,
5769 GVariant *parameters,
5770 const GVariantType *reply_type,
5771 GDBusCallFlags flags,
5773 GUnixFDList *fd_list,
5774 GCancellable *cancellable,
5775 GAsyncReadyCallback callback,
5778 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);
5782 * g_dbus_connection_call_with_unix_fd_list_finish:
5783 * @connection: A #GDBusConnection.
5784 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5785 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5786 * @error: Return location for error or %NULL.
5788 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5790 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5791 * return values. Free with g_variant_unref().
5796 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5797 GUnixFDList **out_fd_list,
5801 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5805 * g_dbus_connection_call_with_unix_fd_list_sync:
5806 * @connection: A #GDBusConnection.
5807 * @bus_name: A unique or well-known bus name.
5808 * @object_path: Path of remote object.
5809 * @interface_name: D-Bus interface to invoke method on.
5810 * @method_name: The name of the method to invoke.
5811 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5812 * or %NULL if not passing parameters.
5813 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5814 * @flags: Flags from the #GDBusCallFlags enumeration.
5815 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5816 * timeout or %G_MAXINT for no timeout.
5817 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5818 * @out_fd_list: (out): Return location for a #GUnixFDList or %NULL.
5819 * @cancellable: A #GCancellable or %NULL.
5820 * @error: Return location for error or %NULL.
5822 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5824 * This method is only available on UNIX.
5826 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5827 * return values. Free with g_variant_unref().
5832 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5833 const gchar *bus_name,
5834 const gchar *object_path,
5835 const gchar *interface_name,
5836 const gchar *method_name,
5837 GVariant *parameters,
5838 const GVariantType *reply_type,
5839 GDBusCallFlags flags,
5841 GUnixFDList *fd_list,
5842 GUnixFDList **out_fd_list,
5843 GCancellable *cancellable,
5846 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);
5849 #endif /* G_OS_UNIX */
5851 /* ---------------------------------------------------------------------------------------------------- */
5853 struct ExportedSubtree
5857 GDBusConnection *connection;
5858 GDBusSubtreeVTable *vtable;
5859 GDBusSubtreeFlags flags;
5861 GMainContext *context;
5863 GDestroyNotify user_data_free_func;
5867 exported_subtree_free (ExportedSubtree *es)
5869 call_destroy_notify (es->context,
5870 es->user_data_free_func,
5873 g_main_context_unref (es->context);
5875 _g_dbus_subtree_vtable_free (es->vtable);
5876 g_free (es->object_path);
5880 /* called without lock held in the thread where the caller registered
5884 handle_subtree_introspect (GDBusConnection *connection,
5885 ExportedSubtree *es,
5886 GDBusMessage *message)
5890 GDBusMessage *reply;
5893 const gchar *sender;
5894 const gchar *requested_object_path;
5895 const gchar *requested_node;
5896 GDBusInterfaceInfo **interfaces;
5898 gchar **subnode_paths;
5899 gboolean has_properties_interface;
5900 gboolean has_introspectable_interface;
5904 requested_object_path = g_dbus_message_get_path (message);
5905 sender = g_dbus_message_get_sender (message);
5906 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5908 s = g_string_new (NULL);
5909 introspect_append_header (s);
5911 /* Strictly we don't need the children in dynamic mode, but we avoid the
5912 * conditionals to preserve code clarity
5914 children = es->vtable->enumerate (es->connection,
5921 requested_node = strrchr (requested_object_path, '/') + 1;
5923 /* Assert existence of object if we are not dynamic */
5924 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5925 !_g_strv_has_string ((const gchar * const *) children, requested_node))
5930 requested_node = NULL;
5933 interfaces = es->vtable->introspect (es->connection,
5938 if (interfaces != NULL)
5940 has_properties_interface = FALSE;
5941 has_introspectable_interface = FALSE;
5943 for (n = 0; interfaces[n] != NULL; n++)
5945 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
5946 has_properties_interface = TRUE;
5947 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
5948 has_introspectable_interface = TRUE;
5950 if (!has_properties_interface)
5951 g_string_append (s, introspect_properties_interface);
5952 if (!has_introspectable_interface)
5953 g_string_append (s, introspect_introspectable_interface);
5955 for (n = 0; interfaces[n] != NULL; n++)
5957 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
5958 g_dbus_interface_info_unref (interfaces[n]);
5960 g_free (interfaces);
5963 /* then include <node> entries from the Subtree for the root */
5966 for (n = 0; children != NULL && children[n] != NULL; n++)
5967 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
5970 /* finally include nodes registered below us */
5971 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
5972 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
5973 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
5974 g_strfreev (subnode_paths);
5976 g_string_append (s, "</node>\n");
5978 reply = g_dbus_message_new_method_reply (message);
5979 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
5980 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
5981 g_object_unref (reply);
5986 g_string_free (s, TRUE);
5987 g_strfreev (children);
5991 /* called without lock held in the thread where the caller registered
5995 handle_subtree_method_invocation (GDBusConnection *connection,
5996 ExportedSubtree *es,
5997 GDBusMessage *message)
6000 const gchar *sender;
6001 const gchar *interface_name;
6002 const gchar *member;
6003 const gchar *signature;
6004 const gchar *requested_object_path;
6005 const gchar *requested_node;
6007 GDBusInterfaceInfo *interface_info;
6008 const GDBusInterfaceVTable *interface_vtable;
6009 gpointer interface_user_data;
6011 GDBusInterfaceInfo **interfaces;
6012 gboolean is_property_get;
6013 gboolean is_property_set;
6014 gboolean is_property_get_all;
6019 requested_object_path = g_dbus_message_get_path (message);
6020 sender = g_dbus_message_get_sender (message);
6021 interface_name = g_dbus_message_get_interface (message);
6022 member = g_dbus_message_get_member (message);
6023 signature = g_dbus_message_get_signature (message);
6024 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6026 is_property_get = FALSE;
6027 is_property_set = FALSE;
6028 is_property_get_all = FALSE;
6029 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6031 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6032 is_property_get = TRUE;
6033 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6034 is_property_set = TRUE;
6035 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6036 is_property_get_all = TRUE;
6041 requested_node = strrchr (requested_object_path, '/') + 1;
6043 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6045 /* We don't want to dispatch to unenumerated
6046 * nodes, so ensure that the child exists.
6051 children = es->vtable->enumerate (es->connection,
6056 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6057 g_strfreev (children);
6065 requested_node = NULL;
6068 /* get introspection data for the node */
6069 interfaces = es->vtable->introspect (es->connection,
6071 requested_object_path,
6075 if (interfaces == NULL)
6078 interface_info = NULL;
6079 for (n = 0; interfaces[n] != NULL; n++)
6081 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6082 interface_info = interfaces[n];
6085 /* dispatch the call if the user wants to handle it */
6086 if (interface_info != NULL)
6088 /* figure out where to dispatch the method call */
6089 interface_user_data = NULL;
6090 interface_vtable = es->vtable->dispatch (es->connection,
6095 &interface_user_data,
6097 if (interface_vtable == NULL)
6100 CONNECTION_LOCK (connection);
6101 handled = validate_and_maybe_schedule_method_call (es->connection,
6108 interface_user_data);
6109 CONNECTION_UNLOCK (connection);
6111 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6112 else if (is_property_get || is_property_set || is_property_get_all)
6114 if (is_property_get)
6115 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6116 else if (is_property_set)
6117 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6118 else if (is_property_get_all)
6119 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6121 g_assert_not_reached ();
6123 /* see if the object supports this interface at all */
6124 for (n = 0; interfaces[n] != NULL; n++)
6126 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6127 interface_info = interfaces[n];
6130 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6131 * claims it won't support the interface
6133 if (interface_info == NULL)
6135 GDBusMessage *reply;
6136 reply = g_dbus_message_new_method_error (message,
6137 "org.freedesktop.DBus.Error.InvalidArgs",
6138 _("No such interface `%s'"),
6140 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6141 g_object_unref (reply);
6146 /* figure out where to dispatch the property get/set/getall calls */
6147 interface_user_data = NULL;
6148 interface_vtable = es->vtable->dispatch (es->connection,
6153 &interface_user_data,
6155 if (interface_vtable == NULL)
6157 g_warning ("The subtree introspection function indicates that '%s' "
6158 "is a valid interface name, but calling the dispatch "
6159 "function on that interface gave us NULL", interface_name);
6163 if (is_property_get || is_property_set)
6165 CONNECTION_LOCK (connection);
6166 handled = validate_and_maybe_schedule_property_getset (es->connection,
6174 interface_user_data);
6175 CONNECTION_UNLOCK (connection);
6177 else if (is_property_get_all)
6179 CONNECTION_LOCK (connection);
6180 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6187 interface_user_data);
6188 CONNECTION_UNLOCK (connection);
6193 if (interfaces != NULL)
6195 for (n = 0; interfaces[n] != NULL; n++)
6196 g_dbus_interface_info_unref (interfaces[n]);
6197 g_free (interfaces);
6205 GDBusMessage *message;
6206 ExportedSubtree *es;
6207 } SubtreeDeferredData;
6210 subtree_deferred_data_free (SubtreeDeferredData *data)
6212 g_object_unref (data->message);
6216 /* called without lock held in the thread where the caller registered the subtree */
6218 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6220 SubtreeDeferredData *data = _data;
6225 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6226 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6227 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6228 handled = handle_subtree_introspect (data->es->connection,
6232 handled = handle_subtree_method_invocation (data->es->connection,
6238 CONNECTION_LOCK (data->es->connection);
6239 handled = handle_generic_unlocked (data->es->connection, data->message);
6240 CONNECTION_UNLOCK (data->es->connection);
6243 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6246 GDBusMessage *reply;
6247 reply = g_dbus_message_new_method_error (data->message,
6248 "org.freedesktop.DBus.Error.UnknownMethod",
6249 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6250 g_dbus_message_get_member (data->message),
6251 g_dbus_message_get_interface (data->message),
6252 g_dbus_message_get_signature (data->message));
6253 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6254 g_object_unref (reply);
6260 /* called in GDBusWorker thread with connection's lock held */
6262 subtree_message_func (GDBusConnection *connection,
6263 ExportedSubtree *es,
6264 GDBusMessage *message)
6266 GSource *idle_source;
6267 SubtreeDeferredData *data;
6269 data = g_new0 (SubtreeDeferredData, 1);
6270 data->message = g_object_ref (message);
6273 /* defer this call to an idle handler in the right thread */
6274 idle_source = g_idle_source_new ();
6275 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6276 g_source_set_callback (idle_source,
6277 process_subtree_vtable_message_in_idle_cb,
6279 (GDestroyNotify) subtree_deferred_data_free);
6280 g_source_attach (idle_source, es->context);
6281 g_source_unref (idle_source);
6283 /* since we own the entire subtree, handlers for objects not in the subtree have been
6284 * tried already by libdbus-1 - so we just need to ensure that we're always going
6285 * to reply to the message
6291 * g_dbus_connection_register_subtree:
6292 * @connection: A #GDBusConnection.
6293 * @object_path: The object path to register the subtree at.
6294 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6295 * @flags: Flags used to fine tune the behavior of the subtree.
6296 * @user_data: Data to pass to functions in @vtable.
6297 * @user_data_free_func: Function to call when the subtree is unregistered.
6298 * @error: Return location for error or %NULL.
6300 * Registers a whole subtree of <quote>dynamic</quote> objects.
6302 * The @enumerate and @introspection functions in @vtable are used to
6303 * convey, to remote callers, what nodes exist in the subtree rooted
6306 * When handling remote calls into any node in the subtree, first the
6307 * @enumerate function is used to check if the node exists. If the node exists
6308 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6309 * the @introspection function is used to check if the node supports the
6310 * requested method. If so, the @dispatch function is used to determine
6311 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6312 * #gpointer will be used to call into the interface vtable for processing
6315 * All calls into user-provided code will be invoked in the <link
6316 * linkend="g-main-context-push-thread-default">thread-default main
6317 * loop</link> of the thread you are calling this method from.
6319 * If an existing subtree is already registered at @object_path or
6320 * then @error is set to #G_IO_ERROR_EXISTS.
6322 * Note that it is valid to register regular objects (using
6323 * g_dbus_connection_register_object()) in a subtree registered with
6324 * g_dbus_connection_register_subtree() - if so, the subtree handler
6325 * is tried as the last resort. One way to think about a subtree
6326 * handler is to consider it a <quote>fallback handler</quote>
6327 * for object paths not registered via g_dbus_connection_register_object()
6328 * or other bindings.
6330 * Note that @vtable will be copied so you cannot change it after
6333 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6335 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6336 * that can be used with g_dbus_connection_unregister_subtree() .
6341 g_dbus_connection_register_subtree (GDBusConnection *connection,
6342 const gchar *object_path,
6343 const GDBusSubtreeVTable *vtable,
6344 GDBusSubtreeFlags flags,
6346 GDestroyNotify user_data_free_func,
6350 ExportedSubtree *es;
6352 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6353 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6354 g_return_val_if_fail (vtable != NULL, 0);
6355 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6356 g_return_val_if_fail (check_initialized (connection), 0);
6360 CONNECTION_LOCK (connection);
6362 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6368 _("A subtree is already exported for %s"),
6373 es = g_new0 (ExportedSubtree, 1);
6374 es->object_path = g_strdup (object_path);
6375 es->connection = connection;
6377 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6379 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6380 es->user_data = user_data;
6381 es->user_data_free_func = user_data_free_func;
6382 es->context = g_main_context_ref_thread_default ();
6384 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6385 g_hash_table_insert (connection->map_id_to_es,
6386 GUINT_TO_POINTER (es->id),
6392 CONNECTION_UNLOCK (connection);
6397 /* ---------------------------------------------------------------------------------------------------- */
6400 * g_dbus_connection_unregister_subtree:
6401 * @connection: A #GDBusConnection.
6402 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6404 * Unregisters a subtree.
6406 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6411 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6412 guint registration_id)
6414 ExportedSubtree *es;
6417 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6418 g_return_val_if_fail (check_initialized (connection), FALSE);
6422 CONNECTION_LOCK (connection);
6424 es = g_hash_table_lookup (connection->map_id_to_es,
6425 GUINT_TO_POINTER (registration_id));
6429 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6430 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6435 CONNECTION_UNLOCK (connection);
6440 /* ---------------------------------------------------------------------------------------------------- */
6442 /* may be called in any thread, with connection's lock held */
6444 handle_generic_ping_unlocked (GDBusConnection *connection,
6445 const gchar *object_path,
6446 GDBusMessage *message)
6448 GDBusMessage *reply;
6449 reply = g_dbus_message_new_method_reply (message);
6450 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6451 g_object_unref (reply);
6454 /* may be called in any thread, with connection's lock held */
6456 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6457 const gchar *object_path,
6458 GDBusMessage *message)
6460 GDBusMessage *reply;
6463 if (connection->machine_id == NULL)
6468 connection->machine_id = _g_dbus_get_machine_id (&error);
6469 if (connection->machine_id == NULL)
6471 reply = g_dbus_message_new_method_error_literal (message,
6472 "org.freedesktop.DBus.Error.Failed",
6474 g_error_free (error);
6480 reply = g_dbus_message_new_method_reply (message);
6481 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6483 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6484 g_object_unref (reply);
6487 /* may be called in any thread, with connection's lock held */
6489 handle_generic_introspect_unlocked (GDBusConnection *connection,
6490 const gchar *object_path,
6491 GDBusMessage *message)
6496 GDBusMessage *reply;
6498 /* first the header */
6499 s = g_string_new (NULL);
6500 introspect_append_header (s);
6502 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6503 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6504 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6505 g_strfreev (registered);
6506 g_string_append (s, "</node>\n");
6508 reply = g_dbus_message_new_method_reply (message);
6509 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6510 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6511 g_object_unref (reply);
6512 g_string_free (s, TRUE);
6515 /* may be called in any thread, with connection's lock held */
6517 handle_generic_unlocked (GDBusConnection *connection,
6518 GDBusMessage *message)
6521 const gchar *interface_name;
6522 const gchar *member;
6523 const gchar *signature;
6526 CONNECTION_ENSURE_LOCK (connection);
6530 interface_name = g_dbus_message_get_interface (message);
6531 member = g_dbus_message_get_member (message);
6532 signature = g_dbus_message_get_signature (message);
6533 path = g_dbus_message_get_path (message);
6535 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6536 g_strcmp0 (member, "Introspect") == 0 &&
6537 g_strcmp0 (signature, "") == 0)
6539 handle_generic_introspect_unlocked (connection, path, message);
6542 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6543 g_strcmp0 (member, "Ping") == 0 &&
6544 g_strcmp0 (signature, "") == 0)
6546 handle_generic_ping_unlocked (connection, path, message);
6549 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6550 g_strcmp0 (member, "GetMachineId") == 0 &&
6551 g_strcmp0 (signature, "") == 0)
6553 handle_generic_get_machine_id_unlocked (connection, path, message);
6560 /* ---------------------------------------------------------------------------------------------------- */
6562 /* called in GDBusWorker thread with connection's lock held */
6564 distribute_method_call (GDBusConnection *connection,
6565 GDBusMessage *message)
6567 GDBusMessage *reply;
6569 ExportedSubtree *es;
6570 const gchar *object_path;
6571 const gchar *interface_name;
6572 const gchar *member;
6574 gchar *subtree_path;
6577 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6579 interface_name = g_dbus_message_get_interface (message);
6580 member = g_dbus_message_get_member (message);
6581 path = g_dbus_message_get_path (message);
6582 subtree_path = g_strdup (path);
6583 needle = strrchr (subtree_path, '/');
6584 if (needle != NULL && needle != subtree_path)
6590 g_free (subtree_path);
6591 subtree_path = NULL;
6595 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6597 _g_dbus_debug_print_lock ();
6598 g_print ("========================================================================\n"
6599 "GDBus-debug:Incoming:\n"
6600 " <<<< METHOD INVOCATION %s.%s()\n"
6602 " invoked by name %s\n"
6604 interface_name, member,
6606 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6607 g_dbus_message_get_serial (message));
6608 _g_dbus_debug_print_unlock ();
6611 object_path = g_dbus_message_get_path (message);
6612 g_assert (object_path != NULL);
6614 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6617 if (obj_message_func (connection, eo, message))
6621 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6624 if (subtree_message_func (connection, es, message))
6628 if (subtree_path != NULL)
6630 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6633 if (subtree_message_func (connection, es, message))
6638 if (handle_generic_unlocked (connection, message))
6641 /* if we end up here, the message has not been not handled - so return an error saying this */
6642 reply = g_dbus_message_new_method_error (message,
6643 "org.freedesktop.DBus.Error.UnknownMethod",
6644 _("No such interface `%s' on object at path %s"),
6647 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6648 g_object_unref (reply);
6651 g_free (subtree_path);
6654 /* ---------------------------------------------------------------------------------------------------- */
6656 /* Called in any user thread, with the message_bus_lock held. */
6657 static GDBusConnection **
6658 message_bus_get_singleton (GBusType bus_type,
6661 GDBusConnection **ret;
6662 const gchar *starter_bus;
6668 case G_BUS_TYPE_SESSION:
6669 ret = &the_session_bus;
6672 case G_BUS_TYPE_SYSTEM:
6673 ret = &the_system_bus;
6676 case G_BUS_TYPE_STARTER:
6677 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6678 if (g_strcmp0 (starter_bus, "session") == 0)
6680 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6683 else if (g_strcmp0 (starter_bus, "system") == 0)
6685 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6690 if (starter_bus != NULL)
6694 G_IO_ERROR_INVALID_ARGUMENT,
6695 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6696 " - unknown value `%s'"),
6701 g_set_error_literal (error,
6703 G_IO_ERROR_INVALID_ARGUMENT,
6704 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6705 "variable is not set"));
6711 g_assert_not_reached ();
6719 /* Called in any user thread, without holding locks. */
6720 static GDBusConnection *
6721 get_uninitialized_connection (GBusType bus_type,
6722 GCancellable *cancellable,
6725 GDBusConnection **singleton;
6726 GDBusConnection *ret;
6730 G_LOCK (message_bus_lock);
6731 singleton = message_bus_get_singleton (bus_type, error);
6732 if (singleton == NULL)
6735 if (*singleton == NULL)
6738 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6739 if (address == NULL)
6741 ret = *singleton = g_object_new (G_TYPE_DBUS_CONNECTION,
6743 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6744 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6745 "exit-on-close", TRUE,
6751 ret = g_object_ref (*singleton);
6754 g_assert (ret != NULL);
6757 G_UNLOCK (message_bus_lock);
6763 * @bus_type: A #GBusType.
6764 * @cancellable: A #GCancellable or %NULL.
6765 * @error: Return location for error or %NULL.
6767 * Synchronously connects to the message bus specified by @bus_type.
6768 * Note that the returned object may shared with other callers,
6769 * e.g. if two separate parts of a process calls this function with
6770 * the same @bus_type, they will share the same object.
6772 * This is a synchronous failable function. See g_bus_get() and
6773 * g_bus_get_finish() for the asynchronous version.
6775 * The returned object is a singleton, that is, shared with other
6776 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6777 * event that you need a private message bus connection, use
6778 * g_dbus_address_get_for_bus_sync() and
6779 * g_dbus_connection_new_for_address().
6781 * Note that the returned #GDBusConnection object will (usually) have
6782 * the #GDBusConnection:exit-on-close property set to %TRUE.
6784 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6789 g_bus_get_sync (GBusType bus_type,
6790 GCancellable *cancellable,
6793 GDBusConnection *connection;
6795 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6797 connection = get_uninitialized_connection (bus_type, cancellable, error);
6798 if (connection == NULL)
6801 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6803 g_object_unref (connection);
6812 bus_get_async_initable_cb (GObject *source_object,
6816 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6820 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6824 g_assert (error != NULL);
6825 g_simple_async_result_take_error (simple, error);
6826 g_object_unref (source_object);
6830 g_simple_async_result_set_op_res_gpointer (simple,
6834 g_simple_async_result_complete_in_idle (simple);
6835 g_object_unref (simple);
6840 * @bus_type: A #GBusType.
6841 * @cancellable: A #GCancellable or %NULL.
6842 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6843 * @user_data: The data to pass to @callback.
6845 * Asynchronously connects to the message bus specified by @bus_type.
6847 * When the operation is finished, @callback will be invoked. You can
6848 * then call g_bus_get_finish() to get the result of the operation.
6850 * This is a asynchronous failable function. See g_bus_get_sync() for
6851 * the synchronous version.
6856 g_bus_get (GBusType bus_type,
6857 GCancellable *cancellable,
6858 GAsyncReadyCallback callback,
6861 GDBusConnection *connection;
6862 GSimpleAsyncResult *simple;
6865 simple = g_simple_async_result_new (NULL,
6871 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6872 if (connection == NULL)
6874 g_assert (error != NULL);
6875 g_simple_async_result_take_error (simple, error);
6876 g_simple_async_result_complete_in_idle (simple);
6877 g_object_unref (simple);
6881 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6884 bus_get_async_initable_cb,
6891 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6892 * @error: Return location for error or %NULL.
6894 * Finishes an operation started with g_bus_get().
6896 * The returned object is a singleton, that is, shared with other
6897 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6898 * event that you need a private message bus connection, use
6899 * g_dbus_address_get_for_bus_sync() and
6900 * g_dbus_connection_new_for_address().
6902 * Note that the returned #GDBusConnection object will (usually) have
6903 * the #GDBusConnection:exit-on-close property set to %TRUE.
6905 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6910 g_bus_get_finish (GAsyncResult *res,
6913 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
6915 GDBusConnection *ret;
6917 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6919 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
6923 if (g_simple_async_result_propagate_error (simple, error))
6926 object = g_simple_async_result_get_op_res_gpointer (simple);
6927 g_assert (object != NULL);
6928 ret = g_object_ref (G_DBUS_CONNECTION (object));
6934 /* ---------------------------------------------------------------------------------------------------- */