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 "gkdbusconnection.h"
119 #include "gdbuserror.h"
120 #include "gioenumtypes.h"
121 #include "gdbusintrospection.h"
122 #include "gdbusmethodinvocation.h"
123 #include "gdbusprivate.h"
124 #include "gdbusauthobserver.h"
125 #include "ginitable.h"
126 #include "gasyncinitable.h"
127 #include "giostream.h"
128 #include "gasyncresult.h"
129 #include "gsimpleasyncresult.h"
132 #include "gunixconnection.h"
133 #include "gunixfdmessage.h"
136 #include "glibintl.h"
139 * SECTION:gdbusconnection
140 * @short_description: D-Bus Connections
141 * @include: gio/gio.h
143 * The #GDBusConnection type is used for D-Bus connections to remote
144 * peers such as a message buses. It is a low-level API that offers a
145 * lot of flexibility. For instance, it lets you establish a connection
146 * over any transport that can by represented as an #GIOStream.
148 * This class is rarely used directly in D-Bus clients. If you are writing
149 * an D-Bus client, it is often easier to use the g_bus_own_name(),
150 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
152 * As an exception to the usual GLib rule that a particular object must not be
153 * used by two threads at the same time, #GDBusConnection's methods may be
154 * called from any thread<footnote>
156 * This is so that g_bus_get() and g_bus_get_sync() can safely return the
157 * same #GDBusConnection when called from any thread.
161 * Most of the ways to obtain a #GDBusConnection automatically initialize it
162 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
163 * g_bus_get(), and the synchronous versions of those methods, give you an
164 * initialized connection. Language bindings for GIO should use
165 * g_initable_new() or g_async_initable_new_async(), which also initialize the
168 * If you construct an uninitialized #GDBusConnection, such as via
169 * g_object_new(), you must initialize it via g_initable_init() or
170 * g_async_initable_init_async() before using its methods or properties.
171 * Calling methods or accessing properties on a #GDBusConnection that has not
172 * completed initialization successfully is considered to be invalid, and leads
173 * to undefined behaviour. In particular, if initialization fails with a
174 * #GError, the only valid thing you can do with that #GDBusConnection is to
175 * free it with g_object_unref().
177 * <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>
179 * <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>
181 * <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>
183 * <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>
186 /* ---------------------------------------------------------------------------------------------------- */
188 typedef struct _GDBusConnectionClass GDBusConnectionClass;
191 * GDBusConnectionClass:
192 * @closed: Signal class handler for the #GDBusConnection::closed signal.
194 * Class structure for #GDBusConnection.
198 struct _GDBusConnectionClass
201 GObjectClass parent_class;
205 void (*closed) (GDBusConnection *connection,
206 gboolean remote_peer_vanished,
210 G_LOCK_DEFINE_STATIC (message_bus_lock);
212 static GWeakRef the_session_bus;
213 static GWeakRef the_system_bus;
215 /* Extra pseudo-member of GDBusSendMessageFlags.
216 * Set by initable_init() to indicate that despite not being initialized yet,
217 * enough of the only-valid-after-init members are set that we can send a
218 * message, and we're being called from its thread, so no memory barrier is
219 * required before accessing them.
221 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
223 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
224 #define CALL_FLAGS_INITIALIZING (1<<31)
226 /* ---------------------------------------------------------------------------------------------------- */
230 GDestroyNotify callback;
232 GMainContext *context;
233 } CallDestroyNotifyData;
236 call_destroy_notify_data_in_idle (gpointer user_data)
238 CallDestroyNotifyData *data = user_data;
239 data->callback (data->user_data);
244 call_destroy_notify_data_free (CallDestroyNotifyData *data)
246 if (data->context != NULL)
247 g_main_context_unref (data->context);
252 * call_destroy_notify: <internal>
253 * @context: (allow-none): A #GMainContext or %NULL.
254 * @callback: (allow-none): A #GDestroyNotify or %NULL.
255 * @user_data: Data to pass to @callback.
257 * Schedules @callback to run in @context.
260 call_destroy_notify (GMainContext *context,
261 GDestroyNotify callback,
264 GSource *idle_source;
265 CallDestroyNotifyData *data;
267 if (callback == NULL)
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);
290 /* ---------------------------------------------------------------------------------------------------- */
293 _g_strv_has_string (const gchar* const *haystack,
298 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
300 if (g_strcmp0 (haystack[n], needle) == 0)
306 /* ---------------------------------------------------------------------------------------------------- */
309 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
311 // TODO: for some reason this doesn't work on Windows
312 #define CONNECTION_ENSURE_LOCK(obj) do { \
313 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
315 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
316 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
321 #define CONNECTION_LOCK(obj) do { \
322 g_mutex_lock (&(obj)->lock); \
325 #define CONNECTION_UNLOCK(obj) do { \
326 g_mutex_unlock (&(obj)->lock); \
329 /* Flags in connection->atomic_flags */
331 FLAG_INITIALIZED = 1 << 0,
332 FLAG_EXIT_ON_CLOSE = 1 << 1,
339 * The #GDBusConnection structure contains only private data and
340 * should only be accessed using the provided API.
344 struct _GDBusConnection
347 GObject parent_instance;
349 /* ------------------------------------------------------------------------ */
350 /* -- General object state ------------------------------------------------ */
351 /* ------------------------------------------------------------------------ */
353 /* General-purpose lock for most fields */
356 /* A lock used in the init() method of the GInitable interface - see comments
357 * in initable_init() for why a separate lock is needed.
359 * If you need both @lock and @init_lock, you must take @init_lock first.
363 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
364 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
368 /* The underlying stream used for communication
369 * Read-only after initable_init(), so it may be read if you either
370 * hold @init_lock or check for initialization first.
374 /* The object used for authentication (if any).
375 * Read-only after initable_init(), so it may be read if you either
376 * hold @init_lock or check for initialization first.
380 /* Last serial used. Protected by @lock. */
383 /* The object used to send/receive messages.
384 * Read-only after initable_init(), so it may be read if you either
385 * hold @init_lock or check for initialization first.
389 /* If connected to a message bus, this contains the unique name assigned to
390 * us by the bus (e.g. ":1.42").
391 * Read-only after initable_init(), so it may be read if you either
392 * hold @init_lock or check for initialization first.
394 gchar *bus_unique_name;
396 /* The GUID returned by the other side if we authenticed as a client or
397 * the GUID to use if authenticating as a server.
398 * Read-only after initable_init(), so it may be read if you either
399 * hold @init_lock or check for initialization first.
403 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
404 * Inspect @initialization_error to see whether it succeeded or failed.
406 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
408 * FLAG_CLOSED is the closed property. It may be read at any time, but
409 * may only be written while holding @lock.
411 volatile gint atomic_flags;
413 /* If the connection could not be established during initable_init(),
414 * this GError will be set.
415 * Read-only after initable_init(), so it may be read if you either
416 * hold @init_lock or check for initialization first.
418 GError *initialization_error;
420 /* The result of g_main_context_ref_thread_default() when the object
421 * was created (the GObject _init() function) - this is used for delivery
422 * of the :closed GObject signal.
424 * Only set in the GObject init function, so no locks are needed.
426 GMainContext *main_context_at_construction;
428 /* Read-only construct properties, no locks needed */
430 GDBusConnectionFlags flags;
432 /* Map used for managing method replies, protected by @lock */
433 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
435 /* Maps used for managing signal subscription, protected by @lock */
436 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
437 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
438 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
440 /* Maps used for managing exported objects and subtrees,
443 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
444 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
445 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
446 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
448 /* Map used for storing last used serials for each thread, protected by @lock */
449 GHashTable *map_thread_to_last_serial;
451 /* Structure used for message filters, protected by @lock */
454 /* Capabilities negotiated during authentication
455 * Read-only after initable_init(), so it may be read without holding a
456 * lock, if you check for initialization first.
458 GDBusCapabilityFlags capabilities;
460 /* Protected by @init_lock */
461 GDBusAuthObserver *authentication_observer;
463 /* Read-only after initable_init(), so it may be read if you either
464 * hold @init_lock or check for initialization first.
466 GCredentials *credentials;
468 /* set to TRUE when finalizing */
472 typedef struct ExportedObject ExportedObject;
473 static void exported_object_free (ExportedObject *eo);
475 typedef struct ExportedSubtree ExportedSubtree;
476 static void exported_subtree_free (ExportedSubtree *es);
494 PROP_CAPABILITY_FLAGS,
495 PROP_AUTHENTICATION_OBSERVER,
498 static void distribute_signals (GDBusConnection *connection,
499 GDBusMessage *message);
501 static void distribute_method_call (GDBusConnection *connection,
502 GDBusMessage *message);
504 static gboolean handle_generic_unlocked (GDBusConnection *connection,
505 GDBusMessage *message);
508 static void purge_all_signal_subscriptions (GDBusConnection *connection);
509 static void purge_all_filters (GDBusConnection *connection);
511 #define _G_ENSURE_LOCK(name) do { \
512 if (G_UNLIKELY (G_TRYLOCK(name))) \
514 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
515 "_G_ENSURE_LOCK: Lock `" #name "' is not locked"); \
519 static guint signals[LAST_SIGNAL] = { 0 };
521 static void initable_iface_init (GInitableIface *initable_iface);
522 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
524 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
525 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
526 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
530 * Check that all members of @connection that can only be accessed after
531 * the connection is initialized can safely be accessed. If not,
532 * log a critical warning. This function is a memory barrier.
534 * Returns: %TRUE if initialized
537 check_initialized (GDBusConnection *connection)
539 /* The access to @atomic_flags isn't conditional, so that this function
540 * provides a memory barrier for thread-safety even if checks are disabled.
541 * (If you don't want this stricter guarantee, you can call
542 * g_return_if_fail (check_initialized (c)).)
544 * This isn't strictly necessary now that we've decided use of an
545 * uninitialized GDBusConnection is undefined behaviour, but it seems
546 * better to be as deterministic as is feasible.
548 * (Anything that could suffer a crash from seeing undefined values
549 * must have a race condition - thread A initializes the connection while
550 * thread B calls a method without initialization, hoping that thread A will
551 * win the race - so its behaviour is undefined anyway.)
553 gint flags = g_atomic_int_get (&connection->atomic_flags);
555 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
557 /* We can safely access this, due to the memory barrier above */
558 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
564 MAY_BE_UNINITIALIZED = (1<<1)
565 } CheckUnclosedFlags;
568 * Check the same thing as check_initialized(), and also that the
569 * connection is not closed. If the connection is uninitialized,
570 * raise a critical warning (it's programmer error); if it's closed,
571 * raise a recoverable GError (it's a runtime error).
573 * This function is a memory barrier.
575 * Returns: %TRUE if initialized and not closed
578 check_unclosed (GDBusConnection *connection,
579 CheckUnclosedFlags check,
582 /* check_initialized() is effectively inlined, so we don't waste time
583 * doing two memory barriers
585 gint flags = g_atomic_int_get (&connection->atomic_flags);
587 if (!(check & MAY_BE_UNINITIALIZED))
589 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
590 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
593 if (flags & FLAG_CLOSED)
595 g_set_error_literal (error,
598 _("The connection is closed"));
605 static GHashTable *alive_connections = NULL;
608 g_dbus_connection_dispose (GObject *object)
610 GDBusConnection *connection = G_DBUS_CONNECTION (object);
612 G_LOCK (message_bus_lock);
613 CONNECTION_LOCK (connection);
614 if (connection->worker != NULL)
616 _g_dbus_worker_stop (connection->worker);
617 connection->worker = NULL;
618 if (alive_connections != NULL)
619 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
623 if (alive_connections != NULL)
624 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
626 CONNECTION_UNLOCK (connection);
627 G_UNLOCK (message_bus_lock);
629 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
630 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
634 g_dbus_connection_finalize (GObject *object)
636 GDBusConnection *connection = G_DBUS_CONNECTION (object);
638 connection->finalizing = TRUE;
640 purge_all_signal_subscriptions (connection);
642 purge_all_filters (connection);
643 g_ptr_array_unref (connection->filters);
645 if (connection->authentication_observer != NULL)
646 g_object_unref (connection->authentication_observer);
648 if (connection->auth != NULL)
649 g_object_unref (connection->auth);
651 if (connection->credentials)
652 g_object_unref (connection->credentials);
654 if (connection->stream != NULL)
656 g_object_unref (connection->stream);
657 connection->stream = NULL;
660 g_free (connection->address);
662 g_free (connection->guid);
663 g_free (connection->bus_unique_name);
665 if (connection->initialization_error != NULL)
666 g_error_free (connection->initialization_error);
668 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
670 g_hash_table_unref (connection->map_rule_to_signal_data);
671 g_hash_table_unref (connection->map_id_to_signal_data);
672 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
674 g_hash_table_unref (connection->map_id_to_ei);
675 g_hash_table_unref (connection->map_object_path_to_eo);
676 g_hash_table_unref (connection->map_id_to_es);
677 g_hash_table_unref (connection->map_object_path_to_es);
679 g_hash_table_unref (connection->map_thread_to_last_serial);
681 g_main_context_unref (connection->main_context_at_construction);
683 g_free (connection->machine_id);
685 g_mutex_clear (&connection->init_lock);
686 g_mutex_clear (&connection->lock);
688 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
691 /* called in any user thread, with the connection's lock not held */
693 g_dbus_connection_get_property (GObject *object,
698 GDBusConnection *connection = G_DBUS_CONNECTION (object);
703 g_value_set_object (value, g_dbus_connection_get_stream (connection));
707 g_value_set_string (value, g_dbus_connection_get_guid (connection));
710 case PROP_UNIQUE_NAME:
711 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
715 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
718 case PROP_EXIT_ON_CLOSE:
719 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
722 case PROP_CAPABILITY_FLAGS:
723 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
727 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
732 /* called in any user thread, with the connection's lock not held */
734 g_dbus_connection_set_property (GObject *object,
739 GDBusConnection *connection = G_DBUS_CONNECTION (object);
744 connection->stream = g_value_dup_object (value);
748 connection->guid = g_value_dup_string (value);
752 connection->address = g_value_dup_string (value);
756 connection->flags = g_value_get_flags (value);
759 case PROP_EXIT_ON_CLOSE:
760 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
763 case PROP_AUTHENTICATION_OBSERVER:
764 connection->authentication_observer = g_value_dup_object (value);
768 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
773 /* Base-class implementation of GDBusConnection::closed.
775 * Called in a user thread, by the main context that was thread-default when
776 * the object was constructed.
779 g_dbus_connection_real_closed (GDBusConnection *connection,
780 gboolean remote_peer_vanished,
783 gint flags = g_atomic_int_get (&connection->atomic_flags);
785 /* Because atomic int access is a memory barrier, we can safely read
786 * initialization_error without a lock, as long as we do it afterwards.
788 if (remote_peer_vanished &&
789 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
790 (flags & FLAG_INITIALIZED) != 0 &&
791 connection->initialization_error == NULL)
795 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
798 g_quark_to_string (error->domain), error->code);
802 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
809 g_dbus_connection_class_init (GDBusConnectionClass *klass)
811 GObjectClass *gobject_class;
813 gobject_class = G_OBJECT_CLASS (klass);
815 gobject_class->finalize = g_dbus_connection_finalize;
816 gobject_class->dispose = g_dbus_connection_dispose;
817 gobject_class->set_property = g_dbus_connection_set_property;
818 gobject_class->get_property = g_dbus_connection_get_property;
820 klass->closed = g_dbus_connection_real_closed;
823 * GDBusConnection:stream:
825 * The underlying #GIOStream used for I/O.
827 * If this is passed on construction and is a #GSocketConnection,
828 * then the corresponding #GSocket will be put into non-blocking mode.
830 * While the #GDBusConnection is active, it will interact with this
831 * stream from a worker thread, so it is not safe to interact with
832 * the stream directly.
836 g_object_class_install_property (gobject_class,
838 g_param_spec_object ("stream",
840 P_("The underlying streams used for I/O"),
844 G_PARAM_CONSTRUCT_ONLY |
845 G_PARAM_STATIC_NAME |
846 G_PARAM_STATIC_BLURB |
847 G_PARAM_STATIC_NICK));
850 * GDBusConnection:address:
852 * A D-Bus address specifying potential endpoints that can be used
853 * when establishing the connection.
857 g_object_class_install_property (gobject_class,
859 g_param_spec_string ("address",
861 P_("D-Bus address specifying potential socket endpoints"),
864 G_PARAM_CONSTRUCT_ONLY |
865 G_PARAM_STATIC_NAME |
866 G_PARAM_STATIC_BLURB |
867 G_PARAM_STATIC_NICK));
870 * GDBusConnection:flags:
872 * Flags from the #GDBusConnectionFlags enumeration.
876 g_object_class_install_property (gobject_class,
878 g_param_spec_flags ("flags",
881 G_TYPE_DBUS_CONNECTION_FLAGS,
882 G_DBUS_CONNECTION_FLAGS_NONE,
884 G_PARAM_CONSTRUCT_ONLY |
885 G_PARAM_STATIC_NAME |
886 G_PARAM_STATIC_BLURB |
887 G_PARAM_STATIC_NICK));
890 * GDBusConnection:guid:
892 * The GUID of the peer performing the role of server when
895 * If you are constructing a #GDBusConnection and pass
896 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
897 * #GDBusConnection:flags property then you MUST also set this
898 * property to a valid guid.
900 * If you are constructing a #GDBusConnection and pass
901 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
902 * #GDBusConnection:flags property you will be able to read the GUID
903 * of the other peer here after the connection has been successfully
908 g_object_class_install_property (gobject_class,
910 g_param_spec_string ("guid",
912 P_("GUID of the server peer"),
916 G_PARAM_CONSTRUCT_ONLY |
917 G_PARAM_STATIC_NAME |
918 G_PARAM_STATIC_BLURB |
919 G_PARAM_STATIC_NICK));
922 * GDBusConnection:unique-name:
924 * The unique name as assigned by the message bus or %NULL if the
925 * connection is not open or not a message bus connection.
929 g_object_class_install_property (gobject_class,
931 g_param_spec_string ("unique-name",
933 P_("Unique name of bus connection"),
936 G_PARAM_STATIC_NAME |
937 G_PARAM_STATIC_BLURB |
938 G_PARAM_STATIC_NICK));
941 * GDBusConnection:closed:
943 * A boolean specifying whether the connection has been closed.
947 g_object_class_install_property (gobject_class,
949 g_param_spec_boolean ("closed",
951 P_("Whether the connection is closed"),
954 G_PARAM_STATIC_NAME |
955 G_PARAM_STATIC_BLURB |
956 G_PARAM_STATIC_NICK));
959 * GDBusConnection:exit-on-close:
961 * A boolean specifying whether the process will be terminated (by
962 * calling <literal>raise(SIGTERM)</literal>) if the connection
963 * is closed by the remote peer.
965 * Note that #GDBusConnection objects returned by g_bus_get_finish() and
966 * g_bus_get_sync() will (usually) have this property set to %TRUE.
970 g_object_class_install_property (gobject_class,
972 g_param_spec_boolean ("exit-on-close",
974 P_("Whether the process is terminated when the connection is closed"),
978 G_PARAM_STATIC_NAME |
979 G_PARAM_STATIC_BLURB |
980 G_PARAM_STATIC_NICK));
983 * GDBusConnection:capabilities:
985 * Flags from the #GDBusCapabilityFlags enumeration
986 * representing connection features negotiated with the other peer.
990 g_object_class_install_property (gobject_class,
991 PROP_CAPABILITY_FLAGS,
992 g_param_spec_flags ("capabilities",
995 G_TYPE_DBUS_CAPABILITY_FLAGS,
996 G_DBUS_CAPABILITY_FLAGS_NONE,
998 G_PARAM_STATIC_NAME |
999 G_PARAM_STATIC_BLURB |
1000 G_PARAM_STATIC_NICK));
1003 * GDBusConnection:authentication-observer:
1005 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1009 g_object_class_install_property (gobject_class,
1010 PROP_AUTHENTICATION_OBSERVER,
1011 g_param_spec_object ("authentication-observer",
1012 P_("Authentication Observer"),
1013 P_("Object used to assist in the authentication process"),
1014 G_TYPE_DBUS_AUTH_OBSERVER,
1016 G_PARAM_CONSTRUCT_ONLY |
1017 G_PARAM_STATIC_NAME |
1018 G_PARAM_STATIC_BLURB |
1019 G_PARAM_STATIC_NICK));
1022 * GDBusConnection::closed:
1023 * @connection: The #GDBusConnection emitting the signal.
1024 * @remote_peer_vanished: %TRUE if @connection is closed because the
1025 * remote peer closed its end of the connection.
1026 * @error: (allow-none): A #GError with more details about the event or %NULL.
1028 * Emitted when the connection is closed.
1030 * The cause of this event can be
1033 * If g_dbus_connection_close() is called. In this case
1034 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1035 * </para></listitem>
1037 * If the remote peer closes the connection. In this case
1038 * @remote_peer_vanished is set to %TRUE and @error is set.
1039 * </para></listitem>
1041 * If the remote peer sends invalid or malformed data. In this
1042 * case @remote_peer_vanished is set to %FALSE and @error
1044 * </para></listitem>
1047 * Upon receiving this signal, you should give up your reference to
1048 * @connection. You are guaranteed that this signal is emitted only
1053 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1054 G_TYPE_DBUS_CONNECTION,
1056 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1067 g_dbus_connection_init (GDBusConnection *connection)
1069 g_mutex_init (&connection->lock);
1070 g_mutex_init (&connection->init_lock);
1072 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1074 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1076 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1078 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1081 (GDestroyNotify) g_ptr_array_unref);
1083 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1086 (GDestroyNotify) exported_object_free);
1088 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1091 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1094 (GDestroyNotify) exported_subtree_free);
1096 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1099 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1102 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1104 connection->filters = g_ptr_array_new ();
1108 * g_dbus_connection_get_stream:
1109 * @connection: a #GDBusConnection
1111 * Gets the underlying stream used for IO.
1113 * While the #GDBusConnection is active, it will interact with this
1114 * stream from a worker thread, so it is not safe to interact with
1115 * the stream directly.
1117 * Returns: (transfer none): the stream used for IO
1122 g_dbus_connection_get_stream (GDBusConnection *connection)
1124 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1126 /* do not use g_return_val_if_fail(), we want the memory barrier */
1127 if (!check_initialized (connection))
1130 return connection->stream;
1134 * g_dbus_connection_start_message_processing:
1135 * @connection: A #GDBusConnection.
1137 * If @connection was created with
1138 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1139 * starts processing messages. Does nothing on if @connection wasn't
1140 * created with this flag or if the method has already been called.
1145 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1147 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1149 /* do not use g_return_val_if_fail(), we want the memory barrier */
1150 if (!check_initialized (connection))
1153 g_assert (connection->worker != NULL);
1154 _g_dbus_worker_unfreeze (connection->worker);
1158 * g_dbus_connection_is_closed:
1159 * @connection: A #GDBusConnection.
1161 * Gets whether @connection is closed.
1163 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1168 g_dbus_connection_is_closed (GDBusConnection *connection)
1172 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1174 flags = g_atomic_int_get (&connection->atomic_flags);
1176 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1180 * g_dbus_connection_get_capabilities:
1181 * @connection: A #GDBusConnection.
1183 * Gets the capabilities negotiated with the remote peer
1185 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1189 GDBusCapabilityFlags
1190 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1192 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1194 /* do not use g_return_val_if_fail(), we want the memory barrier */
1195 if (!check_initialized (connection))
1196 return G_DBUS_CAPABILITY_FLAGS_NONE;
1198 return connection->capabilities;
1201 /* ---------------------------------------------------------------------------------------------------- */
1203 /* Called in a temporary thread without holding locks. */
1205 flush_in_thread_func (GSimpleAsyncResult *res,
1207 GCancellable *cancellable)
1212 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1215 g_simple_async_result_take_error (res, error);
1219 * g_dbus_connection_flush:
1220 * @connection: A #GDBusConnection.
1221 * @cancellable: (allow-none): A #GCancellable or %NULL.
1222 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1223 * satisfied or %NULL if you don't care about the result.
1224 * @user_data: The data to pass to @callback.
1226 * Asynchronously flushes @connection, that is, writes all queued
1227 * outgoing message to the transport and then flushes the transport
1228 * (using g_output_stream_flush_async()). This is useful in programs
1229 * that wants to emit a D-Bus signal and then exit
1230 * immediately. Without flushing the connection, there is no guarantee
1231 * that the message has been sent to the networking buffers in the OS
1234 * This is an asynchronous method. When the operation is finished,
1235 * @callback will be invoked in the <link
1236 * linkend="g-main-context-push-thread-default">thread-default main
1237 * loop</link> of the thread you are calling this method from. You can
1238 * then call g_dbus_connection_flush_finish() to get the result of the
1239 * operation. See g_dbus_connection_flush_sync() for the synchronous
1245 g_dbus_connection_flush (GDBusConnection *connection,
1246 GCancellable *cancellable,
1247 GAsyncReadyCallback callback,
1250 GSimpleAsyncResult *simple;
1252 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1254 simple = g_simple_async_result_new (G_OBJECT (connection),
1257 g_dbus_connection_flush);
1258 g_simple_async_result_set_check_cancellable (simple, cancellable);
1259 g_simple_async_result_run_in_thread (simple,
1260 flush_in_thread_func,
1263 g_object_unref (simple);
1267 * g_dbus_connection_flush_finish:
1268 * @connection: A #GDBusConnection.
1269 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1270 * @error: Return location for error or %NULL.
1272 * Finishes an operation started with g_dbus_connection_flush().
1274 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1279 g_dbus_connection_flush_finish (GDBusConnection *connection,
1283 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1288 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1289 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1290 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1292 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1294 if (g_simple_async_result_propagate_error (simple, error))
1304 * g_dbus_connection_flush_sync:
1305 * @connection: A #GDBusConnection.
1306 * @cancellable: (allow-none): A #GCancellable or %NULL.
1307 * @error: Return location for error or %NULL.
1309 * Synchronously flushes @connection. The calling thread is blocked
1310 * until this is done. See g_dbus_connection_flush() for the
1311 * asynchronous version of this method and more details about what it
1314 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1319 g_dbus_connection_flush_sync (GDBusConnection *connection,
1320 GCancellable *cancellable,
1325 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1326 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1330 /* This is only a best-effort attempt to see whether the connection is
1331 * closed, so it doesn't need the lock. If the connection closes just
1332 * after this check, but before scheduling the flush operation, the
1333 * result will be more or less the same as if the connection closed while
1334 * the flush operation was pending - it'll fail with either CLOSED or
1337 if (!check_unclosed (connection, 0, error))
1340 g_assert (connection->worker != NULL);
1342 ret = _g_dbus_worker_flush_sync (connection->worker,
1350 /* ---------------------------------------------------------------------------------------------------- */
1354 GDBusConnection *connection;
1356 gboolean remote_peer_vanished;
1360 emit_closed_data_free (EmitClosedData *data)
1362 g_object_unref (data->connection);
1363 if (data->error != NULL)
1364 g_error_free (data->error);
1368 /* Called in a user thread that has acquired the main context that was
1369 * thread-default when the object was constructed
1372 emit_closed_in_idle (gpointer user_data)
1374 EmitClosedData *data = user_data;
1377 g_object_notify (G_OBJECT (data->connection), "closed");
1378 g_signal_emit (data->connection,
1379 signals[CLOSED_SIGNAL],
1381 data->remote_peer_vanished,
1387 /* Can be called from any thread, must hold lock.
1388 * FLAG_CLOSED must already have been set.
1391 schedule_closed_unlocked (GDBusConnection *connection,
1392 gboolean remote_peer_vanished,
1395 GSource *idle_source;
1396 EmitClosedData *data;
1398 CONNECTION_ENSURE_LOCK (connection);
1400 data = g_new0 (EmitClosedData, 1);
1401 data->connection = g_object_ref (connection);
1402 data->remote_peer_vanished = remote_peer_vanished;
1403 data->error = error != NULL ? g_error_copy (error) : NULL;
1405 idle_source = g_idle_source_new ();
1406 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1407 g_source_set_callback (idle_source,
1408 emit_closed_in_idle,
1410 (GDestroyNotify) emit_closed_data_free);
1411 g_source_attach (idle_source, connection->main_context_at_construction);
1412 g_source_unref (idle_source);
1415 /* ---------------------------------------------------------------------------------------------------- */
1418 * g_dbus_connection_close:
1419 * @connection: A #GDBusConnection.
1420 * @cancellable: (allow-none): A #GCancellable or %NULL.
1421 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1422 * satisfied or %NULL if you don't care about the result.
1423 * @user_data: The data to pass to @callback.
1425 * Closes @connection. Note that this never causes the process to
1426 * exit (this might only happen if the other end of a shared message
1427 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1429 * Once the connection is closed, operations such as sending a message
1430 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1431 * will not automatically flush the connection so queued messages may
1432 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1434 * If @connection is already closed, this method fails with
1435 * %G_IO_ERROR_CLOSED.
1437 * When @connection has been closed, the #GDBusConnection::closed
1438 * signal is emitted in the <link
1439 * linkend="g-main-context-push-thread-default">thread-default main
1440 * loop</link> of the thread that @connection was constructed in.
1442 * This is an asynchronous method. When the operation is finished,
1443 * @callback will be invoked in the <link
1444 * linkend="g-main-context-push-thread-default">thread-default main
1445 * loop</link> of the thread you are calling this method from. You can
1446 * then call g_dbus_connection_close_finish() to get the result of the
1447 * operation. See g_dbus_connection_close_sync() for the synchronous
1453 g_dbus_connection_close (GDBusConnection *connection,
1454 GCancellable *cancellable,
1455 GAsyncReadyCallback callback,
1458 GSimpleAsyncResult *simple;
1460 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1462 /* do not use g_return_val_if_fail(), we want the memory barrier */
1463 if (!check_initialized (connection))
1466 g_assert (connection->worker != NULL);
1468 simple = g_simple_async_result_new (G_OBJECT (connection),
1471 g_dbus_connection_close);
1472 g_simple_async_result_set_check_cancellable (simple, cancellable);
1473 _g_dbus_worker_close (connection->worker, cancellable, simple);
1474 g_object_unref (simple);
1478 * g_dbus_connection_close_finish:
1479 * @connection: A #GDBusConnection.
1480 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1481 * @error: Return location for error or %NULL.
1483 * Finishes an operation started with g_dbus_connection_close().
1485 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1490 g_dbus_connection_close_finish (GDBusConnection *connection,
1494 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1499 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1500 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1501 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1503 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1505 if (g_simple_async_result_propagate_error (simple, error))
1516 GAsyncResult *result;
1519 /* Can be called by any thread, without the connection lock */
1521 sync_close_cb (GObject *source_object,
1525 SyncCloseData *data = user_data;
1527 data->result = g_object_ref (res);
1528 g_main_loop_quit (data->loop);
1532 * g_dbus_connection_close_sync:
1533 * @connection: A #GDBusConnection.
1534 * @cancellable: (allow-none): A #GCancellable or %NULL.
1535 * @error: Return location for error or %NULL.
1537 * Synchronously closees @connection. The calling thread is blocked
1538 * until this is done. See g_dbus_connection_close() for the
1539 * asynchronous version of this method and more details about what it
1542 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1547 g_dbus_connection_close_sync (GDBusConnection *connection,
1548 GCancellable *cancellable,
1553 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1554 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1558 if (check_unclosed (connection, 0, error))
1560 GMainContext *context;
1563 context = g_main_context_new ();
1564 g_main_context_push_thread_default (context);
1565 data.loop = g_main_loop_new (context, TRUE);
1568 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1569 g_main_loop_run (data.loop);
1570 ret = g_dbus_connection_close_finish (connection, data.result, error);
1572 g_object_unref (data.result);
1573 g_main_loop_unref (data.loop);
1574 g_main_context_pop_thread_default (context);
1575 g_main_context_unref (context);
1581 /* ---------------------------------------------------------------------------------------------------- */
1584 * g_dbus_connection_get_last_serial:
1585 * @connection: A #GDBusConnection.
1587 * Retrieves the last serial number assigned to a #GDBusMessage on
1588 * the current thread. This includes messages sent via both low-level
1589 * API such as g_dbus_connection_send_message() as well as
1590 * high-level API such as g_dbus_connection_emit_signal(),
1591 * g_dbus_connection_call() or g_dbus_proxy_call().
1593 * Returns: the last used serial or zero when no message has been sent
1594 * within the current thread.
1599 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1603 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1605 CONNECTION_LOCK (connection);
1606 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1608 CONNECTION_UNLOCK (connection);
1613 /* ---------------------------------------------------------------------------------------------------- */
1615 /* Can be called by any thread, with the connection lock held */
1617 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1618 GDBusMessage *message,
1619 GDBusSendMessageFlags flags,
1620 volatile guint32 *out_serial,
1625 guint32 serial_to_use;
1628 CONNECTION_ENSURE_LOCK (connection);
1630 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1631 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1633 /* TODO: check all necessary headers are present */
1638 if (out_serial != NULL)
1641 /* If we're in initable_init(), don't check for being initialized, to avoid
1642 * chicken-and-egg problems. initable_init() is responsible for setting up
1643 * our prerequisites (mainly connection->worker), and only calling us
1644 * from its own thread (so no memory barrier is needed).
1646 if (!check_unclosed (connection,
1647 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1651 if(g_kdbus_get_sender(g_dbus_worker_get_kdbus(connection->worker)) != NULL)
1653 g_dbus_message_set_sender(message, g_kdbus_get_sender(g_dbus_worker_get_kdbus(connection->worker)));
1654 g_print ("g_dbus_connection_send_message_unlocked: set_sender ok: ! \n");
1657 blob = g_dbus_message_to_blob (message,
1659 connection->capabilities,
1664 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1665 serial_to_use = g_dbus_message_get_serial (message);
1667 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1672 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1675 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1678 g_assert_not_reached ();
1683 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1684 blob_size, serial_to_use, connection);
1685 g_printerr ("----\n");
1686 hexdump (blob, blob_size);
1687 g_printerr ("----\n");
1690 /* TODO: use connection->auth to encode the blob */
1692 if (out_serial != NULL)
1693 *out_serial = serial_to_use;
1695 /* store used serial for the current thread */
1696 /* TODO: watch the thread disposal and remove associated record
1698 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1700 g_hash_table_replace (connection->map_thread_to_last_serial,
1702 GUINT_TO_POINTER (serial_to_use));
1704 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1705 g_dbus_message_set_serial (message, serial_to_use);
1707 g_dbus_message_lock (message);
1708 _g_dbus_worker_send_message (connection->worker,
1712 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1723 * g_dbus_connection_send_message:
1724 * @connection: A #GDBusConnection.
1725 * @message: A #GDBusMessage
1726 * @flags: Flags affecting how the message is sent.
1727 * @out_serial: (out) (allow-none): Return location for serial number assigned
1728 * to @message when sending it or %NULL.
1729 * @error: Return location for error or %NULL.
1731 * Asynchronously sends @message to the peer represented by @connection.
1733 * Unless @flags contain the
1734 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1735 * will be assigned by @connection and set on @message via
1736 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1737 * serial number used will be written to this location prior to
1738 * submitting the message to the underlying transport.
1740 * If @connection is closed then the operation will fail with
1741 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1742 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1744 * See <xref linkend="gdbus-server"/> and <xref
1745 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1746 * low-level API to send and receive UNIX file descriptors.
1748 * Note that @message must be unlocked, unless @flags contain the
1749 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1751 * Returns: %TRUE if the message was well-formed and queued for
1752 * transmission, %FALSE if @error is set.
1757 g_dbus_connection_send_message (GDBusConnection *connection,
1758 GDBusMessage *message,
1759 GDBusSendMessageFlags flags,
1760 volatile guint32 *out_serial,
1765 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1766 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1767 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1768 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1770 CONNECTION_LOCK (connection);
1771 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1772 CONNECTION_UNLOCK (connection);
1776 /* ---------------------------------------------------------------------------------------------------- */
1780 volatile gint ref_count;
1781 GDBusConnection *connection;
1783 GSimpleAsyncResult *simple;
1785 GMainContext *main_context;
1787 GCancellable *cancellable;
1789 gulong cancellable_handler_id;
1791 GSource *timeout_source;
1796 /* Can be called from any thread with or without lock held */
1797 static SendMessageData *
1798 send_message_data_ref (SendMessageData *data)
1800 g_atomic_int_inc (&data->ref_count);
1804 /* Can be called from any thread with or without lock held */
1806 send_message_data_unref (SendMessageData *data)
1808 if (g_atomic_int_dec_and_test (&data->ref_count))
1810 g_assert (data->timeout_source == NULL);
1811 g_assert (data->simple == NULL);
1812 g_assert (data->cancellable_handler_id == 0);
1813 g_object_unref (data->connection);
1814 if (data->cancellable != NULL)
1815 g_object_unref (data->cancellable);
1816 g_main_context_unref (data->main_context);
1821 /* ---------------------------------------------------------------------------------------------------- */
1823 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1825 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1827 CONNECTION_ENSURE_LOCK (data->connection);
1829 g_assert (!data->delivered);
1831 data->delivered = TRUE;
1833 g_simple_async_result_complete_in_idle (data->simple);
1834 g_object_unref (data->simple);
1835 data->simple = NULL;
1837 if (data->timeout_source != NULL)
1839 g_source_destroy (data->timeout_source);
1840 data->timeout_source = NULL;
1842 if (data->cancellable_handler_id > 0)
1844 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1845 data->cancellable_handler_id = 0;
1850 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1851 GUINT_TO_POINTER (data->serial)));
1854 send_message_data_unref (data);
1857 /* ---------------------------------------------------------------------------------------------------- */
1859 /* Can be called from any thread with lock held */
1861 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1862 GDBusMessage *reply)
1864 if (data->delivered)
1867 g_simple_async_result_set_op_res_gpointer (data->simple,
1868 g_object_ref (reply),
1871 send_message_with_reply_deliver (data, TRUE);
1877 /* ---------------------------------------------------------------------------------------------------- */
1879 /* Called from a user thread, lock is not held */
1881 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1883 SendMessageData *data = user_data;
1885 CONNECTION_LOCK (data->connection);
1886 if (data->delivered)
1889 g_simple_async_result_set_error (data->simple,
1891 G_IO_ERROR_CANCELLED,
1892 _("Operation was cancelled"));
1894 send_message_with_reply_deliver (data, TRUE);
1897 CONNECTION_UNLOCK (data->connection);
1901 /* Can be called from any thread with or without lock held */
1903 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1906 SendMessageData *data = user_data;
1907 GSource *idle_source;
1909 /* postpone cancellation to idle handler since we may be called directly
1910 * via g_cancellable_connect() (e.g. holding lock)
1912 idle_source = g_idle_source_new ();
1913 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1914 g_source_set_callback (idle_source,
1915 send_message_with_reply_cancelled_idle_cb,
1916 send_message_data_ref (data),
1917 (GDestroyNotify) send_message_data_unref);
1918 g_source_attach (idle_source, data->main_context);
1919 g_source_unref (idle_source);
1922 /* ---------------------------------------------------------------------------------------------------- */
1924 /* Called from a user thread, lock is not held */
1926 send_message_with_reply_timeout_cb (gpointer user_data)
1928 SendMessageData *data = user_data;
1930 CONNECTION_LOCK (data->connection);
1931 if (data->delivered)
1934 g_simple_async_result_set_error (data->simple,
1936 G_IO_ERROR_TIMED_OUT,
1937 _("Timeout was reached"));
1939 send_message_with_reply_deliver (data, TRUE);
1942 CONNECTION_UNLOCK (data->connection);
1947 /* ---------------------------------------------------------------------------------------------------- */
1949 /* Called from a user thread, connection's lock is held */
1951 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1952 GDBusMessage *message,
1953 GDBusSendMessageFlags flags,
1955 volatile guint32 *out_serial,
1956 GCancellable *cancellable,
1957 GAsyncReadyCallback callback,
1960 GSimpleAsyncResult *simple;
1961 SendMessageData *data;
1963 volatile guint32 serial;
1967 if (out_serial == NULL)
1968 out_serial = &serial;
1970 if (timeout_msec == -1)
1971 timeout_msec = 25 * 1000;
1973 simple = g_simple_async_result_new (G_OBJECT (connection),
1976 g_dbus_connection_send_message_with_reply);
1977 g_simple_async_result_set_check_cancellable (simple, cancellable);
1979 if (g_cancellable_is_cancelled (cancellable))
1981 g_simple_async_result_set_error (simple,
1983 G_IO_ERROR_CANCELLED,
1984 _("Operation was cancelled"));
1985 g_simple_async_result_complete_in_idle (simple);
1986 g_object_unref (simple);
1991 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1993 g_simple_async_result_take_error (simple, error);
1994 g_simple_async_result_complete_in_idle (simple);
1995 g_object_unref (simple);
1999 data = g_new0 (SendMessageData, 1);
2000 data->ref_count = 1;
2001 data->connection = g_object_ref (connection);
2002 data->simple = simple;
2003 data->serial = *out_serial;
2004 data->main_context = g_main_context_ref_thread_default ();
2006 if (cancellable != NULL)
2008 data->cancellable = g_object_ref (cancellable);
2009 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2010 G_CALLBACK (send_message_with_reply_cancelled_cb),
2011 send_message_data_ref (data),
2012 (GDestroyNotify) send_message_data_unref);
2015 if (timeout_msec != G_MAXINT)
2017 data->timeout_source = g_timeout_source_new (timeout_msec);
2018 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2019 g_source_set_callback (data->timeout_source,
2020 send_message_with_reply_timeout_cb,
2021 send_message_data_ref (data),
2022 (GDestroyNotify) send_message_data_unref);
2023 g_source_attach (data->timeout_source, data->main_context);
2024 g_source_unref (data->timeout_source);
2027 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2028 GUINT_TO_POINTER (*out_serial),
2036 * g_dbus_connection_send_message_with_reply:
2037 * @connection: A #GDBusConnection.
2038 * @message: A #GDBusMessage.
2039 * @flags: Flags affecting how the message is sent.
2040 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2041 * timeout or %G_MAXINT for no timeout.
2042 * @out_serial: (out) (allow-none): Return location for serial number assigned
2043 * to @message when sending it or %NULL.
2044 * @cancellable: (allow-none): A #GCancellable or %NULL.
2045 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
2046 * satisfied or %NULL if you don't care about the result.
2047 * @user_data: The data to pass to @callback.
2049 * Asynchronously sends @message to the peer represented by @connection.
2051 * Unless @flags contain the
2052 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2053 * will be assigned by @connection and set on @message via
2054 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2055 * serial number used will be written to this location prior to
2056 * submitting the message to the underlying transport.
2058 * If @connection is closed then the operation will fail with
2059 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2060 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2061 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2063 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2064 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2065 * of the thread you are calling this method from. You can then call
2066 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2067 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2069 * Note that @message must be unlocked, unless @flags contain the
2070 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2072 * See <xref linkend="gdbus-server"/> and <xref
2073 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2074 * low-level API to send and receive UNIX file descriptors.
2079 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2080 GDBusMessage *message,
2081 GDBusSendMessageFlags flags,
2083 volatile guint32 *out_serial,
2084 GCancellable *cancellable,
2085 GAsyncReadyCallback callback,
2088 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2089 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2090 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2091 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2093 CONNECTION_LOCK (connection);
2094 g_dbus_connection_send_message_with_reply_unlocked (connection,
2102 CONNECTION_UNLOCK (connection);
2106 * g_dbus_connection_send_message_with_reply_finish:
2107 * @connection: a #GDBusConnection
2108 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2109 * @error: Return location for error or %NULL.
2111 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2113 * Note that @error is only set if a local in-process error
2114 * occurred. That is to say that the returned #GDBusMessage object may
2115 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2116 * g_dbus_message_to_gerror() to transcode this to a #GError.
2118 * See <xref linkend="gdbus-server"/> and <xref
2119 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2120 * low-level API to send and receive UNIX file descriptors.
2122 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2127 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2131 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2132 GDBusMessage *reply;
2134 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2135 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2139 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2141 if (g_simple_async_result_propagate_error (simple, error))
2144 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2150 /* ---------------------------------------------------------------------------------------------------- */
2155 GMainContext *context;
2157 } SendMessageSyncData;
2159 /* Called from a user thread, lock is not held */
2161 send_message_with_reply_sync_cb (GDBusConnection *connection,
2165 SendMessageSyncData *data = user_data;
2166 data->res = g_object_ref (res);
2167 g_main_loop_quit (data->loop);
2171 * g_dbus_connection_send_message_with_reply_sync:
2172 * @connection: A #GDBusConnection.
2173 * @message: A #GDBusMessage.
2174 * @flags: Flags affecting how the message is sent.
2175 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2176 * timeout or %G_MAXINT for no timeout.
2177 * @out_serial: (out) (allow-none): Return location for serial number assigned
2178 * to @message when sending it or %NULL.
2179 * @cancellable: (allow-none): A #GCancellable or %NULL.
2180 * @error: Return location for error or %NULL.
2182 * Synchronously sends @message to the peer represented by @connection
2183 * and blocks the calling thread until a reply is received or the
2184 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2185 * for the asynchronous version of this method.
2187 * Unless @flags contain the
2188 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2189 * will be assigned by @connection and set on @message via
2190 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2191 * serial number used will be written to this location prior to
2192 * submitting the message to the underlying transport.
2194 * If @connection is closed then the operation will fail with
2195 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2196 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2197 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2199 * Note that @error is only set if a local in-process error
2200 * occurred. That is to say that the returned #GDBusMessage object may
2201 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2202 * g_dbus_message_to_gerror() to transcode this to a #GError.
2204 * See <xref linkend="gdbus-server"/> and <xref
2205 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2206 * low-level API to send and receive UNIX file descriptors.
2208 * Note that @message must be unlocked, unless @flags contain the
2209 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2211 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2216 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2217 GDBusMessage *message,
2218 GDBusSendMessageFlags flags,
2220 volatile guint32 *out_serial,
2221 GCancellable *cancellable,
2224 SendMessageSyncData *data;
2225 GDBusMessage *reply;
2227 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2228 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2229 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2230 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2231 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2233 data = g_new0 (SendMessageSyncData, 1);
2234 data->context = g_main_context_new ();
2235 data->loop = g_main_loop_new (data->context, FALSE);
2237 g_main_context_push_thread_default (data->context);
2239 g_dbus_connection_send_message_with_reply (connection,
2245 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2247 g_main_loop_run (data->loop);
2248 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2252 g_main_context_pop_thread_default (data->context);
2254 g_main_context_unref (data->context);
2255 g_main_loop_unref (data->loop);
2256 g_object_unref (data->res);
2262 /* ---------------------------------------------------------------------------------------------------- */
2266 GDBusMessageFilterFunction func;
2273 GDBusMessageFilterFunction filter_function;
2275 GDestroyNotify user_data_free_func;
2278 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2280 on_worker_message_received (GDBusWorker *worker,
2281 GDBusMessage *message,
2284 GDBusConnection *connection;
2285 FilterCallback *filters;
2290 G_LOCK (message_bus_lock);
2291 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2294 G_UNLOCK (message_bus_lock);
2297 connection = G_DBUS_CONNECTION (user_data);
2298 g_object_ref (connection);
2299 G_UNLOCK (message_bus_lock);
2301 //g_debug ("in on_worker_message_received");
2303 g_object_ref (message);
2304 g_dbus_message_lock (message);
2306 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2308 /* First collect the set of callback functions */
2309 CONNECTION_LOCK (connection);
2310 num_filters = connection->filters->len;
2311 filters = g_new0 (FilterCallback, num_filters);
2312 for (n = 0; n < num_filters; n++)
2314 FilterData *data = connection->filters->pdata[n];
2315 filters[n].func = data->filter_function;
2316 filters[n].user_data = data->user_data;
2318 CONNECTION_UNLOCK (connection);
2320 /* then call the filters in order (without holding the lock) */
2321 for (n = 0; n < num_filters; n++)
2323 message = filters[n].func (connection,
2326 filters[n].user_data);
2327 if (message == NULL)
2329 g_dbus_message_lock (message);
2332 /* Standard dispatch unless the filter ate the message - no need to
2333 * do anything if the message was altered
2335 if (message != NULL)
2337 GDBusMessageType message_type;
2339 message_type = g_dbus_message_get_message_type (message);
2340 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2342 guint32 reply_serial;
2343 SendMessageData *send_message_data;
2345 reply_serial = g_dbus_message_get_reply_serial (message);
2346 CONNECTION_LOCK (connection);
2347 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2348 GUINT_TO_POINTER (reply_serial));
2349 if (send_message_data != NULL)
2351 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2352 send_message_data_deliver_reply_unlocked (send_message_data, message);
2356 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2358 CONNECTION_UNLOCK (connection);
2360 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2362 CONNECTION_LOCK (connection);
2363 distribute_signals (connection, message);
2364 CONNECTION_UNLOCK (connection);
2366 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2368 CONNECTION_LOCK (connection);
2369 distribute_method_call (connection, message);
2370 CONNECTION_UNLOCK (connection);
2374 if (message != NULL)
2375 g_object_unref (message);
2376 g_object_unref (connection);
2380 /* Called in GDBusWorker's thread, lock is not held */
2381 static GDBusMessage *
2382 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2383 GDBusMessage *message,
2386 GDBusConnection *connection;
2387 FilterCallback *filters;
2392 G_LOCK (message_bus_lock);
2393 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2396 G_UNLOCK (message_bus_lock);
2399 connection = G_DBUS_CONNECTION (user_data);
2400 g_object_ref (connection);
2401 G_UNLOCK (message_bus_lock);
2403 //g_debug ("in on_worker_message_about_to_be_sent");
2405 /* First collect the set of callback functions */
2406 CONNECTION_LOCK (connection);
2407 num_filters = connection->filters->len;
2408 filters = g_new0 (FilterCallback, num_filters);
2409 for (n = 0; n < num_filters; n++)
2411 FilterData *data = connection->filters->pdata[n];
2412 filters[n].func = data->filter_function;
2413 filters[n].user_data = data->user_data;
2415 CONNECTION_UNLOCK (connection);
2417 /* then call the filters in order (without holding the lock) */
2418 for (n = 0; n < num_filters; n++)
2420 g_dbus_message_lock (message);
2421 message = filters[n].func (connection,
2424 filters[n].user_data);
2425 if (message == NULL)
2429 g_object_unref (connection);
2435 /* called with connection lock held, in GDBusWorker thread */
2437 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2439 SendMessageData *data = value;
2441 if (data->delivered)
2444 g_simple_async_result_set_error (data->simple,
2447 _("The connection is closed"));
2449 /* Ask send_message_with_reply_deliver not to remove the element from the
2450 * hash table - we're in the middle of a foreach; that would be unsafe.
2451 * Instead, return TRUE from this function so that it gets removed safely.
2453 send_message_with_reply_deliver (data, FALSE);
2457 /* Called in GDBusWorker's thread - we must not block - without lock held */
2459 on_worker_closed (GDBusWorker *worker,
2460 gboolean remote_peer_vanished,
2464 GDBusConnection *connection;
2466 guint old_atomic_flags;
2468 G_LOCK (message_bus_lock);
2469 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2472 G_UNLOCK (message_bus_lock);
2475 connection = G_DBUS_CONNECTION (user_data);
2476 g_object_ref (connection);
2477 G_UNLOCK (message_bus_lock);
2479 //g_debug ("in on_worker_closed: %s", error->message);
2481 CONNECTION_LOCK (connection);
2482 /* Even though this is atomic, we do it inside the lock to avoid breaking
2483 * assumptions in remove_match_rule(). We'd need the lock in a moment
2484 * anyway, so, no loss.
2486 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2488 if (!(old_atomic_flags & FLAG_CLOSED))
2490 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2491 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2493 CONNECTION_UNLOCK (connection);
2495 g_object_unref (connection);
2498 /* ---------------------------------------------------------------------------------------------------- */
2500 /* Determines the biggest set of capabilities we can support on this
2503 * Called with the init_lock held.
2505 static GDBusCapabilityFlags
2506 get_offered_capabilities_max (GDBusConnection *connection)
2508 GDBusCapabilityFlags ret;
2509 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2511 if (G_IS_UNIX_CONNECTION (connection->stream))
2512 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2517 /* Called in a user thread, lock is not held */
2519 initable_init (GInitable *initable,
2520 GCancellable *cancellable,
2523 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2526 /* This method needs to be idempotent to work with the singleton
2527 * pattern. See the docs for g_initable_init(). We implement this by
2530 * Unfortunately we can't use the main lock since the on_worker_*()
2531 * callbacks above needs the lock during initialization (for message
2532 * bus connections we do a synchronous Hello() call on the bus).
2534 g_mutex_lock (&connection->init_lock);
2538 /* Make this a no-op if we're already initialized (successfully or
2541 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2543 ret = (connection->initialization_error == NULL);
2547 /* Because of init_lock, we can't get here twice in different threads */
2548 g_assert (connection->initialization_error == NULL);
2550 /* The user can pass multiple (but mutally exclusive) construct
2553 * - stream (of type GIOStream)
2554 * - address (of type gchar*)
2556 * At the end of the day we end up with a non-NULL GIOStream
2557 * object in connection->stream.
2559 if (connection->address != NULL)
2561 g_assert (connection->stream == NULL);
2563 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2564 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2566 g_set_error_literal (&connection->initialization_error,
2568 G_IO_ERROR_INVALID_ARGUMENT,
2569 _("Unsupported flags encountered when constructing a client-side connection"));
2573 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2574 NULL, /* TODO: out_guid */
2576 &connection->initialization_error);
2577 if (connection->stream == NULL)
2580 else if (connection->stream != NULL)
2586 g_assert_not_reached ();
2589 if (!G_IS_KDBUS_CONNECTION (connection->stream))
2591 /* Authenticate the connection */
2592 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2594 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2595 g_assert (connection->guid != NULL);
2596 connection->auth = _g_dbus_auth_new (connection->stream);
2597 if (!_g_dbus_auth_run_server (connection->auth,
2598 connection->authentication_observer,
2600 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2601 get_offered_capabilities_max (connection),
2602 &connection->capabilities,
2603 &connection->credentials,
2605 &connection->initialization_error))
2608 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2610 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2611 g_assert (connection->guid == NULL);
2612 connection->auth = _g_dbus_auth_new (connection->stream);
2613 connection->guid = _g_dbus_auth_run_client (connection->auth,
2614 connection->authentication_observer,
2615 get_offered_capabilities_max (connection),
2616 &connection->capabilities,
2618 &connection->initialization_error);
2619 if (connection->guid == NULL)
2623 if (connection->authentication_observer != NULL)
2625 g_object_unref (connection->authentication_observer);
2626 connection->authentication_observer = NULL;
2629 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2631 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2634 /* We want all IO operations to be non-blocking since they happen in
2635 * the worker thread which is shared by _all_ connections.
2637 if (G_IS_SOCKET_CONNECTION (connection->stream))
2639 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2643 G_LOCK (message_bus_lock);
2644 if (alive_connections == NULL)
2645 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2646 g_hash_table_insert (alive_connections, connection, connection);
2647 G_UNLOCK (message_bus_lock);
2649 connection->worker = _g_dbus_worker_new (connection->stream,
2650 connection->capabilities,
2651 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2652 on_worker_message_received,
2653 on_worker_message_about_to_be_sent,
2657 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2658 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2660 GVariant *hello_result;
2662 /* we could lift this restriction by adding code in gdbusprivate.c */
2663 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2665 g_set_error_literal (&connection->initialization_error,
2668 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2672 hello_result = g_dbus_connection_call_sync (connection,
2673 "org.freedesktop.DBus", /* name */
2674 "/org/freedesktop/DBus", /* path */
2675 "org.freedesktop.DBus", /* interface */
2677 NULL, /* parameters */
2678 G_VARIANT_TYPE ("(s)"),
2679 CALL_FLAGS_INITIALIZING,
2681 NULL, /* TODO: cancellable */
2682 &connection->initialization_error);
2683 if (hello_result == NULL)
2686 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2687 g_variant_unref (hello_result);
2688 //g_debug ("unique name is `%s'", connection->bus_unique_name);
2695 g_assert (connection->initialization_error != NULL);
2696 g_propagate_error (error, g_error_copy (connection->initialization_error));
2699 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2700 g_mutex_unlock (&connection->init_lock);
2706 initable_iface_init (GInitableIface *initable_iface)
2708 initable_iface->init = initable_init;
2711 /* ---------------------------------------------------------------------------------------------------- */
2714 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2719 /* ---------------------------------------------------------------------------------------------------- */
2722 * g_dbus_connection_new:
2723 * @stream: A #GIOStream.
2724 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2725 * @flags: Flags describing how to make the connection.
2726 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2727 * @cancellable: (allow-none): A #GCancellable or %NULL.
2728 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2729 * @user_data: The data to pass to @callback.
2731 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2732 * with the end represented by @stream.
2734 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2735 * will be put into non-blocking mode.
2737 * The D-Bus connection will interact with @stream from a worker thread.
2738 * As a result, the caller should not interact with @stream after this
2739 * method has been called, except by calling g_object_unref() on it.
2741 * If @observer is not %NULL it may be used to control the
2742 * authentication process.
2744 * When the operation is finished, @callback will be invoked. You can
2745 * then call g_dbus_connection_new_finish() to get the result of the
2748 * This is a asynchronous failable constructor. See
2749 * g_dbus_connection_new_sync() for the synchronous
2755 g_dbus_connection_new (GIOStream *stream,
2757 GDBusConnectionFlags flags,
2758 GDBusAuthObserver *observer,
2759 GCancellable *cancellable,
2760 GAsyncReadyCallback callback,
2763 g_return_if_fail (G_IS_IO_STREAM (stream));
2764 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2772 "authentication-observer", observer,
2777 * g_dbus_connection_new_finish:
2778 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2779 * @error: Return location for error or %NULL.
2781 * Finishes an operation started with g_dbus_connection_new().
2783 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2788 g_dbus_connection_new_finish (GAsyncResult *res,
2792 GObject *source_object;
2794 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2795 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2797 source_object = g_async_result_get_source_object (res);
2798 g_assert (source_object != NULL);
2799 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2802 g_object_unref (source_object);
2804 return G_DBUS_CONNECTION (object);
2810 * g_dbus_connection_new_sync:
2811 * @stream: A #GIOStream.
2812 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2813 * @flags: Flags describing how to make the connection.
2814 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2815 * @cancellable: (allow-none): A #GCancellable or %NULL.
2816 * @error: Return location for error or %NULL.
2818 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2819 * with the end represented by @stream.
2821 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2822 * will be put into non-blocking mode.
2824 * The D-Bus connection will interact with @stream from a worker thread.
2825 * As a result, the caller should not interact with @stream after this
2826 * method has been called, except by calling g_object_unref() on it.
2828 * If @observer is not %NULL it may be used to control the
2829 * authentication process.
2831 * This is a synchronous failable constructor. See
2832 * g_dbus_connection_new() for the asynchronous version.
2834 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2839 g_dbus_connection_new_sync (GIOStream *stream,
2841 GDBusConnectionFlags flags,
2842 GDBusAuthObserver *observer,
2843 GCancellable *cancellable,
2846 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2847 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2848 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2854 "authentication-observer", observer,
2858 /* ---------------------------------------------------------------------------------------------------- */
2861 * g_dbus_connection_new_for_address:
2862 * @address: A D-Bus address.
2863 * @flags: Flags describing how to make the connection.
2864 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2865 * @cancellable: (allow-none): A #GCancellable or %NULL.
2866 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2867 * @user_data: The data to pass to @callback.
2869 * Asynchronously connects and sets up a D-Bus client connection for
2870 * exchanging D-Bus messages with an endpoint specified by @address
2871 * which must be in the D-Bus address format.
2873 * This constructor can only be used to initiate client-side
2874 * connections - use g_dbus_connection_new() if you need to act as the
2875 * server. In particular, @flags cannot contain the
2876 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2877 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2879 * When the operation is finished, @callback will be invoked. You can
2880 * then call g_dbus_connection_new_finish() to get the result of the
2883 * If @observer is not %NULL it may be used to control the
2884 * authentication process.
2886 * This is a asynchronous failable constructor. See
2887 * g_dbus_connection_new_for_address_sync() for the synchronous
2893 g_dbus_connection_new_for_address (const gchar *address,
2894 GDBusConnectionFlags flags,
2895 GDBusAuthObserver *observer,
2896 GCancellable *cancellable,
2897 GAsyncReadyCallback callback,
2900 g_return_if_fail (address != NULL);
2901 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2908 "authentication-observer", observer,
2913 * g_dbus_connection_new_for_address_finish:
2914 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2915 * @error: Return location for error or %NULL.
2917 * Finishes an operation started with g_dbus_connection_new_for_address().
2919 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2924 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2928 GObject *source_object;
2930 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2931 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2933 source_object = g_async_result_get_source_object (res);
2934 g_assert (source_object != NULL);
2935 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2938 g_object_unref (source_object);
2940 return G_DBUS_CONNECTION (object);
2946 * g_dbus_connection_new_for_address_sync:
2947 * @address: A D-Bus address.
2948 * @flags: Flags describing how to make the connection.
2949 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2950 * @cancellable: (allow-none): A #GCancellable or %NULL.
2951 * @error: Return location for error or %NULL.
2953 * Synchronously connects and sets up a D-Bus client connection for
2954 * exchanging D-Bus messages with an endpoint specified by @address
2955 * which must be in the D-Bus address format.
2957 * This constructor can only be used to initiate client-side
2958 * connections - use g_dbus_connection_new_sync() if you need to act
2959 * as the server. In particular, @flags cannot contain the
2960 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2961 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2963 * This is a synchronous failable constructor. See
2964 * g_dbus_connection_new_for_address() for the asynchronous version.
2966 * If @observer is not %NULL it may be used to control the
2967 * authentication process.
2969 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2974 g_dbus_connection_new_for_address_sync (const gchar *address,
2975 GDBusConnectionFlags flags,
2976 GDBusAuthObserver *observer,
2977 GCancellable *cancellable,
2980 g_return_val_if_fail (address != NULL, NULL);
2981 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2982 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2987 "authentication-observer", observer,
2991 /* ---------------------------------------------------------------------------------------------------- */
2994 * g_dbus_connection_set_exit_on_close:
2995 * @connection: A #GDBusConnection.
2996 * @exit_on_close: Whether the process should be terminated
2997 * when @connection is closed by the remote peer.
2999 * Sets whether the process should be terminated when @connection is
3000 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3003 * Note that this function should be used with care. Most modern UNIX
3004 * desktops tie the notion of a user session the session bus, and expect
3005 * all of a users applications to quit when their bus connection goes away.
3006 * If you are setting @exit_on_close to %FALSE for the shared session
3007 * bus connection, you should make sure that your application exits
3008 * when the user session ends.
3013 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3014 gboolean exit_on_close)
3016 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3019 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3021 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3026 * g_dbus_connection_get_exit_on_close:
3027 * @connection: A #GDBusConnection.
3029 * Gets whether the process is terminated when @connection is
3030 * closed by the remote peer. See
3031 * #GDBusConnection:exit-on-close for more details.
3033 * Returns: Whether the process is terminated when @connection is
3034 * closed by the remote peer.
3039 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3041 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3043 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3050 * g_dbus_connection_get_guid:
3051 * @connection: A #GDBusConnection.
3053 * The GUID of the peer performing the role of server when
3054 * authenticating. See #GDBusConnection:guid for more details.
3056 * Returns: The GUID. Do not free this string, it is owned by
3062 g_dbus_connection_get_guid (GDBusConnection *connection)
3064 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3065 return connection->guid;
3069 * g_dbus_connection_get_unique_name:
3070 * @connection: A #GDBusConnection.
3072 * Gets the unique name of @connection as assigned by the message
3073 * bus. This can also be used to figure out if @connection is a
3074 * message bus connection.
3076 * Returns: The unique name or %NULL if @connection is not a message
3077 * bus connection. Do not free this string, it is owned by
3083 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3085 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3087 /* do not use g_return_val_if_fail(), we want the memory barrier */
3088 if (!check_initialized (connection))
3091 return connection->bus_unique_name;
3095 * g_dbus_connection_get_peer_credentials:
3096 * @connection: A #GDBusConnection.
3098 * Gets the credentials of the authenticated peer. This will always
3099 * return %NULL unless @connection acted as a server
3100 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3101 * when set up and the client passed credentials as part of the
3102 * authentication process.
3104 * In a message bus setup, the message bus is always the server and
3105 * each application is a client. So this method will always return
3106 * %NULL for message bus clients.
3108 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3109 * this object, it is owned by @connection.
3114 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3116 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3118 /* do not use g_return_val_if_fail(), we want the memory barrier */
3119 if (!check_initialized (connection))
3122 return connection->credentials;
3125 /* ---------------------------------------------------------------------------------------------------- */
3127 static guint _global_filter_id = 1;
3130 * g_dbus_connection_add_filter:
3131 * @connection: A #GDBusConnection.
3132 * @filter_function: A filter function.
3133 * @user_data: User data to pass to @filter_function.
3134 * @user_data_free_func: Function to free @user_data with when filter
3135 * is removed or %NULL.
3137 * Adds a message filter. Filters are handlers that are run on all
3138 * incoming and outgoing messages, prior to standard dispatch. Filters
3139 * are run in the order that they were added. The same handler can be
3140 * added as a filter more than once, in which case it will be run more
3141 * than once. Filters added during a filter callback won't be run on
3142 * the message being processed. Filter functions are allowed to modify
3143 * and even drop messages.
3145 * Note that filters are run in a dedicated message handling thread so
3146 * they can't block and, generally, can't do anything but signal a
3147 * worker thread. Also note that filters are rarely needed - use API
3148 * such as g_dbus_connection_send_message_with_reply(),
3149 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3151 * If a filter consumes an incoming message the message is not
3152 * dispatched anywhere else - not even the standard dispatch machinery
3153 * (that API such as g_dbus_connection_signal_subscribe() and
3154 * g_dbus_connection_send_message_with_reply() relies on) will see the
3155 * message. Similary, if a filter consumes an outgoing message, the
3156 * message will not be sent to the other peer.
3158 * Returns: A filter identifier that can be used with
3159 * g_dbus_connection_remove_filter().
3164 g_dbus_connection_add_filter (GDBusConnection *connection,
3165 GDBusMessageFilterFunction filter_function,
3167 GDestroyNotify user_data_free_func)
3171 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3172 g_return_val_if_fail (filter_function != NULL, 0);
3173 g_return_val_if_fail (check_initialized (connection), 0);
3175 CONNECTION_LOCK (connection);
3176 data = g_new0 (FilterData, 1);
3177 data->id = _global_filter_id++; /* TODO: overflow etc. */
3178 data->filter_function = filter_function;
3179 data->user_data = user_data;
3180 data->user_data_free_func = user_data_free_func;
3181 g_ptr_array_add (connection->filters, data);
3182 CONNECTION_UNLOCK (connection);
3187 /* only called from finalize(), removes all filters */
3189 purge_all_filters (GDBusConnection *connection)
3192 for (n = 0; n < connection->filters->len; n++)
3194 FilterData *data = connection->filters->pdata[n];
3195 if (data->user_data_free_func != NULL)
3196 data->user_data_free_func (data->user_data);
3202 * g_dbus_connection_remove_filter:
3203 * @connection: a #GDBusConnection
3204 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3211 g_dbus_connection_remove_filter (GDBusConnection *connection,
3215 FilterData *to_destroy;
3217 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3218 g_return_if_fail (check_initialized (connection));
3220 CONNECTION_LOCK (connection);
3222 for (n = 0; n < connection->filters->len; n++)
3224 FilterData *data = connection->filters->pdata[n];
3225 if (data->id == filter_id)
3227 g_ptr_array_remove_index (connection->filters, n);
3232 CONNECTION_UNLOCK (connection);
3234 /* do free without holding lock */
3235 if (to_destroy != NULL)
3237 if (to_destroy->user_data_free_func != NULL)
3238 to_destroy->user_data_free_func (to_destroy->user_data);
3239 g_free (to_destroy);
3243 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3247 /* ---------------------------------------------------------------------------------------------------- */
3253 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3254 gchar *interface_name;
3258 GArray *subscribers;
3263 GDBusSignalCallback callback;
3265 GDestroyNotify user_data_free_func;
3267 GMainContext *context;
3271 signal_data_free (SignalData *signal_data)
3273 g_free (signal_data->rule);
3274 g_free (signal_data->sender);
3275 g_free (signal_data->sender_unique_name);
3276 g_free (signal_data->interface_name);
3277 g_free (signal_data->member);
3278 g_free (signal_data->object_path);
3279 g_free (signal_data->arg0);
3280 g_array_free (signal_data->subscribers, TRUE);
3281 g_free (signal_data);
3285 args_to_rule (const gchar *sender,
3286 const gchar *interface_name,
3287 const gchar *member,
3288 const gchar *object_path,
3294 rule = g_string_new ("type='signal'");
3296 g_string_prepend_c (rule, '-');
3298 g_string_append_printf (rule, ",sender='%s'", sender);
3299 if (interface_name != NULL)
3300 g_string_append_printf (rule, ",interface='%s'", interface_name);
3302 g_string_append_printf (rule, ",member='%s'", member);
3303 if (object_path != NULL)
3304 g_string_append_printf (rule, ",path='%s'", object_path);
3306 g_string_append_printf (rule, ",arg0='%s'", arg0);
3308 return g_string_free (rule, FALSE);
3311 static guint _global_subscriber_id = 1;
3312 static guint _global_registration_id = 1;
3313 static guint _global_subtree_registration_id = 1;
3315 /* ---------------------------------------------------------------------------------------------------- */
3317 /* Called in a user thread, lock is held */
3319 add_match_rule (GDBusConnection *connection,
3320 const gchar *match_rule)
3323 GDBusMessage *message;
3325 if (match_rule[0] == '-')
3328 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3329 "/org/freedesktop/DBus", /* path */
3330 "org.freedesktop.DBus", /* interface */
3332 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3334 if (!g_dbus_connection_send_message_unlocked (connection,
3336 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3340 g_critical ("Error while sending AddMatch() message: %s", error->message);
3341 g_error_free (error);
3343 g_object_unref (message);
3346 /* ---------------------------------------------------------------------------------------------------- */
3348 /* Called in a user thread, lock is held */
3350 remove_match_rule (GDBusConnection *connection,
3351 const gchar *match_rule)
3354 GDBusMessage *message;
3356 if (match_rule[0] == '-')
3359 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3360 "/org/freedesktop/DBus", /* path */
3361 "org.freedesktop.DBus", /* interface */
3363 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3366 if (!g_dbus_connection_send_message_unlocked (connection,
3368 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3372 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3373 * critical; but we're holding the lock, and our caller checked whether
3374 * we were already closed, so we can't get that error.
3376 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3377 g_error_free (error);
3379 g_object_unref (message);
3382 /* ---------------------------------------------------------------------------------------------------- */
3385 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3387 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3388 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3389 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3390 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3391 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3394 /* ---------------------------------------------------------------------------------------------------- */
3397 * g_dbus_connection_signal_subscribe:
3398 * @connection: A #GDBusConnection.
3399 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3400 * or %NULL to listen from all senders.
3401 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3402 * match on all interfaces.
3403 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3404 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3405 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3406 * to match on all kinds of arguments.
3407 * @flags: Flags describing how to subscribe to the signal (currently unused).
3408 * @callback: Callback to invoke when there is a signal matching the requested data.
3409 * @user_data: User data to pass to @callback.
3410 * @user_data_free_func: (allow-none): Function to free @user_data with when
3411 * subscription is removed or %NULL.
3413 * Subscribes to signals on @connection and invokes @callback with a
3414 * whenever the signal is received. Note that @callback
3415 * will be invoked in the <link
3416 * linkend="g-main-context-push-thread-default">thread-default main
3417 * loop</link> of the thread you are calling this method from.
3419 * If @connection is not a message bus connection, @sender must be
3422 * If @sender is a well-known name note that @callback is invoked with
3423 * the unique name for the owner of @sender, not the well-known name
3424 * as one would expect. This is because the message bus rewrites the
3425 * name. As such, to avoid certain race conditions, users should be
3426 * tracking the name owner of the well-known name and use that when
3427 * processing the received signal.
3429 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3434 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3435 const gchar *sender,
3436 const gchar *interface_name,
3437 const gchar *member,
3438 const gchar *object_path,
3440 GDBusSignalFlags flags,
3441 GDBusSignalCallback callback,
3443 GDestroyNotify user_data_free_func)
3446 SignalData *signal_data;
3447 SignalSubscriber subscriber;
3448 GPtrArray *signal_data_array;
3449 const gchar *sender_unique_name;
3451 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3452 * an OOM condition. We might want to change that but that would involve making
3453 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3454 * handle that. And there's really no sensible way of handling this short of retrying
3455 * to add the match rule... and then there's the little thing that, hey, maybe there's
3456 * a reason the bus in an OOM condition.
3458 * Doable, but not really sure it's worth it...
3461 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3462 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3463 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3464 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3465 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3466 g_return_val_if_fail (callback != NULL, 0);
3467 g_return_val_if_fail (check_initialized (connection), 0);
3469 CONNECTION_LOCK (connection);
3471 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3472 * with a '-' character to prefix the rule (which will otherwise be
3475 * This allows us to hash the rule and do our lifecycle tracking in
3476 * the usual way, but the '-' prevents the match rule from ever
3477 * actually being send to the bus (either for add or remove).
3479 rule = args_to_rule (sender, interface_name, member, object_path, arg0,
3480 (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE) != 0);
3482 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3483 sender_unique_name = sender;
3485 sender_unique_name = "";
3487 subscriber.callback = callback;
3488 subscriber.user_data = user_data;
3489 subscriber.user_data_free_func = user_data_free_func;
3490 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3491 subscriber.context = g_main_context_ref_thread_default ();
3493 /* see if we've already have this rule */
3494 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3495 if (signal_data != NULL)
3497 g_array_append_val (signal_data->subscribers, subscriber);
3502 signal_data = g_new0 (SignalData, 1);
3503 signal_data->rule = rule;
3504 signal_data->sender = g_strdup (sender);
3505 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3506 signal_data->interface_name = g_strdup (interface_name);
3507 signal_data->member = g_strdup (member);
3508 signal_data->object_path = g_strdup (object_path);
3509 signal_data->arg0 = g_strdup (arg0);
3510 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3511 g_array_append_val (signal_data->subscribers, subscriber);
3513 g_hash_table_insert (connection->map_rule_to_signal_data,
3517 /* Add the match rule to the bus...
3519 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3520 * always send such messages to us.
3522 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3524 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3525 add_match_rule (connection, signal_data->rule);
3528 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3529 signal_data->sender_unique_name);
3530 if (signal_data_array == NULL)
3532 signal_data_array = g_ptr_array_new ();
3533 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3534 g_strdup (signal_data->sender_unique_name),
3537 g_ptr_array_add (signal_data_array, signal_data);
3540 g_hash_table_insert (connection->map_id_to_signal_data,
3541 GUINT_TO_POINTER (subscriber.id),
3544 CONNECTION_UNLOCK (connection);
3546 return subscriber.id;
3549 /* ---------------------------------------------------------------------------------------------------- */
3551 /* called in any thread */
3552 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3554 unsubscribe_id_internal (GDBusConnection *connection,
3555 guint subscription_id,
3556 GArray *out_removed_subscribers)
3558 SignalData *signal_data;
3559 GPtrArray *signal_data_array;
3562 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3563 GUINT_TO_POINTER (subscription_id));
3564 if (signal_data == NULL)
3566 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3570 for (n = 0; n < signal_data->subscribers->len; n++)
3572 SignalSubscriber *subscriber;
3574 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3575 if (subscriber->id != subscription_id)
3578 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3579 GUINT_TO_POINTER (subscription_id)));
3580 g_array_append_val (out_removed_subscribers, *subscriber);
3581 g_array_remove_index (signal_data->subscribers, n);
3583 if (signal_data->subscribers->len == 0)
3585 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3587 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3588 signal_data->sender_unique_name);
3589 g_warn_if_fail (signal_data_array != NULL);
3590 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3592 if (signal_data_array->len == 0)
3594 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3595 signal_data->sender_unique_name));
3598 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3599 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3600 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3601 !g_dbus_connection_is_closed (connection) &&
3602 !connection->finalizing)
3604 /* The check for g_dbus_connection_is_closed() means that
3605 * sending the RemoveMatch message can't fail with
3606 * G_IO_ERROR_CLOSED, because we're holding the lock,
3607 * so on_worker_closed() can't happen between the check we just
3608 * did, and releasing the lock later.
3610 remove_match_rule (connection, signal_data->rule);
3613 signal_data_free (signal_data);
3619 g_assert_not_reached ();
3626 * g_dbus_connection_signal_unsubscribe:
3627 * @connection: A #GDBusConnection.
3628 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3630 * Unsubscribes from signals.
3635 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3636 guint subscription_id)
3638 GArray *subscribers;
3641 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3642 g_return_if_fail (check_initialized (connection));
3644 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3646 CONNECTION_LOCK (connection);
3647 unsubscribe_id_internal (connection,
3650 CONNECTION_UNLOCK (connection);
3653 g_assert (subscribers->len == 0 || subscribers->len == 1);
3655 /* call GDestroyNotify without lock held */
3656 for (n = 0; n < subscribers->len; n++)
3658 SignalSubscriber *subscriber;
3659 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3660 call_destroy_notify (subscriber->context,
3661 subscriber->user_data_free_func,
3662 subscriber->user_data);
3663 g_main_context_unref (subscriber->context);
3666 g_array_free (subscribers, TRUE);
3669 /* ---------------------------------------------------------------------------------------------------- */
3673 guint subscription_id;
3674 GDBusSignalCallback callback;
3676 GDBusMessage *message;
3677 GDBusConnection *connection;
3678 const gchar *sender;
3680 const gchar *interface;
3681 const gchar *member;
3684 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3688 emit_signal_instance_in_idle_cb (gpointer data)
3690 SignalInstance *signal_instance = data;
3691 GVariant *parameters;
3692 gboolean has_subscription;
3694 parameters = g_dbus_message_get_body (signal_instance->message);
3695 if (parameters == NULL)
3697 parameters = g_variant_new ("()");
3698 g_variant_ref_sink (parameters);
3702 g_variant_ref_sink (parameters);
3706 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3707 signal_instance->subscription_id,
3708 signal_instance->sender,
3709 signal_instance->path,
3710 signal_instance->interface,
3711 signal_instance->member,
3712 g_variant_print (parameters, TRUE));
3715 /* Careful here, don't do the callback if we no longer has the subscription */
3716 CONNECTION_LOCK (signal_instance->connection);
3717 has_subscription = FALSE;
3718 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3719 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3720 has_subscription = TRUE;
3721 CONNECTION_UNLOCK (signal_instance->connection);
3723 if (has_subscription)
3724 signal_instance->callback (signal_instance->connection,
3725 signal_instance->sender,
3726 signal_instance->path,
3727 signal_instance->interface,
3728 signal_instance->member,
3730 signal_instance->user_data);
3732 g_variant_unref (parameters);
3738 signal_instance_free (SignalInstance *signal_instance)
3740 g_object_unref (signal_instance->message);
3741 g_object_unref (signal_instance->connection);
3742 g_free (signal_instance);
3745 /* called in GDBusWorker thread WITH lock held */
3747 schedule_callbacks (GDBusConnection *connection,
3748 GPtrArray *signal_data_array,
3749 GDBusMessage *message,
3750 const gchar *sender)
3753 const gchar *interface;
3754 const gchar *member;
3763 interface = g_dbus_message_get_interface (message);
3764 member = g_dbus_message_get_member (message);
3765 path = g_dbus_message_get_path (message);
3766 arg0 = g_dbus_message_get_arg0 (message);
3769 g_print ("In schedule_callbacks:\n"
3771 " interface = `%s'\n"
3782 /* TODO: if this is slow, then we can change signal_data_array into
3783 * map_object_path_to_signal_data_array or something.
3785 for (n = 0; n < signal_data_array->len; n++)
3787 SignalData *signal_data = signal_data_array->pdata[n];
3789 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3792 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3795 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3798 if (signal_data->arg0 != NULL && g_strcmp0 (signal_data->arg0, arg0) != 0)
3801 for (m = 0; m < signal_data->subscribers->len; m++)
3803 SignalSubscriber *subscriber;
3804 GSource *idle_source;
3805 SignalInstance *signal_instance;
3807 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3809 signal_instance = g_new0 (SignalInstance, 1);
3810 signal_instance->subscription_id = subscriber->id;
3811 signal_instance->callback = subscriber->callback;
3812 signal_instance->user_data = subscriber->user_data;
3813 signal_instance->message = g_object_ref (message);
3814 signal_instance->connection = g_object_ref (connection);
3815 signal_instance->sender = sender;
3816 signal_instance->path = path;
3817 signal_instance->interface = interface;
3818 signal_instance->member = member;
3820 idle_source = g_idle_source_new ();
3821 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3822 g_source_set_callback (idle_source,
3823 emit_signal_instance_in_idle_cb,
3825 (GDestroyNotify) signal_instance_free);
3826 g_source_attach (idle_source, subscriber->context);
3827 g_source_unref (idle_source);
3832 /* called in GDBusWorker thread with lock held */
3834 distribute_signals (GDBusConnection *connection,
3835 GDBusMessage *message)
3837 GPtrArray *signal_data_array;
3838 const gchar *sender;
3840 sender = g_dbus_message_get_sender (message);
3842 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3844 _g_dbus_debug_print_lock ();
3845 g_print ("========================================================================\n"
3846 "GDBus-debug:Signal:\n"
3847 " <<<< RECEIVED SIGNAL %s.%s\n"
3849 " sent by name %s\n",
3850 g_dbus_message_get_interface (message),
3851 g_dbus_message_get_member (message),
3852 g_dbus_message_get_path (message),
3853 sender != NULL ? sender : "(none)");
3854 _g_dbus_debug_print_unlock ();
3857 /* collect subscribers that match on sender */
3860 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3861 if (signal_data_array != NULL)
3862 schedule_callbacks (connection, signal_data_array, message, sender);
3865 /* collect subscribers not matching on sender */
3866 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3867 if (signal_data_array != NULL)
3868 schedule_callbacks (connection, signal_data_array, message, sender);
3871 /* ---------------------------------------------------------------------------------------------------- */
3873 /* only called from finalize(), removes all subscriptions */
3875 purge_all_signal_subscriptions (GDBusConnection *connection)
3877 GHashTableIter iter;
3880 GArray *subscribers;
3883 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3884 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3885 while (g_hash_table_iter_next (&iter, &key, NULL))
3887 guint subscription_id = GPOINTER_TO_UINT (key);
3888 g_array_append_val (ids, subscription_id);
3891 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3892 for (n = 0; n < ids->len; n++)
3894 guint subscription_id = g_array_index (ids, guint, n);
3895 unsubscribe_id_internal (connection,
3899 g_array_free (ids, TRUE);
3901 /* call GDestroyNotify without lock held */
3902 for (n = 0; n < subscribers->len; n++)
3904 SignalSubscriber *subscriber;
3905 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3906 call_destroy_notify (subscriber->context,
3907 subscriber->user_data_free_func,
3908 subscriber->user_data);
3909 g_main_context_unref (subscriber->context);
3912 g_array_free (subscribers, TRUE);
3915 /* ---------------------------------------------------------------------------------------------------- */
3917 static GDBusInterfaceVTable *
3918 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3920 /* Don't waste memory by copying padding - remember to update this
3921 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3923 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3927 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3932 /* ---------------------------------------------------------------------------------------------------- */
3934 static GDBusSubtreeVTable *
3935 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
3937 /* Don't waste memory by copying padding - remember to update this
3938 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
3940 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3944 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
3949 /* ---------------------------------------------------------------------------------------------------- */
3951 struct ExportedObject
3954 GDBusConnection *connection;
3956 /* maps gchar* -> ExportedInterface* */
3957 GHashTable *map_if_name_to_ei;
3960 /* only called with lock held */
3962 exported_object_free (ExportedObject *eo)
3964 g_free (eo->object_path);
3965 g_hash_table_unref (eo->map_if_name_to_ei);
3974 gchar *interface_name;
3975 GDBusInterfaceVTable *vtable;
3976 GDBusInterfaceInfo *interface_info;
3978 GMainContext *context;
3980 GDestroyNotify user_data_free_func;
3981 } ExportedInterface;
3983 /* called with lock held */
3985 exported_interface_free (ExportedInterface *ei)
3987 g_dbus_interface_info_cache_release (ei->interface_info);
3988 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
3990 call_destroy_notify (ei->context,
3991 ei->user_data_free_func,
3994 g_main_context_unref (ei->context);
3996 g_free (ei->interface_name);
3997 _g_dbus_interface_vtable_free (ei->vtable);
4001 /* ---------------------------------------------------------------------------------------------------- */
4003 /* Convenience function to check if @registration_id (if not zero) or
4004 * @subtree_registration_id (if not zero) has been unregistered. If
4005 * so, returns %TRUE.
4007 * May be called by any thread. Caller must *not* hold lock.
4010 has_object_been_unregistered (GDBusConnection *connection,
4011 guint registration_id,
4012 guint subtree_registration_id)
4016 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4020 CONNECTION_LOCK (connection);
4021 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4022 GUINT_TO_POINTER (registration_id)) == NULL)
4026 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4027 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4031 CONNECTION_UNLOCK (connection);
4036 /* ---------------------------------------------------------------------------------------------------- */
4040 GDBusConnection *connection;
4041 GDBusMessage *message;
4043 const gchar *property_name;
4044 const GDBusInterfaceVTable *vtable;
4045 GDBusInterfaceInfo *interface_info;
4046 const GDBusPropertyInfo *property_info;
4047 guint registration_id;
4048 guint subtree_registration_id;
4052 property_data_free (PropertyData *data)
4054 g_object_unref (data->connection);
4055 g_object_unref (data->message);
4059 /* called in thread where object was registered - no locks held */
4061 invoke_get_property_in_idle_cb (gpointer _data)
4063 PropertyData *data = _data;
4066 GDBusMessage *reply;
4068 if (has_object_been_unregistered (data->connection,
4069 data->registration_id,
4070 data->subtree_registration_id))
4072 reply = g_dbus_message_new_method_error (data->message,
4073 "org.freedesktop.DBus.Error.UnknownMethod",
4074 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4075 g_dbus_message_get_path (data->message));
4076 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4077 g_object_unref (reply);
4082 value = data->vtable->get_property (data->connection,
4083 g_dbus_message_get_sender (data->message),
4084 g_dbus_message_get_path (data->message),
4085 data->interface_info->name,
4086 data->property_name,
4093 g_assert_no_error (error);
4095 g_variant_take_ref (value);
4096 reply = g_dbus_message_new_method_reply (data->message);
4097 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4098 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4099 g_variant_unref (value);
4100 g_object_unref (reply);
4104 gchar *dbus_error_name;
4105 g_assert (error != NULL);
4106 dbus_error_name = g_dbus_error_encode_gerror (error);
4107 reply = g_dbus_message_new_method_error_literal (data->message,
4110 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4111 g_free (dbus_error_name);
4112 g_error_free (error);
4113 g_object_unref (reply);
4120 /* called in thread where object was registered - no locks held */
4122 invoke_set_property_in_idle_cb (gpointer _data)
4124 PropertyData *data = _data;
4126 GDBusMessage *reply;
4132 g_variant_get (g_dbus_message_get_body (data->message),
4138 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4139 * of the given value is wrong
4141 if (g_strcmp0 (g_variant_get_type_string (value), data->property_info->signature) != 0)
4143 reply = g_dbus_message_new_method_error (data->message,
4144 "org.freedesktop.DBus.Error.InvalidArgs",
4145 _("Error setting property `%s': Expected type `%s' but got `%s'"),
4146 data->property_info->name,
4147 data->property_info->signature,
4148 g_variant_get_type_string (value));
4152 if (!data->vtable->set_property (data->connection,
4153 g_dbus_message_get_sender (data->message),
4154 g_dbus_message_get_path (data->message),
4155 data->interface_info->name,
4156 data->property_name,
4161 gchar *dbus_error_name;
4162 g_assert (error != NULL);
4163 dbus_error_name = g_dbus_error_encode_gerror (error);
4164 reply = g_dbus_message_new_method_error_literal (data->message,
4167 g_free (dbus_error_name);
4168 g_error_free (error);
4172 reply = g_dbus_message_new_method_reply (data->message);
4176 g_assert (reply != NULL);
4177 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4178 g_object_unref (reply);
4179 g_variant_unref (value);
4184 /* called in any thread with connection's lock held */
4186 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4187 GDBusMessage *message,
4188 guint registration_id,
4189 guint subtree_registration_id,
4191 GDBusInterfaceInfo *interface_info,
4192 const GDBusInterfaceVTable *vtable,
4193 GMainContext *main_context,
4197 const char *interface_name;
4198 const char *property_name;
4199 const GDBusPropertyInfo *property_info;
4200 GSource *idle_source;
4201 PropertyData *property_data;
4202 GDBusMessage *reply;
4207 g_variant_get (g_dbus_message_get_body (message),
4212 g_variant_get (g_dbus_message_get_body (message),
4221 if (vtable == NULL || vtable->get_property == NULL)
4226 if (vtable == NULL || vtable->set_property == NULL)
4230 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4232 property_info = NULL;
4234 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4235 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4236 if (property_info == NULL)
4238 reply = g_dbus_message_new_method_error (message,
4239 "org.freedesktop.DBus.Error.InvalidArgs",
4240 _("No such property `%s'"),
4242 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4243 g_object_unref (reply);
4248 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4250 reply = g_dbus_message_new_method_error (message,
4251 "org.freedesktop.DBus.Error.InvalidArgs",
4252 _("Property `%s' is not readable"),
4254 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4255 g_object_unref (reply);
4259 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4261 reply = g_dbus_message_new_method_error (message,
4262 "org.freedesktop.DBus.Error.InvalidArgs",
4263 _("Property `%s' is not writable"),
4265 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4266 g_object_unref (reply);
4271 /* ok, got the property info - call user code in an idle handler */
4272 property_data = g_new0 (PropertyData, 1);
4273 property_data->connection = g_object_ref (connection);
4274 property_data->message = g_object_ref (message);
4275 property_data->user_data = user_data;
4276 property_data->property_name = property_name;
4277 property_data->vtable = vtable;
4278 property_data->interface_info = interface_info;
4279 property_data->property_info = property_info;
4280 property_data->registration_id = registration_id;
4281 property_data->subtree_registration_id = subtree_registration_id;
4283 idle_source = g_idle_source_new ();
4284 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4285 g_source_set_callback (idle_source,
4286 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4288 (GDestroyNotify) property_data_free);
4289 g_source_attach (idle_source, main_context);
4290 g_source_unref (idle_source);
4298 /* called in GDBusWorker thread with connection's lock held */
4300 handle_getset_property (GDBusConnection *connection,
4302 GDBusMessage *message,
4305 ExportedInterface *ei;
4307 const char *interface_name;
4308 const char *property_name;
4313 g_variant_get (g_dbus_message_get_body (message),
4318 g_variant_get (g_dbus_message_get_body (message),
4324 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4325 * no such interface registered
4327 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4330 GDBusMessage *reply;
4331 reply = g_dbus_message_new_method_error (message,
4332 "org.freedesktop.DBus.Error.InvalidArgs",
4333 _("No such interface `%s'"),
4335 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4336 g_object_unref (reply);
4341 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4354 /* ---------------------------------------------------------------------------------------------------- */
4358 GDBusConnection *connection;
4359 GDBusMessage *message;
4361 const GDBusInterfaceVTable *vtable;
4362 GDBusInterfaceInfo *interface_info;
4363 guint registration_id;
4364 guint subtree_registration_id;
4365 } PropertyGetAllData;
4368 property_get_all_data_free (PropertyData *data)
4370 g_object_unref (data->connection);
4371 g_object_unref (data->message);
4375 /* called in thread where object was registered - no locks held */
4377 invoke_get_all_properties_in_idle_cb (gpointer _data)
4379 PropertyGetAllData *data = _data;
4380 GVariantBuilder builder;
4381 GDBusMessage *reply;
4384 if (has_object_been_unregistered (data->connection,
4385 data->registration_id,
4386 data->subtree_registration_id))
4388 reply = g_dbus_message_new_method_error (data->message,
4389 "org.freedesktop.DBus.Error.UnknownMethod",
4390 _("No such interface `org.freedesktop.DBus.Properties' on object at path %s"),
4391 g_dbus_message_get_path (data->message));
4392 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4393 g_object_unref (reply);
4397 /* TODO: Right now we never fail this call - we just omit values if
4398 * a get_property() call is failing.
4400 * We could fail the whole call if just a single get_property() call
4401 * returns an error. We need clarification in the D-Bus spec about this.
4403 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4404 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4405 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4407 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4410 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4413 value = data->vtable->get_property (data->connection,
4414 g_dbus_message_get_sender (data->message),
4415 g_dbus_message_get_path (data->message),
4416 data->interface_info->name,
4417 property_info->name,
4424 g_variant_take_ref (value);
4425 g_variant_builder_add (&builder,
4427 property_info->name,
4429 g_variant_unref (value);
4431 g_variant_builder_close (&builder);
4433 reply = g_dbus_message_new_method_reply (data->message);
4434 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4435 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4436 g_object_unref (reply);
4442 /* called in any thread with connection's lock held */
4444 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4445 GDBusMessage *message,
4446 guint registration_id,
4447 guint subtree_registration_id,
4448 GDBusInterfaceInfo *interface_info,
4449 const GDBusInterfaceVTable *vtable,
4450 GMainContext *main_context,
4454 const char *interface_name;
4455 GSource *idle_source;
4456 PropertyGetAllData *property_get_all_data;
4460 g_variant_get (g_dbus_message_get_body (message),
4464 if (vtable == NULL || vtable->get_property == NULL)
4467 /* ok, got the property info - call user in an idle handler */
4468 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4469 property_get_all_data->connection = g_object_ref (connection);
4470 property_get_all_data->message = g_object_ref (message);
4471 property_get_all_data->user_data = user_data;
4472 property_get_all_data->vtable = vtable;
4473 property_get_all_data->interface_info = interface_info;
4474 property_get_all_data->registration_id = registration_id;
4475 property_get_all_data->subtree_registration_id = subtree_registration_id;
4477 idle_source = g_idle_source_new ();
4478 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4479 g_source_set_callback (idle_source,
4480 invoke_get_all_properties_in_idle_cb,
4481 property_get_all_data,
4482 (GDestroyNotify) property_get_all_data_free);
4483 g_source_attach (idle_source, main_context);
4484 g_source_unref (idle_source);
4492 /* called in GDBusWorker thread with connection's lock held */
4494 handle_get_all_properties (GDBusConnection *connection,
4496 GDBusMessage *message)
4498 ExportedInterface *ei;
4500 const char *interface_name;
4504 g_variant_get (g_dbus_message_get_body (message),
4508 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4509 * no such interface registered
4511 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4514 GDBusMessage *reply;
4515 reply = g_dbus_message_new_method_error (message,
4516 "org.freedesktop.DBus.Error.InvalidArgs",
4517 _("No such interface"),
4519 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4520 g_object_unref (reply);
4525 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4537 /* ---------------------------------------------------------------------------------------------------- */
4539 static const gchar introspect_header[] =
4540 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4541 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4542 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4545 static const gchar introspect_tail[] =
4548 static const gchar introspect_properties_interface[] =
4549 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4550 " <method name=\"Get\">\n"
4551 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4552 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4553 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4555 " <method name=\"GetAll\">\n"
4556 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4557 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4559 " <method name=\"Set\">\n"
4560 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4561 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4562 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4564 " <signal name=\"PropertiesChanged\">\n"
4565 " <arg type=\"s\" name=\"interface_name\"/>\n"
4566 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4567 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4571 static const gchar introspect_introspectable_interface[] =
4572 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4573 " <method name=\"Introspect\">\n"
4574 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4577 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4578 " <method name=\"Ping\"/>\n"
4579 " <method name=\"GetMachineId\">\n"
4580 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4585 introspect_append_header (GString *s)
4587 g_string_append (s, introspect_header);
4591 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4593 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4599 begin = object_path + path_len;
4600 end = strchr (begin, '/');
4602 s = g_strndup (begin, end - begin);
4604 s = g_strdup (begin);
4606 if (g_hash_table_lookup (set, s) == NULL)
4607 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4613 /* TODO: we want a nicer public interface for this */
4614 /* called in any thread with connection's lock held */
4616 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4621 GHashTableIter hash_iter;
4622 const gchar *object_path;
4628 CONNECTION_ENSURE_LOCK (connection);
4630 path_len = strlen (path);
4634 set = g_hash_table_new (g_str_hash, g_str_equal);
4636 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4637 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4638 maybe_add_path (path, path_len, object_path, set);
4640 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4641 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4642 maybe_add_path (path, path_len, object_path, set);
4644 p = g_ptr_array_new ();
4645 keys = g_hash_table_get_keys (set);
4646 for (l = keys; l != NULL; l = l->next)
4647 g_ptr_array_add (p, l->data);
4648 g_hash_table_unref (set);
4651 g_ptr_array_add (p, NULL);
4652 ret = (gchar **) g_ptr_array_free (p, FALSE);
4656 /* called in any thread with connection's lock not held */
4658 g_dbus_connection_list_registered (GDBusConnection *connection,
4662 CONNECTION_LOCK (connection);
4663 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4664 CONNECTION_UNLOCK (connection);
4668 /* called in GDBusWorker thread with connection's lock held */
4670 handle_introspect (GDBusConnection *connection,
4672 GDBusMessage *message)
4676 GDBusMessage *reply;
4677 GHashTableIter hash_iter;
4678 ExportedInterface *ei;
4681 /* first the header with the standard interfaces */
4682 s = g_string_sized_new (sizeof (introspect_header) +
4683 sizeof (introspect_properties_interface) +
4684 sizeof (introspect_introspectable_interface) +
4685 sizeof (introspect_tail));
4686 introspect_append_header (s);
4687 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4688 "org.freedesktop.DBus.Properties"))
4689 g_string_append (s, introspect_properties_interface);
4691 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4692 "org.freedesktop.DBus.Introspectable"))
4693 g_string_append (s, introspect_introspectable_interface);
4695 /* then include the registered interfaces */
4696 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4697 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4698 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4700 /* finally include nodes registered below us */
4701 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4702 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4703 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4704 g_strfreev (registered);
4705 g_string_append (s, introspect_tail);
4707 reply = g_dbus_message_new_method_reply (message);
4708 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4709 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4710 g_object_unref (reply);
4711 g_string_free (s, TRUE);
4716 /* called in thread where object was registered - no locks held */
4718 call_in_idle_cb (gpointer user_data)
4720 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4721 GDBusInterfaceVTable *vtable;
4722 guint registration_id;
4723 guint subtree_registration_id;
4725 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4726 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4728 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4730 subtree_registration_id))
4732 GDBusMessage *reply;
4733 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4734 "org.freedesktop.DBus.Error.UnknownMethod",
4735 _("No such interface `%s' on object at path %s"),
4736 g_dbus_method_invocation_get_interface_name (invocation),
4737 g_dbus_method_invocation_get_object_path (invocation));
4738 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4739 g_object_unref (reply);
4743 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4744 g_assert (vtable != NULL && vtable->method_call != NULL);
4746 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4747 g_dbus_method_invocation_get_sender (invocation),
4748 g_dbus_method_invocation_get_object_path (invocation),
4749 g_dbus_method_invocation_get_interface_name (invocation),
4750 g_dbus_method_invocation_get_method_name (invocation),
4751 g_dbus_method_invocation_get_parameters (invocation),
4752 g_object_ref (invocation),
4753 g_dbus_method_invocation_get_user_data (invocation));
4759 /* called in GDBusWorker thread with connection's lock held */
4761 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4762 GDBusMessage *message,
4763 guint registration_id,
4764 guint subtree_registration_id,
4765 GDBusInterfaceInfo *interface_info,
4766 const GDBusInterfaceVTable *vtable,
4767 GMainContext *main_context,
4770 GDBusMethodInvocation *invocation;
4771 const GDBusMethodInfo *method_info;
4772 GDBusMessage *reply;
4773 GVariant *parameters;
4774 GSource *idle_source;
4776 GVariantType *in_type;
4780 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4781 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4783 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4784 * error to the caller
4786 if (method_info == NULL)
4788 reply = g_dbus_message_new_method_error (message,
4789 "org.freedesktop.DBus.Error.UnknownMethod",
4790 _("No such method `%s'"),
4791 g_dbus_message_get_member (message));
4792 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4793 g_object_unref (reply);
4798 parameters = g_dbus_message_get_body (message);
4799 if (parameters == NULL)
4801 parameters = g_variant_new ("()");
4802 g_variant_ref_sink (parameters);
4806 g_variant_ref (parameters);
4809 /* Check that the incoming args are of the right type - if they are not, return
4810 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4812 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4813 if (!g_variant_is_of_type (parameters, in_type))
4817 type_string = g_variant_type_dup_string (in_type);
4819 reply = g_dbus_message_new_method_error (message,
4820 "org.freedesktop.DBus.Error.InvalidArgs",
4821 _("Type of message, `%s', does not match expected type `%s'"),
4822 g_variant_get_type_string (parameters),
4824 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4825 g_variant_type_free (in_type);
4826 g_variant_unref (parameters);
4827 g_object_unref (reply);
4828 g_free (type_string);
4832 g_variant_type_free (in_type);
4834 /* schedule the call in idle */
4835 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4836 g_dbus_message_get_path (message),
4837 g_dbus_message_get_interface (message),
4838 g_dbus_message_get_member (message),
4844 g_variant_unref (parameters);
4846 /* TODO: would be nicer with a real MethodData like we already
4847 * have PropertyData and PropertyGetAllData... */
4848 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4849 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4850 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4852 idle_source = g_idle_source_new ();
4853 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4854 g_source_set_callback (idle_source,
4858 g_source_attach (idle_source, main_context);
4859 g_source_unref (idle_source);
4867 /* ---------------------------------------------------------------------------------------------------- */
4869 /* called in GDBusWorker thread with connection's lock held */
4871 obj_message_func (GDBusConnection *connection,
4873 GDBusMessage *message)
4875 const gchar *interface_name;
4876 const gchar *member;
4877 const gchar *signature;
4882 interface_name = g_dbus_message_get_interface (message);
4883 member = g_dbus_message_get_member (message);
4884 signature = g_dbus_message_get_signature (message);
4886 /* see if we have an interface for handling this call */
4887 if (interface_name != NULL)
4889 ExportedInterface *ei;
4890 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4893 /* we do - invoke the handler in idle in the right thread */
4895 /* handle no vtable or handler being present */
4896 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4899 handled = validate_and_maybe_schedule_method_call (connection,
4911 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
4912 g_strcmp0 (member, "Introspect") == 0 &&
4913 g_strcmp0 (signature, "") == 0)
4915 handled = handle_introspect (connection, eo, message);
4918 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4919 g_strcmp0 (member, "Get") == 0 &&
4920 g_strcmp0 (signature, "ss") == 0)
4922 handled = handle_getset_property (connection, eo, message, TRUE);
4925 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4926 g_strcmp0 (member, "Set") == 0 &&
4927 g_strcmp0 (signature, "ssv") == 0)
4929 handled = handle_getset_property (connection, eo, message, FALSE);
4932 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
4933 g_strcmp0 (member, "GetAll") == 0 &&
4934 g_strcmp0 (signature, "s") == 0)
4936 handled = handle_get_all_properties (connection, eo, message);
4945 * g_dbus_connection_register_object:
4946 * @connection: A #GDBusConnection.
4947 * @object_path: The object path to register at.
4948 * @interface_info: Introspection data for the interface.
4949 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
4950 * @user_data: (allow-none): Data to pass to functions in @vtable.
4951 * @user_data_free_func: Function to call when the object path is unregistered.
4952 * @error: Return location for error or %NULL.
4954 * Registers callbacks for exported objects at @object_path with the
4955 * D-Bus interface that is described in @interface_info.
4957 * Calls to functions in @vtable (and @user_data_free_func) will
4958 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
4959 * loop</link> of the thread you are calling this method from.
4961 * Note that all #GVariant values passed to functions in @vtable will match
4962 * the signature given in @interface_info - if a remote caller passes
4963 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
4964 * is returned to the remote caller.
4966 * Additionally, if the remote caller attempts to invoke methods or
4967 * access properties not mentioned in @interface_info the
4968 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
4969 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
4970 * are returned to the caller.
4972 * It is considered a programming error if the
4973 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
4974 * #GVariant of incorrect type.
4976 * If an existing callback is already registered at @object_path and
4977 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
4979 * GDBus automatically implements the standard D-Bus interfaces
4980 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
4981 * and org.freedesktop.Peer, so you don't have to implement those for
4982 * the objects you export. You <emphasis>can</emphasis> implement
4983 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
4984 * and setting of properties asynchronously.
4986 * Note that the reference count on @interface_info will be
4987 * incremented by 1 (unless allocated statically, e.g. if the
4988 * reference count is -1, see g_dbus_interface_info_ref()) for as long
4989 * as the object is exported. Also note that @vtable will be copied.
4991 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
4993 * Returns: 0 if @error is set, otherwise a registration id (never 0)
4994 * that can be used with g_dbus_connection_unregister_object() .
4999 g_dbus_connection_register_object (GDBusConnection *connection,
5000 const gchar *object_path,
5001 GDBusInterfaceInfo *interface_info,
5002 const GDBusInterfaceVTable *vtable,
5004 GDestroyNotify user_data_free_func,
5008 ExportedInterface *ei;
5011 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5012 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5013 g_return_val_if_fail (interface_info != NULL, 0);
5014 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5015 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5016 g_return_val_if_fail (check_initialized (connection), 0);
5020 CONNECTION_LOCK (connection);
5022 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5025 eo = g_new0 (ExportedObject, 1);
5026 eo->object_path = g_strdup (object_path);
5027 eo->connection = connection;
5028 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5031 (GDestroyNotify) exported_interface_free);
5032 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5035 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5041 _("An object is already exported for the interface %s at %s"),
5042 interface_info->name,
5047 ei = g_new0 (ExportedInterface, 1);
5048 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5050 ei->user_data = user_data;
5051 ei->user_data_free_func = user_data_free_func;
5052 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5053 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5054 g_dbus_interface_info_cache_build (ei->interface_info);
5055 ei->interface_name = g_strdup (interface_info->name);
5056 ei->context = g_main_context_ref_thread_default ();
5058 g_hash_table_insert (eo->map_if_name_to_ei,
5059 (gpointer) ei->interface_name,
5061 g_hash_table_insert (connection->map_id_to_ei,
5062 GUINT_TO_POINTER (ei->id),
5068 CONNECTION_UNLOCK (connection);
5074 * g_dbus_connection_unregister_object:
5075 * @connection: A #GDBusConnection.
5076 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5078 * Unregisters an object.
5080 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5085 g_dbus_connection_unregister_object (GDBusConnection *connection,
5086 guint registration_id)
5088 ExportedInterface *ei;
5092 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5093 g_return_val_if_fail (check_initialized (connection), FALSE);
5097 CONNECTION_LOCK (connection);
5099 ei = g_hash_table_lookup (connection->map_id_to_ei,
5100 GUINT_TO_POINTER (registration_id));
5106 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5107 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5108 /* unregister object path if we have no more exported interfaces */
5109 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5110 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5116 CONNECTION_UNLOCK (connection);
5121 /* ---------------------------------------------------------------------------------------------------- */
5124 * g_dbus_connection_emit_signal:
5125 * @connection: A #GDBusConnection.
5126 * @destination_bus_name: (allow-none): The unique bus name for the destination
5127 * for the signal or %NULL to emit to all listeners.
5128 * @object_path: Path of remote object.
5129 * @interface_name: D-Bus interface to emit a signal on.
5130 * @signal_name: The name of the signal to emit.
5131 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5132 * or %NULL if not passing parameters.
5133 * @error: Return location for error or %NULL.
5137 * If the parameters GVariant is floating, it is consumed.
5139 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5141 * Returns: %TRUE unless @error is set.
5146 g_dbus_connection_emit_signal (GDBusConnection *connection,
5147 const gchar *destination_bus_name,
5148 const gchar *object_path,
5149 const gchar *interface_name,
5150 const gchar *signal_name,
5151 GVariant *parameters,
5154 GDBusMessage *message;
5160 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5161 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5162 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5163 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5164 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5165 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5166 g_return_val_if_fail (check_initialized (connection), FALSE);
5168 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5170 _g_dbus_debug_print_lock ();
5171 g_print ("========================================================================\n"
5172 "GDBus-debug:Emission:\n"
5173 " >>>> SIGNAL EMISSION %s.%s()\n"
5175 " destination %s\n",
5176 interface_name, signal_name,
5178 destination_bus_name != NULL ? destination_bus_name : "(none)");
5179 _g_dbus_debug_print_unlock ();
5182 message = g_dbus_message_new_signal (object_path,
5186 if (destination_bus_name != NULL)
5187 g_dbus_message_set_header (message,
5188 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5189 g_variant_new_string (destination_bus_name));
5191 if (parameters != NULL)
5192 g_dbus_message_set_body (message, parameters);
5194 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5195 g_object_unref (message);
5201 add_call_flags (GDBusMessage *message,
5202 GDBusCallFlags flags)
5204 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5205 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5209 decode_method_reply (GDBusMessage *reply,
5210 const gchar *method_name,
5211 const GVariantType *reply_type,
5212 GUnixFDList **out_fd_list,
5218 switch (g_dbus_message_get_message_type (reply))
5220 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5221 result = g_dbus_message_get_body (reply);
5224 result = g_variant_new ("()");
5225 g_variant_ref_sink (result);
5229 g_variant_ref (result);
5232 if (!g_variant_is_of_type (result, reply_type))
5234 gchar *type_string = g_variant_type_dup_string (reply_type);
5238 G_IO_ERROR_INVALID_ARGUMENT,
5239 _("Method `%s' returned type `%s', but expected `%s'"),
5240 method_name, g_variant_get_type_string (result), type_string);
5242 g_variant_unref (result);
5243 g_free (type_string);
5250 if (out_fd_list != NULL)
5252 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5253 if (*out_fd_list != NULL)
5254 g_object_ref (*out_fd_list);
5260 case G_DBUS_MESSAGE_TYPE_ERROR:
5261 g_dbus_message_to_gerror (reply, error);
5265 g_assert_not_reached ();
5275 GSimpleAsyncResult *simple;
5276 GVariantType *reply_type;
5277 gchar *method_name; /* for error message */
5281 GUnixFDList *fd_list;
5285 call_state_free (CallState *state)
5287 g_variant_type_free (state->reply_type);
5288 g_free (state->method_name);
5290 if (state->value != NULL)
5291 g_variant_unref (state->value);
5292 if (state->fd_list != NULL)
5293 g_object_unref (state->fd_list);
5294 g_slice_free (CallState, state);
5297 /* called in any thread, with the connection's lock not held */
5299 g_dbus_connection_call_done (GObject *source,
5300 GAsyncResult *result,
5303 GSimpleAsyncResult *simple;
5304 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5305 CallState *state = user_data;
5307 GDBusMessage *reply;
5310 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5314 if (G_UNLIKELY (_g_dbus_debug_call ()))
5316 _g_dbus_debug_print_lock ();
5317 g_print ("========================================================================\n"
5318 "GDBus-debug:Call:\n"
5319 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5325 g_print ("SUCCESS\n");
5329 g_print ("FAILED: %s\n",
5332 _g_dbus_debug_print_unlock ();
5336 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5338 simple = state->simple; /* why? because state is freed before we unref simple.. */
5341 g_simple_async_result_take_error (state->simple, error);
5342 g_simple_async_result_complete (state->simple);
5343 call_state_free (state);
5347 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5348 g_simple_async_result_complete (state->simple);
5350 g_clear_object (&reply);
5351 g_object_unref (simple);
5354 /* called in any thread, with the connection's lock not held */
5356 g_dbus_connection_call_internal (GDBusConnection *connection,
5357 const gchar *bus_name,
5358 const gchar *object_path,
5359 const gchar *interface_name,
5360 const gchar *method_name,
5361 GVariant *parameters,
5362 const GVariantType *reply_type,
5363 GDBusCallFlags flags,
5365 GUnixFDList *fd_list,
5366 GCancellable *cancellable,
5367 GAsyncReadyCallback callback,
5370 GDBusMessage *message;
5373 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5374 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5375 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5376 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5377 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5378 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5379 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5380 g_return_if_fail (check_initialized (connection));
5382 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5384 g_return_if_fail (fd_list == NULL);
5387 message = g_dbus_message_new_method_call (bus_name,
5391 add_call_flags (message, flags);
5392 if (parameters != NULL)
5393 g_dbus_message_set_body (message, parameters);
5396 if (fd_list != NULL)
5397 g_dbus_message_set_unix_fd_list (message, fd_list);
5400 /* If the user has no callback then we can just send the message with
5401 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5402 * the logic for processing the reply. If the service sends the reply
5403 * anyway then it will just be ignored.
5405 if (callback != NULL)
5409 state = g_slice_new0 (CallState);
5410 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5411 callback, user_data,
5412 g_dbus_connection_call_internal);
5413 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5414 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5416 if (reply_type == NULL)
5417 reply_type = G_VARIANT_TYPE_ANY;
5419 state->reply_type = g_variant_type_copy (reply_type);
5421 g_dbus_connection_send_message_with_reply (connection,
5423 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5427 g_dbus_connection_call_done,
5429 serial = state->serial;
5433 GDBusMessageFlags flags;
5435 flags = g_dbus_message_get_flags (message);
5436 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5437 g_dbus_message_set_flags (message, flags);
5439 g_dbus_connection_send_message (connection,
5441 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5445 if (G_UNLIKELY (_g_dbus_debug_call ()))
5447 _g_dbus_debug_print_lock ();
5448 g_print ("========================================================================\n"
5449 "GDBus-debug:Call:\n"
5450 " >>>> ASYNC %s.%s()\n"
5452 " owned by name %s (serial %d)\n",
5456 bus_name != NULL ? bus_name : "(none)",
5458 _g_dbus_debug_print_unlock ();
5461 if (message != NULL)
5462 g_object_unref (message);
5465 /* called in any thread, with the connection's lock not held */
5467 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5468 GUnixFDList **out_fd_list,
5472 GSimpleAsyncResult *simple;
5475 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5476 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5477 g_dbus_connection_call_internal), NULL);
5478 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5480 simple = G_SIMPLE_ASYNC_RESULT (res);
5482 if (g_simple_async_result_propagate_error (simple, error))
5485 state = g_simple_async_result_get_op_res_gpointer (simple);
5486 if (out_fd_list != NULL)
5487 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5488 return g_variant_ref (state->value);
5491 /* called in any user thread, with the connection's lock not held */
5493 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5494 const gchar *bus_name,
5495 const gchar *object_path,
5496 const gchar *interface_name,
5497 const gchar *method_name,
5498 GVariant *parameters,
5499 const GVariantType *reply_type,
5500 GDBusCallFlags flags,
5502 GUnixFDList *fd_list,
5503 GUnixFDList **out_fd_list,
5504 GCancellable *cancellable,
5507 GDBusMessage *message;
5508 GDBusMessage *reply;
5510 GError *local_error;
5511 GDBusSendMessageFlags send_flags;
5517 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5518 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5519 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5520 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5521 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5522 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5523 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5525 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5527 g_return_val_if_fail (fd_list == NULL, NULL);
5529 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5531 if (!(flags & CALL_FLAGS_INITIALIZING))
5532 g_return_val_if_fail (check_initialized (connection), FALSE);
5534 if (reply_type == NULL)
5535 reply_type = G_VARIANT_TYPE_ANY;
5537 message = g_dbus_message_new_method_call (bus_name,
5541 add_call_flags (message, flags);
5542 if (parameters != NULL)
5543 g_dbus_message_set_body (message, parameters);
5546 if (fd_list != NULL)
5547 g_dbus_message_set_unix_fd_list (message, fd_list);
5550 if (G_UNLIKELY (_g_dbus_debug_call ()))
5552 _g_dbus_debug_print_lock ();
5553 g_print ("========================================================================\n"
5554 "GDBus-debug:Call:\n"
5555 " >>>> SYNC %s.%s()\n"
5557 " owned by name %s\n",
5561 bus_name != NULL ? bus_name : "(none)");
5562 _g_dbus_debug_print_unlock ();
5567 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5569 /* translate from one flavour of flags to another... */
5570 if (flags & CALL_FLAGS_INITIALIZING)
5571 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5573 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5577 NULL, /* volatile guint32 *out_serial */
5581 if (G_UNLIKELY (_g_dbus_debug_call ()))
5583 _g_dbus_debug_print_lock ();
5584 g_print ("========================================================================\n"
5585 "GDBus-debug:Call:\n"
5586 " <<<< SYNC COMPLETE %s.%s()\n"
5592 g_print ("SUCCESS\n");
5596 g_print ("FAILED: %s\n",
5597 local_error->message);
5599 _g_dbus_debug_print_unlock ();
5605 *error = local_error;
5607 g_error_free (local_error);
5611 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5614 if (message != NULL)
5615 g_object_unref (message);
5617 g_object_unref (reply);
5622 /* ---------------------------------------------------------------------------------------------------- */
5625 * g_dbus_connection_call:
5626 * @connection: A #GDBusConnection.
5627 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5628 * @connection is not a message bus connection.
5629 * @object_path: Path of remote object.
5630 * @interface_name: D-Bus interface to invoke method on.
5631 * @method_name: The name of the method to invoke.
5632 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5633 * or %NULL if not passing parameters.
5634 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5635 * @flags: Flags from the #GDBusCallFlags enumeration.
5636 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5637 * timeout or %G_MAXINT for no timeout.
5638 * @cancellable: (allow-none): A #GCancellable or %NULL.
5639 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5640 * satisfied or %NULL if you don't care about the result of the
5641 * method invocation.
5642 * @user_data: The data to pass to @callback.
5644 * Asynchronously invokes the @method_name method on the
5645 * @interface_name D-Bus interface on the remote object at
5646 * @object_path owned by @bus_name.
5648 * If @connection is closed then the operation will fail with
5649 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5650 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5651 * not compatible with the D-Bus protocol, the operation fails with
5652 * %G_IO_ERROR_INVALID_ARGUMENT.
5654 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5655 * error will be raised if it does not match. Said another way, if you give a @reply_type
5656 * then any non-%NULL return value will be of this type.
5658 * If the @parameters #GVariant is floating, it is consumed. This allows
5659 * convenient 'inline' use of g_variant_new(), e.g.:
5661 * g_dbus_connection_call (connection,
5662 * "org.freedesktop.StringThings",
5663 * "/org/freedesktop/StringThings",
5664 * "org.freedesktop.StringThings",
5666 * g_variant_new ("(ss)",
5670 * G_DBUS_CALL_FLAGS_NONE,
5673 * (GAsyncReadyCallback) two_strings_done,
5677 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5678 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5679 * of the thread you are calling this method from. You can then call
5680 * g_dbus_connection_call_finish() to get the result of the operation.
5681 * See g_dbus_connection_call_sync() for the synchronous version of this
5684 * If @callback is %NULL then the D-Bus method call message will be sent with
5685 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5690 g_dbus_connection_call (GDBusConnection *connection,
5691 const gchar *bus_name,
5692 const gchar *object_path,
5693 const gchar *interface_name,
5694 const gchar *method_name,
5695 GVariant *parameters,
5696 const GVariantType *reply_type,
5697 GDBusCallFlags flags,
5699 GCancellable *cancellable,
5700 GAsyncReadyCallback callback,
5703 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);
5707 * g_dbus_connection_call_finish:
5708 * @connection: A #GDBusConnection.
5709 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5710 * @error: Return location for error or %NULL.
5712 * Finishes an operation started with g_dbus_connection_call().
5714 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5715 * return values. Free with g_variant_unref().
5720 g_dbus_connection_call_finish (GDBusConnection *connection,
5724 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5728 * g_dbus_connection_call_sync:
5729 * @connection: A #GDBusConnection.
5730 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5731 * @connection is not a message bus connection.
5732 * @object_path: Path of remote object.
5733 * @interface_name: D-Bus interface to invoke method on.
5734 * @method_name: The name of the method to invoke.
5735 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5736 * or %NULL if not passing parameters.
5737 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5738 * @flags: Flags from the #GDBusCallFlags enumeration.
5739 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5740 * timeout or %G_MAXINT for no timeout.
5741 * @cancellable: (allow-none): A #GCancellable or %NULL.
5742 * @error: Return location for error or %NULL.
5744 * Synchronously invokes the @method_name method on the
5745 * @interface_name D-Bus interface on the remote object at
5746 * @object_path owned by @bus_name.
5748 * If @connection is closed then the operation will fail with
5749 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5750 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5751 * contains a value not compatible with the D-Bus protocol, the operation
5752 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5754 * If @reply_type is non-%NULL then the reply will be checked for having
5755 * this type and an error will be raised if it does not match. Said
5756 * another way, if you give a @reply_type then any non-%NULL return
5757 * value will be of this type.
5759 * If the @parameters #GVariant is floating, it is consumed.
5760 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5762 * g_dbus_connection_call_sync (connection,
5763 * "org.freedesktop.StringThings",
5764 * "/org/freedesktop/StringThings",
5765 * "org.freedesktop.StringThings",
5767 * g_variant_new ("(ss)",
5771 * G_DBUS_CALL_FLAGS_NONE,
5777 * The calling thread is blocked until a reply is received. See
5778 * g_dbus_connection_call() for the asynchronous version of
5781 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5782 * return values. Free with g_variant_unref().
5787 g_dbus_connection_call_sync (GDBusConnection *connection,
5788 const gchar *bus_name,
5789 const gchar *object_path,
5790 const gchar *interface_name,
5791 const gchar *method_name,
5792 GVariant *parameters,
5793 const GVariantType *reply_type,
5794 GDBusCallFlags flags,
5796 GCancellable *cancellable,
5799 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);
5802 /* ---------------------------------------------------------------------------------------------------- */
5807 * g_dbus_connection_call_with_unix_fd_list:
5808 * @connection: A #GDBusConnection.
5809 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5810 * @connection is not a message bus connection.
5811 * @object_path: Path of remote object.
5812 * @interface_name: D-Bus interface to invoke method on.
5813 * @method_name: The name of the method to invoke.
5814 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5815 * or %NULL if not passing parameters.
5816 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5817 * @flags: Flags from the #GDBusCallFlags enumeration.
5818 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5819 * timeout or %G_MAXINT for no timeout.
5820 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5821 * @cancellable: (allow-none): A #GCancellable or %NULL.
5822 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5823 * satisfied or %NULL if you don't * care about the result of the
5824 * method invocation.
5825 * @user_data: The data to pass to @callback.
5827 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5829 * This method is only available on UNIX.
5834 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5835 const gchar *bus_name,
5836 const gchar *object_path,
5837 const gchar *interface_name,
5838 const gchar *method_name,
5839 GVariant *parameters,
5840 const GVariantType *reply_type,
5841 GDBusCallFlags flags,
5843 GUnixFDList *fd_list,
5844 GCancellable *cancellable,
5845 GAsyncReadyCallback callback,
5848 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);
5852 * g_dbus_connection_call_with_unix_fd_list_finish:
5853 * @connection: A #GDBusConnection.
5854 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5855 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5856 * @error: Return location for error or %NULL.
5858 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5860 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5861 * return values. Free with g_variant_unref().
5866 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5867 GUnixFDList **out_fd_list,
5871 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5875 * g_dbus_connection_call_with_unix_fd_list_sync:
5876 * @connection: A #GDBusConnection.
5877 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5878 * @connection is not a message bus connection.
5879 * @object_path: Path of remote object.
5880 * @interface_name: D-Bus interface to invoke method on.
5881 * @method_name: The name of the method to invoke.
5882 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5883 * or %NULL if not passing parameters.
5884 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5885 * @flags: Flags from the #GDBusCallFlags enumeration.
5886 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5887 * timeout or %G_MAXINT for no timeout.
5888 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5889 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5890 * @cancellable: (allow-none): A #GCancellable or %NULL.
5891 * @error: Return location for error or %NULL.
5893 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5895 * This method is only available on UNIX.
5897 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5898 * return values. Free with g_variant_unref().
5903 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
5904 const gchar *bus_name,
5905 const gchar *object_path,
5906 const gchar *interface_name,
5907 const gchar *method_name,
5908 GVariant *parameters,
5909 const GVariantType *reply_type,
5910 GDBusCallFlags flags,
5912 GUnixFDList *fd_list,
5913 GUnixFDList **out_fd_list,
5914 GCancellable *cancellable,
5917 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);
5920 #endif /* G_OS_UNIX */
5922 /* ---------------------------------------------------------------------------------------------------- */
5924 struct ExportedSubtree
5928 GDBusConnection *connection;
5929 GDBusSubtreeVTable *vtable;
5930 GDBusSubtreeFlags flags;
5932 GMainContext *context;
5934 GDestroyNotify user_data_free_func;
5938 exported_subtree_free (ExportedSubtree *es)
5940 call_destroy_notify (es->context,
5941 es->user_data_free_func,
5944 g_main_context_unref (es->context);
5946 _g_dbus_subtree_vtable_free (es->vtable);
5947 g_free (es->object_path);
5951 /* called without lock held in the thread where the caller registered
5955 handle_subtree_introspect (GDBusConnection *connection,
5956 ExportedSubtree *es,
5957 GDBusMessage *message)
5961 GDBusMessage *reply;
5964 const gchar *sender;
5965 const gchar *requested_object_path;
5966 const gchar *requested_node;
5967 GDBusInterfaceInfo **interfaces;
5969 gchar **subnode_paths;
5970 gboolean has_properties_interface;
5971 gboolean has_introspectable_interface;
5975 requested_object_path = g_dbus_message_get_path (message);
5976 sender = g_dbus_message_get_sender (message);
5977 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
5979 s = g_string_new (NULL);
5980 introspect_append_header (s);
5982 /* Strictly we don't need the children in dynamic mode, but we avoid the
5983 * conditionals to preserve code clarity
5985 children = es->vtable->enumerate (es->connection,
5992 requested_node = strrchr (requested_object_path, '/') + 1;
5994 /* Assert existence of object if we are not dynamic */
5995 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
5996 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6001 requested_node = NULL;
6004 interfaces = es->vtable->introspect (es->connection,
6009 if (interfaces != NULL)
6011 has_properties_interface = FALSE;
6012 has_introspectable_interface = FALSE;
6014 for (n = 0; interfaces[n] != NULL; n++)
6016 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6017 has_properties_interface = TRUE;
6018 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6019 has_introspectable_interface = TRUE;
6021 if (!has_properties_interface)
6022 g_string_append (s, introspect_properties_interface);
6023 if (!has_introspectable_interface)
6024 g_string_append (s, introspect_introspectable_interface);
6026 for (n = 0; interfaces[n] != NULL; n++)
6028 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6029 g_dbus_interface_info_unref (interfaces[n]);
6031 g_free (interfaces);
6034 /* then include <node> entries from the Subtree for the root */
6037 for (n = 0; children != NULL && children[n] != NULL; n++)
6038 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6041 /* finally include nodes registered below us */
6042 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6043 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6044 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6045 g_strfreev (subnode_paths);
6047 g_string_append (s, "</node>\n");
6049 reply = g_dbus_message_new_method_reply (message);
6050 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6051 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6052 g_object_unref (reply);
6057 g_string_free (s, TRUE);
6058 g_strfreev (children);
6062 /* called without lock held in the thread where the caller registered
6066 handle_subtree_method_invocation (GDBusConnection *connection,
6067 ExportedSubtree *es,
6068 GDBusMessage *message)
6071 const gchar *sender;
6072 const gchar *interface_name;
6073 const gchar *member;
6074 const gchar *signature;
6075 const gchar *requested_object_path;
6076 const gchar *requested_node;
6078 GDBusInterfaceInfo *interface_info;
6079 const GDBusInterfaceVTable *interface_vtable;
6080 gpointer interface_user_data;
6082 GDBusInterfaceInfo **interfaces;
6083 gboolean is_property_get;
6084 gboolean is_property_set;
6085 gboolean is_property_get_all;
6090 requested_object_path = g_dbus_message_get_path (message);
6091 sender = g_dbus_message_get_sender (message);
6092 interface_name = g_dbus_message_get_interface (message);
6093 member = g_dbus_message_get_member (message);
6094 signature = g_dbus_message_get_signature (message);
6095 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6097 is_property_get = FALSE;
6098 is_property_set = FALSE;
6099 is_property_get_all = FALSE;
6100 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6102 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6103 is_property_get = TRUE;
6104 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6105 is_property_set = TRUE;
6106 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6107 is_property_get_all = TRUE;
6112 requested_node = strrchr (requested_object_path, '/') + 1;
6114 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6116 /* We don't want to dispatch to unenumerated
6117 * nodes, so ensure that the child exists.
6122 children = es->vtable->enumerate (es->connection,
6127 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6128 g_strfreev (children);
6136 requested_node = NULL;
6139 /* get introspection data for the node */
6140 interfaces = es->vtable->introspect (es->connection,
6142 requested_object_path,
6146 if (interfaces == NULL)
6149 interface_info = NULL;
6150 for (n = 0; interfaces[n] != NULL; n++)
6152 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6153 interface_info = interfaces[n];
6156 /* dispatch the call if the user wants to handle it */
6157 if (interface_info != NULL)
6159 /* figure out where to dispatch the method call */
6160 interface_user_data = NULL;
6161 interface_vtable = es->vtable->dispatch (es->connection,
6166 &interface_user_data,
6168 if (interface_vtable == NULL)
6171 CONNECTION_LOCK (connection);
6172 handled = validate_and_maybe_schedule_method_call (es->connection,
6179 interface_user_data);
6180 CONNECTION_UNLOCK (connection);
6182 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6183 else if (is_property_get || is_property_set || is_property_get_all)
6185 if (is_property_get)
6186 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6187 else if (is_property_set)
6188 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6189 else if (is_property_get_all)
6190 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6192 g_assert_not_reached ();
6194 /* see if the object supports this interface at all */
6195 for (n = 0; interfaces[n] != NULL; n++)
6197 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6198 interface_info = interfaces[n];
6201 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6202 * claims it won't support the interface
6204 if (interface_info == NULL)
6206 GDBusMessage *reply;
6207 reply = g_dbus_message_new_method_error (message,
6208 "org.freedesktop.DBus.Error.InvalidArgs",
6209 _("No such interface `%s'"),
6211 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6212 g_object_unref (reply);
6217 /* figure out where to dispatch the property get/set/getall calls */
6218 interface_user_data = NULL;
6219 interface_vtable = es->vtable->dispatch (es->connection,
6224 &interface_user_data,
6226 if (interface_vtable == NULL)
6228 g_warning ("The subtree introspection function indicates that '%s' "
6229 "is a valid interface name, but calling the dispatch "
6230 "function on that interface gave us NULL", interface_name);
6234 if (is_property_get || is_property_set)
6236 CONNECTION_LOCK (connection);
6237 handled = validate_and_maybe_schedule_property_getset (es->connection,
6245 interface_user_data);
6246 CONNECTION_UNLOCK (connection);
6248 else if (is_property_get_all)
6250 CONNECTION_LOCK (connection);
6251 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6258 interface_user_data);
6259 CONNECTION_UNLOCK (connection);
6264 if (interfaces != NULL)
6266 for (n = 0; interfaces[n] != NULL; n++)
6267 g_dbus_interface_info_unref (interfaces[n]);
6268 g_free (interfaces);
6276 GDBusMessage *message;
6277 ExportedSubtree *es;
6278 } SubtreeDeferredData;
6281 subtree_deferred_data_free (SubtreeDeferredData *data)
6283 g_object_unref (data->message);
6287 /* called without lock held in the thread where the caller registered the subtree */
6289 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6291 SubtreeDeferredData *data = _data;
6296 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6297 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6298 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6299 handled = handle_subtree_introspect (data->es->connection,
6303 handled = handle_subtree_method_invocation (data->es->connection,
6309 CONNECTION_LOCK (data->es->connection);
6310 handled = handle_generic_unlocked (data->es->connection, data->message);
6311 CONNECTION_UNLOCK (data->es->connection);
6314 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6317 GDBusMessage *reply;
6318 reply = g_dbus_message_new_method_error (data->message,
6319 "org.freedesktop.DBus.Error.UnknownMethod",
6320 _("Method `%s' on interface `%s' with signature `%s' does not exist"),
6321 g_dbus_message_get_member (data->message),
6322 g_dbus_message_get_interface (data->message),
6323 g_dbus_message_get_signature (data->message));
6324 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6325 g_object_unref (reply);
6331 /* called in GDBusWorker thread with connection's lock held */
6333 subtree_message_func (GDBusConnection *connection,
6334 ExportedSubtree *es,
6335 GDBusMessage *message)
6337 GSource *idle_source;
6338 SubtreeDeferredData *data;
6340 data = g_new0 (SubtreeDeferredData, 1);
6341 data->message = g_object_ref (message);
6344 /* defer this call to an idle handler in the right thread */
6345 idle_source = g_idle_source_new ();
6346 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6347 g_source_set_callback (idle_source,
6348 process_subtree_vtable_message_in_idle_cb,
6350 (GDestroyNotify) subtree_deferred_data_free);
6351 g_source_attach (idle_source, es->context);
6352 g_source_unref (idle_source);
6354 /* since we own the entire subtree, handlers for objects not in the subtree have been
6355 * tried already by libdbus-1 - so we just need to ensure that we're always going
6356 * to reply to the message
6362 * g_dbus_connection_register_subtree:
6363 * @connection: A #GDBusConnection.
6364 * @object_path: The object path to register the subtree at.
6365 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6366 * @flags: Flags used to fine tune the behavior of the subtree.
6367 * @user_data: Data to pass to functions in @vtable.
6368 * @user_data_free_func: Function to call when the subtree is unregistered.
6369 * @error: Return location for error or %NULL.
6371 * Registers a whole subtree of <quote>dynamic</quote> objects.
6373 * The @enumerate and @introspection functions in @vtable are used to
6374 * convey, to remote callers, what nodes exist in the subtree rooted
6377 * When handling remote calls into any node in the subtree, first the
6378 * @enumerate function is used to check if the node exists. If the node exists
6379 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6380 * the @introspection function is used to check if the node supports the
6381 * requested method. If so, the @dispatch function is used to determine
6382 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6383 * #gpointer will be used to call into the interface vtable for processing
6386 * All calls into user-provided code will be invoked in the <link
6387 * linkend="g-main-context-push-thread-default">thread-default main
6388 * loop</link> of the thread you are calling this method from.
6390 * If an existing subtree is already registered at @object_path or
6391 * then @error is set to #G_IO_ERROR_EXISTS.
6393 * Note that it is valid to register regular objects (using
6394 * g_dbus_connection_register_object()) in a subtree registered with
6395 * g_dbus_connection_register_subtree() - if so, the subtree handler
6396 * is tried as the last resort. One way to think about a subtree
6397 * handler is to consider it a <quote>fallback handler</quote>
6398 * for object paths not registered via g_dbus_connection_register_object()
6399 * or other bindings.
6401 * Note that @vtable will be copied so you cannot change it after
6404 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6406 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6407 * that can be used with g_dbus_connection_unregister_subtree() .
6412 g_dbus_connection_register_subtree (GDBusConnection *connection,
6413 const gchar *object_path,
6414 const GDBusSubtreeVTable *vtable,
6415 GDBusSubtreeFlags flags,
6417 GDestroyNotify user_data_free_func,
6421 ExportedSubtree *es;
6423 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6424 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6425 g_return_val_if_fail (vtable != NULL, 0);
6426 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6427 g_return_val_if_fail (check_initialized (connection), 0);
6431 CONNECTION_LOCK (connection);
6433 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6439 _("A subtree is already exported for %s"),
6444 es = g_new0 (ExportedSubtree, 1);
6445 es->object_path = g_strdup (object_path);
6446 es->connection = connection;
6448 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6450 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6451 es->user_data = user_data;
6452 es->user_data_free_func = user_data_free_func;
6453 es->context = g_main_context_ref_thread_default ();
6455 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6456 g_hash_table_insert (connection->map_id_to_es,
6457 GUINT_TO_POINTER (es->id),
6463 CONNECTION_UNLOCK (connection);
6468 /* ---------------------------------------------------------------------------------------------------- */
6471 * g_dbus_connection_unregister_subtree:
6472 * @connection: A #GDBusConnection.
6473 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6475 * Unregisters a subtree.
6477 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6482 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6483 guint registration_id)
6485 ExportedSubtree *es;
6488 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6489 g_return_val_if_fail (check_initialized (connection), FALSE);
6493 CONNECTION_LOCK (connection);
6495 es = g_hash_table_lookup (connection->map_id_to_es,
6496 GUINT_TO_POINTER (registration_id));
6500 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6501 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6506 CONNECTION_UNLOCK (connection);
6511 /* ---------------------------------------------------------------------------------------------------- */
6513 /* may be called in any thread, with connection's lock held */
6515 handle_generic_ping_unlocked (GDBusConnection *connection,
6516 const gchar *object_path,
6517 GDBusMessage *message)
6519 GDBusMessage *reply;
6520 reply = g_dbus_message_new_method_reply (message);
6521 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6522 g_object_unref (reply);
6525 /* may be called in any thread, with connection's lock held */
6527 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6528 const gchar *object_path,
6529 GDBusMessage *message)
6531 GDBusMessage *reply;
6534 if (connection->machine_id == NULL)
6539 connection->machine_id = _g_dbus_get_machine_id (&error);
6540 if (connection->machine_id == NULL)
6542 reply = g_dbus_message_new_method_error_literal (message,
6543 "org.freedesktop.DBus.Error.Failed",
6545 g_error_free (error);
6551 reply = g_dbus_message_new_method_reply (message);
6552 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6554 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6555 g_object_unref (reply);
6558 /* may be called in any thread, with connection's lock held */
6560 handle_generic_introspect_unlocked (GDBusConnection *connection,
6561 const gchar *object_path,
6562 GDBusMessage *message)
6567 GDBusMessage *reply;
6569 /* first the header */
6570 s = g_string_new (NULL);
6571 introspect_append_header (s);
6573 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6574 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6575 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6576 g_strfreev (registered);
6577 g_string_append (s, "</node>\n");
6579 reply = g_dbus_message_new_method_reply (message);
6580 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6581 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6582 g_object_unref (reply);
6583 g_string_free (s, TRUE);
6586 /* may be called in any thread, with connection's lock held */
6588 handle_generic_unlocked (GDBusConnection *connection,
6589 GDBusMessage *message)
6592 const gchar *interface_name;
6593 const gchar *member;
6594 const gchar *signature;
6597 CONNECTION_ENSURE_LOCK (connection);
6601 interface_name = g_dbus_message_get_interface (message);
6602 member = g_dbus_message_get_member (message);
6603 signature = g_dbus_message_get_signature (message);
6604 path = g_dbus_message_get_path (message);
6606 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6607 g_strcmp0 (member, "Introspect") == 0 &&
6608 g_strcmp0 (signature, "") == 0)
6610 handle_generic_introspect_unlocked (connection, path, message);
6613 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6614 g_strcmp0 (member, "Ping") == 0 &&
6615 g_strcmp0 (signature, "") == 0)
6617 handle_generic_ping_unlocked (connection, path, message);
6620 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6621 g_strcmp0 (member, "GetMachineId") == 0 &&
6622 g_strcmp0 (signature, "") == 0)
6624 handle_generic_get_machine_id_unlocked (connection, path, message);
6631 /* ---------------------------------------------------------------------------------------------------- */
6633 /* called in GDBusWorker thread with connection's lock held */
6635 distribute_method_call (GDBusConnection *connection,
6636 GDBusMessage *message)
6638 GDBusMessage *reply;
6640 ExportedSubtree *es;
6641 const gchar *object_path;
6642 const gchar *interface_name;
6643 const gchar *member;
6645 gchar *subtree_path;
6648 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6650 interface_name = g_dbus_message_get_interface (message);
6651 member = g_dbus_message_get_member (message);
6652 path = g_dbus_message_get_path (message);
6653 subtree_path = g_strdup (path);
6654 needle = strrchr (subtree_path, '/');
6655 if (needle != NULL && needle != subtree_path)
6661 g_free (subtree_path);
6662 subtree_path = NULL;
6666 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6668 _g_dbus_debug_print_lock ();
6669 g_print ("========================================================================\n"
6670 "GDBus-debug:Incoming:\n"
6671 " <<<< METHOD INVOCATION %s.%s()\n"
6673 " invoked by name %s\n"
6675 interface_name, member,
6677 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6678 g_dbus_message_get_serial (message));
6679 _g_dbus_debug_print_unlock ();
6682 object_path = g_dbus_message_get_path (message);
6683 g_assert (object_path != NULL);
6685 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6688 if (obj_message_func (connection, eo, message))
6692 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6695 if (subtree_message_func (connection, es, message))
6699 if (subtree_path != NULL)
6701 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6704 if (subtree_message_func (connection, es, message))
6709 if (handle_generic_unlocked (connection, message))
6712 /* if we end up here, the message has not been not handled - so return an error saying this */
6713 reply = g_dbus_message_new_method_error (message,
6714 "org.freedesktop.DBus.Error.UnknownMethod",
6715 _("No such interface `%s' on object at path %s"),
6718 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6719 g_object_unref (reply);
6722 g_free (subtree_path);
6725 /* ---------------------------------------------------------------------------------------------------- */
6727 /* Called in any user thread, with the message_bus_lock held. */
6729 message_bus_get_singleton (GBusType bus_type,
6733 const gchar *starter_bus;
6739 case G_BUS_TYPE_SESSION:
6740 ret = &the_session_bus;
6743 case G_BUS_TYPE_SYSTEM:
6744 ret = &the_system_bus;
6747 case G_BUS_TYPE_STARTER:
6748 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6749 if (g_strcmp0 (starter_bus, "session") == 0)
6751 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6754 else if (g_strcmp0 (starter_bus, "system") == 0)
6756 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6761 if (starter_bus != NULL)
6765 G_IO_ERROR_INVALID_ARGUMENT,
6766 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6767 " - unknown value `%s'"),
6772 g_set_error_literal (error,
6774 G_IO_ERROR_INVALID_ARGUMENT,
6775 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6776 "variable is not set"));
6782 g_assert_not_reached ();
6790 /* Called in any user thread, without holding locks. */
6791 static GDBusConnection *
6792 get_uninitialized_connection (GBusType bus_type,
6793 GCancellable *cancellable,
6796 GWeakRef *singleton;
6797 GDBusConnection *ret;
6801 G_LOCK (message_bus_lock);
6802 singleton = message_bus_get_singleton (bus_type, error);
6803 if (singleton == NULL)
6806 ret = g_weak_ref_get (singleton);
6811 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6812 if (address == NULL)
6814 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6816 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6817 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6818 "exit-on-close", TRUE,
6821 g_weak_ref_set (singleton, ret);
6825 g_assert (ret != NULL);
6828 G_UNLOCK (message_bus_lock);
6832 /* May be called from any thread. Must not hold message_bus_lock. */
6834 _g_bus_get_singleton_if_exists (GBusType bus_type)
6836 GWeakRef *singleton;
6837 GDBusConnection *ret = NULL;
6839 G_LOCK (message_bus_lock);
6840 singleton = message_bus_get_singleton (bus_type, NULL);
6841 if (singleton == NULL)
6844 ret = g_weak_ref_get (singleton);
6847 G_UNLOCK (message_bus_lock);
6853 * @bus_type: A #GBusType.
6854 * @cancellable: (allow-none): A #GCancellable or %NULL.
6855 * @error: Return location for error or %NULL.
6857 * Synchronously connects to the message bus specified by @bus_type.
6858 * Note that the returned object may shared with other callers,
6859 * e.g. if two separate parts of a process calls this function with
6860 * the same @bus_type, they will share the same object.
6862 * This is a synchronous failable function. See g_bus_get() and
6863 * g_bus_get_finish() for the asynchronous version.
6865 * The returned object is a singleton, that is, shared with other
6866 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6867 * event that you need a private message bus connection, use
6868 * g_dbus_address_get_for_bus_sync() and
6869 * g_dbus_connection_new_for_address().
6871 * Note that the returned #GDBusConnection object will (usually) have
6872 * the #GDBusConnection:exit-on-close property set to %TRUE.
6874 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6879 g_bus_get_sync (GBusType bus_type,
6880 GCancellable *cancellable,
6883 GDBusConnection *connection;
6885 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6887 connection = get_uninitialized_connection (bus_type, cancellable, error);
6888 if (connection == NULL)
6891 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6893 g_object_unref (connection);
6902 bus_get_async_initable_cb (GObject *source_object,
6906 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
6910 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
6914 g_assert (error != NULL);
6915 g_simple_async_result_take_error (simple, error);
6916 g_object_unref (source_object);
6920 g_simple_async_result_set_op_res_gpointer (simple,
6924 g_simple_async_result_complete_in_idle (simple);
6925 g_object_unref (simple);
6930 * @bus_type: A #GBusType.
6931 * @cancellable: (allow-none): A #GCancellable or %NULL.
6932 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
6933 * @user_data: The data to pass to @callback.
6935 * Asynchronously connects to the message bus specified by @bus_type.
6937 * When the operation is finished, @callback will be invoked. You can
6938 * then call g_bus_get_finish() to get the result of the operation.
6940 * This is a asynchronous failable function. See g_bus_get_sync() for
6941 * the synchronous version.
6946 g_bus_get (GBusType bus_type,
6947 GCancellable *cancellable,
6948 GAsyncReadyCallback callback,
6951 GDBusConnection *connection;
6952 GSimpleAsyncResult *simple;
6955 simple = g_simple_async_result_new (NULL,
6959 g_simple_async_result_set_check_cancellable (simple, cancellable);
6962 connection = get_uninitialized_connection (bus_type, cancellable, &error);
6963 if (connection == NULL)
6965 g_assert (error != NULL);
6966 g_simple_async_result_take_error (simple, error);
6967 g_simple_async_result_complete_in_idle (simple);
6968 g_object_unref (simple);
6972 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
6975 bus_get_async_initable_cb,
6982 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
6983 * @error: Return location for error or %NULL.
6985 * Finishes an operation started with g_bus_get().
6987 * The returned object is a singleton, that is, shared with other
6988 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6989 * event that you need a private message bus connection, use
6990 * g_dbus_address_get_for_bus_sync() and
6991 * g_dbus_connection_new_for_address().
6993 * Note that the returned #GDBusConnection object will (usually) have
6994 * the #GDBusConnection:exit-on-close property set to %TRUE.
6996 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7001 g_bus_get_finish (GAsyncResult *res,
7004 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7006 GDBusConnection *ret;
7008 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7010 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7014 if (g_simple_async_result_propagate_error (simple, error))
7017 object = g_simple_async_result_get_op_res_gpointer (simple);
7018 g_assert (object != NULL);
7019 ret = g_object_ref (G_DBUS_CONNECTION (object));
7025 /* ---------------------------------------------------------------------------------------------------- */