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, see <http://www.gnu.org/licenses/>.
18 * Author: David Zeuthen <davidz@redhat.com>
24 * - would be nice to expose GDBusAuthMechanism and an extension point
26 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
27 * the mechanism VFuncs need to be able to set an error.
29 * - Need to document other mechanisms/sources for determining the D-Bus
30 * address of a well-known bus.
32 * - e.g. on Win32 we need code like from here
34 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
36 * that was never copied over here because it originally was copy-paste
37 * from the GPLv2 / AFL 2.1 libdbus sources.
39 * - on OS X we need to look in launchd for the address
41 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
43 * - on X11 we need to look in a X11 property on the X server
44 * - (we can also just use dbus-launch(1) from the D-Bus
47 * - (ideally) this requires D-Bus spec work because none of
48 * this has never really been specced out properly (except
51 * - Related to the above, we also need to be able to launch a message bus
52 * instance.... Since we don't want to write our own bus daemon we should
53 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
55 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
56 * to specify where the nonce is stored. This will allow people to use
57 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
58 * to easily achieve secure RPC via nonce-tcp.
60 * - need to expose an extension point for resolving D-Bus address and
61 * turning them into GIOStream objects. This will allow us to implement
62 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
64 * - see g_dbus_address_connect() in gdbusaddress.c
66 * - would be cute to use kernel-specific APIs to resolve fds for
67 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
69 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
71 * maybe we can show more information about what fd 21 really is.
72 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
73 * Initial experiments on Linux 2.6 suggests that the symlink looks
78 * e.g. not of much use.
80 * - GDBus High-Level docs
81 * - Proxy: properties, signals...
82 * - Connection: IOStream based, ::close, connection setup steps
83 * mainloop integration, threading
84 * - Differences from libdbus (extend "Migrating from")
85 * - the message handling thread
86 * - Using GVariant instead of GValue
87 * - Explain why the high-level API is a good thing and what
88 * kind of pitfalls it avoids
89 * - Export objects before claiming names
90 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
92 * - use abstract sockets in test code
93 * - right now it doesn't work, dbus-daemon(1) fails with
95 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
96 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
97 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
107 #include "gdbusauth.h"
108 #include "gdbusutils.h"
109 #include "gdbusaddress.h"
110 #include "gdbusmessage.h"
111 #include "gdbusconnection.h"
112 #include "gdbuserror.h"
113 #include "gioenumtypes.h"
114 #include "gdbusintrospection.h"
115 #include "gdbusmethodinvocation.h"
116 #include "gdbusprivate.h"
117 #include "gdbusauthobserver.h"
118 #include "ginitable.h"
119 #include "gasyncinitable.h"
120 #include "giostream.h"
121 #include "gasyncresult.h"
122 #include "gsimpleasyncresult.h"
125 #include "gunixconnection.h"
126 #include "gunixfdmessage.h"
129 #include "glibintl.h"
132 * SECTION:gdbusconnection
133 * @short_description: D-Bus Connections
134 * @include: gio/gio.h
136 * The #GDBusConnection type is used for D-Bus connections to remote
137 * peers such as a message buses. It is a low-level API that offers a
138 * lot of flexibility. For instance, it lets you establish a connection
139 * over any transport that can by represented as an #GIOStream.
141 * This class is rarely used directly in D-Bus clients. If you are writing
142 * an D-Bus client, it is often easier to use the g_bus_own_name(),
143 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
145 * As an exception to the usual GLib rule that a particular object must not
146 * be used by two threads at the same time, #GDBusConnection's methods may be
147 * called from any thread. This is so that g_bus_get() and g_bus_get_sync()
148 * can safely return the same #GDBusConnection when called from any thread.
150 * Most of the ways to obtain a #GDBusConnection automatically initialize it
151 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
152 * g_bus_get(), and the synchronous versions of those methods, give you an
153 * initialized connection. Language bindings for GIO should use
154 * g_initable_new() or g_async_initable_new_async(), which also initialize the
157 * If you construct an uninitialized #GDBusConnection, such as via
158 * g_object_new(), you must initialize it via g_initable_init() or
159 * g_async_initable_init_async() before using its methods or properties.
160 * Calling methods or accessing properties on a #GDBusConnection that has not
161 * completed initialization successfully is considered to be invalid, and leads
162 * to undefined behaviour. In particular, if initialization fails with a
163 * #GError, the only valid thing you can do with that #GDBusConnection is to
164 * free it with g_object_unref().
166 * <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>
168 * <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>
170 * <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>
172 * <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>
175 /* ---------------------------------------------------------------------------------------------------- */
177 typedef struct _GDBusConnectionClass GDBusConnectionClass;
180 * GDBusConnectionClass:
181 * @closed: Signal class handler for the #GDBusConnection::closed signal.
183 * Class structure for #GDBusConnection.
187 struct _GDBusConnectionClass
190 GObjectClass parent_class;
194 void (*closed) (GDBusConnection *connection,
195 gboolean remote_peer_vanished,
199 G_LOCK_DEFINE_STATIC (message_bus_lock);
201 static GWeakRef the_session_bus;
202 static GWeakRef the_system_bus;
204 /* Extra pseudo-member of GDBusSendMessageFlags.
205 * Set by initable_init() to indicate that despite not being initialized yet,
206 * enough of the only-valid-after-init members are set that we can send a
207 * message, and we're being called from its thread, so no memory barrier is
208 * required before accessing them.
210 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
212 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
213 #define CALL_FLAGS_INITIALIZING (1<<31)
215 /* ---------------------------------------------------------------------------------------------------- */
219 GDestroyNotify callback;
221 GMainContext *context;
222 } CallDestroyNotifyData;
225 call_destroy_notify_data_in_idle (gpointer user_data)
227 CallDestroyNotifyData *data = user_data;
228 data->callback (data->user_data);
233 call_destroy_notify_data_free (CallDestroyNotifyData *data)
235 if (data->context != NULL)
236 g_main_context_unref (data->context);
241 * call_destroy_notify: <internal>
242 * @context: (allow-none): A #GMainContext or %NULL.
243 * @callback: (allow-none): A #GDestroyNotify or %NULL.
244 * @user_data: Data to pass to @callback.
246 * Schedules @callback to run in @context.
249 call_destroy_notify (GMainContext *context,
250 GDestroyNotify callback,
253 GSource *idle_source;
254 CallDestroyNotifyData *data;
256 if (callback == NULL)
259 data = g_new0 (CallDestroyNotifyData, 1);
260 data->callback = callback;
261 data->user_data = user_data;
262 data->context = context;
263 if (data->context != NULL)
264 g_main_context_ref (data->context);
266 idle_source = g_idle_source_new ();
267 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
268 g_source_set_callback (idle_source,
269 call_destroy_notify_data_in_idle,
271 (GDestroyNotify) call_destroy_notify_data_free);
272 g_source_attach (idle_source, data->context);
273 g_source_unref (idle_source);
279 /* ---------------------------------------------------------------------------------------------------- */
282 _g_strv_has_string (const gchar* const *haystack,
287 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
289 if (g_strcmp0 (haystack[n], needle) == 0)
295 /* ---------------------------------------------------------------------------------------------------- */
298 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
300 // TODO: for some reason this doesn't work on Windows
301 #define CONNECTION_ENSURE_LOCK(obj) do { \
302 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
304 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
305 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
310 #define CONNECTION_LOCK(obj) do { \
311 g_mutex_lock (&(obj)->lock); \
314 #define CONNECTION_UNLOCK(obj) do { \
315 g_mutex_unlock (&(obj)->lock); \
318 /* Flags in connection->atomic_flags */
320 FLAG_INITIALIZED = 1 << 0,
321 FLAG_EXIT_ON_CLOSE = 1 << 1,
328 * The #GDBusConnection structure contains only private data and
329 * should only be accessed using the provided API.
333 struct _GDBusConnection
336 GObject parent_instance;
338 /* ------------------------------------------------------------------------ */
339 /* -- General object state ------------------------------------------------ */
340 /* ------------------------------------------------------------------------ */
342 /* General-purpose lock for most fields */
345 /* A lock used in the init() method of the GInitable interface - see comments
346 * in initable_init() for why a separate lock is needed.
348 * If you need both @lock and @init_lock, you must take @init_lock first.
352 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
353 * someone calls org.freedesktop.DBus.Peer.GetMachineId(). Protected by @lock.
357 /* The underlying stream used for communication
358 * Read-only after initable_init(), so it may be read if you either
359 * hold @init_lock or check for initialization first.
363 /* The object used for authentication (if any).
364 * Read-only after initable_init(), so it may be read if you either
365 * hold @init_lock or check for initialization first.
369 /* Last serial used. Protected by @lock. */
372 /* The object used to send/receive messages.
373 * Read-only after initable_init(), so it may be read if you either
374 * hold @init_lock or check for initialization first.
378 /* If connected to a message bus, this contains the unique name assigned to
379 * us by the bus (e.g. ":1.42").
380 * Read-only after initable_init(), so it may be read if you either
381 * hold @init_lock or check for initialization first.
383 gchar *bus_unique_name;
385 /* The GUID returned by the other side if we authenticed as a client or
386 * the GUID to use if authenticating as a server.
387 * Read-only after initable_init(), so it may be read if you either
388 * hold @init_lock or check for initialization first.
392 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
393 * Inspect @initialization_error to see whether it succeeded or failed.
395 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
397 * FLAG_CLOSED is the closed property. It may be read at any time, but
398 * may only be written while holding @lock.
400 volatile gint atomic_flags;
402 /* If the connection could not be established during initable_init(),
403 * this GError will be set.
404 * Read-only after initable_init(), so it may be read if you either
405 * hold @init_lock or check for initialization first.
407 GError *initialization_error;
409 /* The result of g_main_context_ref_thread_default() when the object
410 * was created (the GObject _init() function) - this is used for delivery
411 * of the :closed GObject signal.
413 * Only set in the GObject init function, so no locks are needed.
415 GMainContext *main_context_at_construction;
417 /* Read-only construct properties, no locks needed */
419 GDBusConnectionFlags flags;
421 /* Map used for managing method replies, protected by @lock */
422 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
424 /* Maps used for managing signal subscription, protected by @lock */
425 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
426 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
427 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
429 /* Maps used for managing exported objects and subtrees,
432 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
433 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
434 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
435 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
437 /* Map used for storing last used serials for each thread, protected by @lock */
438 GHashTable *map_thread_to_last_serial;
440 /* Structure used for message filters, protected by @lock */
443 /* Capabilities negotiated during authentication
444 * Read-only after initable_init(), so it may be read without holding a
445 * lock, if you check for initialization first.
447 GDBusCapabilityFlags capabilities;
449 /* Protected by @init_lock */
450 GDBusAuthObserver *authentication_observer;
452 /* Read-only after initable_init(), so it may be read if you either
453 * hold @init_lock or check for initialization first.
455 GCredentials *credentials;
457 /* set to TRUE when finalizing */
461 typedef struct ExportedObject ExportedObject;
462 static void exported_object_free (ExportedObject *eo);
464 typedef struct ExportedSubtree ExportedSubtree;
465 static void exported_subtree_free (ExportedSubtree *es);
483 PROP_CAPABILITY_FLAGS,
484 PROP_AUTHENTICATION_OBSERVER,
487 static void distribute_signals (GDBusConnection *connection,
488 GDBusMessage *message);
490 static void distribute_method_call (GDBusConnection *connection,
491 GDBusMessage *message);
493 static gboolean handle_generic_unlocked (GDBusConnection *connection,
494 GDBusMessage *message);
497 static void purge_all_signal_subscriptions (GDBusConnection *connection);
498 static void purge_all_filters (GDBusConnection *connection);
500 static void schedule_method_call (GDBusConnection *connection,
501 GDBusMessage *message,
502 guint registration_id,
503 guint subtree_registration_id,
504 const GDBusInterfaceInfo *interface_info,
505 const GDBusMethodInfo *method_info,
506 const GDBusPropertyInfo *property_info,
507 GVariant *parameters,
508 const GDBusInterfaceVTable *vtable,
509 GMainContext *main_context,
512 #define _G_ENSURE_LOCK(name) do { \
513 if (G_UNLIKELY (G_TRYLOCK(name))) \
515 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
516 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
520 static guint signals[LAST_SIGNAL] = { 0 };
522 static void initable_iface_init (GInitableIface *initable_iface);
523 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
525 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
526 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
527 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
531 * Check that all members of @connection that can only be accessed after
532 * the connection is initialized can safely be accessed. If not,
533 * log a critical warning. This function is a memory barrier.
535 * Returns: %TRUE if initialized
538 check_initialized (GDBusConnection *connection)
540 /* The access to @atomic_flags isn't conditional, so that this function
541 * provides a memory barrier for thread-safety even if checks are disabled.
542 * (If you don't want this stricter guarantee, you can call
543 * g_return_if_fail (check_initialized (c)).)
545 * This isn't strictly necessary now that we've decided use of an
546 * uninitialized GDBusConnection is undefined behaviour, but it seems
547 * better to be as deterministic as is feasible.
549 * (Anything that could suffer a crash from seeing undefined values
550 * must have a race condition - thread A initializes the connection while
551 * thread B calls a method without initialization, hoping that thread A will
552 * win the race - so its behaviour is undefined anyway.)
554 gint flags = g_atomic_int_get (&connection->atomic_flags);
556 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
558 /* We can safely access this, due to the memory barrier above */
559 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
565 MAY_BE_UNINITIALIZED = (1<<1)
566 } CheckUnclosedFlags;
569 * Check the same thing as check_initialized(), and also that the
570 * connection is not closed. If the connection is uninitialized,
571 * raise a critical warning (it's programmer error); if it's closed,
572 * raise a recoverable GError (it's a runtime error).
574 * This function is a memory barrier.
576 * Returns: %TRUE if initialized and not closed
579 check_unclosed (GDBusConnection *connection,
580 CheckUnclosedFlags check,
583 /* check_initialized() is effectively inlined, so we don't waste time
584 * doing two memory barriers
586 gint flags = g_atomic_int_get (&connection->atomic_flags);
588 if (!(check & MAY_BE_UNINITIALIZED))
590 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
591 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
594 if (flags & FLAG_CLOSED)
596 g_set_error_literal (error,
599 _("The connection is closed"));
606 static GHashTable *alive_connections = NULL;
609 g_dbus_connection_dispose (GObject *object)
611 GDBusConnection *connection = G_DBUS_CONNECTION (object);
613 G_LOCK (message_bus_lock);
614 CONNECTION_LOCK (connection);
615 if (connection->worker != NULL)
617 _g_dbus_worker_stop (connection->worker);
618 connection->worker = NULL;
619 if (alive_connections != NULL)
620 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
624 if (alive_connections != NULL)
625 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
627 CONNECTION_UNLOCK (connection);
628 G_UNLOCK (message_bus_lock);
630 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
631 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
635 g_dbus_connection_finalize (GObject *object)
637 GDBusConnection *connection = G_DBUS_CONNECTION (object);
639 connection->finalizing = TRUE;
641 purge_all_signal_subscriptions (connection);
643 purge_all_filters (connection);
644 g_ptr_array_unref (connection->filters);
646 if (connection->authentication_observer != NULL)
647 g_object_unref (connection->authentication_observer);
649 if (connection->auth != NULL)
650 g_object_unref (connection->auth);
652 if (connection->credentials)
653 g_object_unref (connection->credentials);
655 if (connection->stream != NULL)
657 g_object_unref (connection->stream);
658 connection->stream = NULL;
661 g_free (connection->address);
663 g_free (connection->guid);
664 g_free (connection->bus_unique_name);
666 if (connection->initialization_error != NULL)
667 g_error_free (connection->initialization_error);
669 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
671 g_hash_table_unref (connection->map_rule_to_signal_data);
672 g_hash_table_unref (connection->map_id_to_signal_data);
673 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
675 g_hash_table_unref (connection->map_id_to_ei);
676 g_hash_table_unref (connection->map_object_path_to_eo);
677 g_hash_table_unref (connection->map_id_to_es);
678 g_hash_table_unref (connection->map_object_path_to_es);
680 g_hash_table_unref (connection->map_thread_to_last_serial);
682 g_main_context_unref (connection->main_context_at_construction);
684 g_free (connection->machine_id);
686 g_mutex_clear (&connection->init_lock);
687 g_mutex_clear (&connection->lock);
689 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
692 /* called in any user thread, with the connection's lock not held */
694 g_dbus_connection_get_property (GObject *object,
699 GDBusConnection *connection = G_DBUS_CONNECTION (object);
704 g_value_set_object (value, g_dbus_connection_get_stream (connection));
708 g_value_set_string (value, g_dbus_connection_get_guid (connection));
711 case PROP_UNIQUE_NAME:
712 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
716 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
719 case PROP_EXIT_ON_CLOSE:
720 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
723 case PROP_CAPABILITY_FLAGS:
724 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
728 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
733 /* called in any user thread, with the connection's lock not held */
735 g_dbus_connection_set_property (GObject *object,
740 GDBusConnection *connection = G_DBUS_CONNECTION (object);
745 connection->stream = g_value_dup_object (value);
749 connection->guid = g_value_dup_string (value);
753 connection->address = g_value_dup_string (value);
757 connection->flags = g_value_get_flags (value);
760 case PROP_EXIT_ON_CLOSE:
761 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
764 case PROP_AUTHENTICATION_OBSERVER:
765 connection->authentication_observer = g_value_dup_object (value);
769 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
774 /* Base-class implementation of GDBusConnection::closed.
776 * Called in a user thread, by the main context that was thread-default when
777 * the object was constructed.
780 g_dbus_connection_real_closed (GDBusConnection *connection,
781 gboolean remote_peer_vanished,
784 gint flags = g_atomic_int_get (&connection->atomic_flags);
786 /* Because atomic int access is a memory barrier, we can safely read
787 * initialization_error without a lock, as long as we do it afterwards.
789 if (remote_peer_vanished &&
790 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
791 (flags & FLAG_INITIALIZED) != 0 &&
792 connection->initialization_error == NULL)
796 g_printerr ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
799 g_quark_to_string (error->domain), error->code);
803 g_printerr ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
810 g_dbus_connection_class_init (GDBusConnectionClass *klass)
812 GObjectClass *gobject_class;
814 gobject_class = G_OBJECT_CLASS (klass);
816 gobject_class->finalize = g_dbus_connection_finalize;
817 gobject_class->dispose = g_dbus_connection_dispose;
818 gobject_class->set_property = g_dbus_connection_set_property;
819 gobject_class->get_property = g_dbus_connection_get_property;
821 klass->closed = g_dbus_connection_real_closed;
824 * GDBusConnection:stream:
826 * The underlying #GIOStream used for I/O.
828 * If this is passed on construction and is a #GSocketConnection,
829 * then the corresponding #GSocket will be put into non-blocking mode.
831 * While the #GDBusConnection is active, it will interact with this
832 * stream from a worker thread, so it is not safe to interact with
833 * the stream directly.
837 g_object_class_install_property (gobject_class,
839 g_param_spec_object ("stream",
841 P_("The underlying streams used for I/O"),
845 G_PARAM_CONSTRUCT_ONLY |
846 G_PARAM_STATIC_NAME |
847 G_PARAM_STATIC_BLURB |
848 G_PARAM_STATIC_NICK));
851 * GDBusConnection:address:
853 * A D-Bus address specifying potential endpoints that can be used
854 * when establishing the connection.
858 g_object_class_install_property (gobject_class,
860 g_param_spec_string ("address",
862 P_("D-Bus address specifying potential socket endpoints"),
865 G_PARAM_CONSTRUCT_ONLY |
866 G_PARAM_STATIC_NAME |
867 G_PARAM_STATIC_BLURB |
868 G_PARAM_STATIC_NICK));
871 * GDBusConnection:flags:
873 * Flags from the #GDBusConnectionFlags enumeration.
877 g_object_class_install_property (gobject_class,
879 g_param_spec_flags ("flags",
882 G_TYPE_DBUS_CONNECTION_FLAGS,
883 G_DBUS_CONNECTION_FLAGS_NONE,
885 G_PARAM_CONSTRUCT_ONLY |
886 G_PARAM_STATIC_NAME |
887 G_PARAM_STATIC_BLURB |
888 G_PARAM_STATIC_NICK));
891 * GDBusConnection:guid:
893 * The GUID of the peer performing the role of server when
896 * If you are constructing a #GDBusConnection and pass
897 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
898 * #GDBusConnection:flags property then you MUST also set this
899 * property to a valid guid.
901 * If you are constructing a #GDBusConnection and pass
902 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
903 * #GDBusConnection:flags property you will be able to read the GUID
904 * of the other peer here after the connection has been successfully
909 g_object_class_install_property (gobject_class,
911 g_param_spec_string ("guid",
913 P_("GUID of the server peer"),
917 G_PARAM_CONSTRUCT_ONLY |
918 G_PARAM_STATIC_NAME |
919 G_PARAM_STATIC_BLURB |
920 G_PARAM_STATIC_NICK));
923 * GDBusConnection:unique-name:
925 * The unique name as assigned by the message bus or %NULL if the
926 * connection is not open or not a message bus connection.
930 g_object_class_install_property (gobject_class,
932 g_param_spec_string ("unique-name",
934 P_("Unique name of bus connection"),
937 G_PARAM_STATIC_NAME |
938 G_PARAM_STATIC_BLURB |
939 G_PARAM_STATIC_NICK));
942 * GDBusConnection:closed:
944 * A boolean specifying whether the connection has been closed.
948 g_object_class_install_property (gobject_class,
950 g_param_spec_boolean ("closed",
952 P_("Whether the connection is closed"),
955 G_PARAM_STATIC_NAME |
956 G_PARAM_STATIC_BLURB |
957 G_PARAM_STATIC_NICK));
960 * GDBusConnection:exit-on-close:
962 * A boolean specifying whether the process will be terminated (by
963 * calling `raise(SIGTERM)`) if the connection is closed by the
966 * Note that #GDBusConnection objects returned by g_bus_get_finish()
967 * and g_bus_get_sync() will (usually) have this property set to %TRUE.
971 g_object_class_install_property (gobject_class,
973 g_param_spec_boolean ("exit-on-close",
975 P_("Whether the process is terminated when the connection is closed"),
979 G_PARAM_STATIC_NAME |
980 G_PARAM_STATIC_BLURB |
981 G_PARAM_STATIC_NICK));
984 * GDBusConnection:capabilities:
986 * Flags from the #GDBusCapabilityFlags enumeration
987 * representing connection features negotiated with the other peer.
991 g_object_class_install_property (gobject_class,
992 PROP_CAPABILITY_FLAGS,
993 g_param_spec_flags ("capabilities",
996 G_TYPE_DBUS_CAPABILITY_FLAGS,
997 G_DBUS_CAPABILITY_FLAGS_NONE,
999 G_PARAM_STATIC_NAME |
1000 G_PARAM_STATIC_BLURB |
1001 G_PARAM_STATIC_NICK));
1004 * GDBusConnection:authentication-observer:
1006 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1010 g_object_class_install_property (gobject_class,
1011 PROP_AUTHENTICATION_OBSERVER,
1012 g_param_spec_object ("authentication-observer",
1013 P_("Authentication Observer"),
1014 P_("Object used to assist in the authentication process"),
1015 G_TYPE_DBUS_AUTH_OBSERVER,
1017 G_PARAM_CONSTRUCT_ONLY |
1018 G_PARAM_STATIC_NAME |
1019 G_PARAM_STATIC_BLURB |
1020 G_PARAM_STATIC_NICK));
1023 * GDBusConnection::closed:
1024 * @connection: the #GDBusConnection emitting the signal
1025 * @remote_peer_vanished: %TRUE if @connection is closed because the
1026 * remote peer closed its end of the connection
1027 * @error: (allow-none): a #GError with more details about the event or %NULL
1029 * Emitted when the connection is closed.
1031 * The cause of this event can be
1033 * - If g_dbus_connection_close() is called. In this case
1034 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1036 * - If the remote peer closes the connection. In this case
1037 * @remote_peer_vanished is set to %TRUE and @error is set.
1039 * - If the remote peer sends invalid or malformed data. In this
1040 * case @remote_peer_vanished is set to %FALSE and @error is set.
1042 * Upon receiving this signal, you should give up your reference to
1043 * @connection. You are guaranteed that this signal is emitted only
1048 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1049 G_TYPE_DBUS_CONNECTION,
1051 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1062 g_dbus_connection_init (GDBusConnection *connection)
1064 g_mutex_init (&connection->lock);
1065 g_mutex_init (&connection->init_lock);
1067 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1069 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1071 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1073 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1076 (GDestroyNotify) g_ptr_array_unref);
1078 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1081 (GDestroyNotify) exported_object_free);
1083 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1086 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1089 (GDestroyNotify) exported_subtree_free);
1091 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1094 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1097 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1099 connection->filters = g_ptr_array_new ();
1103 * g_dbus_connection_get_stream:
1104 * @connection: a #GDBusConnection
1106 * Gets the underlying stream used for IO.
1108 * While the #GDBusConnection is active, it will interact with this
1109 * stream from a worker thread, so it is not safe to interact with
1110 * the stream directly.
1112 * Returns: (transfer none): the stream used for IO
1117 g_dbus_connection_get_stream (GDBusConnection *connection)
1119 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1121 /* do not use g_return_val_if_fail(), we want the memory barrier */
1122 if (!check_initialized (connection))
1125 return connection->stream;
1129 * g_dbus_connection_start_message_processing:
1130 * @connection: a #GDBusConnection
1132 * If @connection was created with
1133 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1134 * starts processing messages. Does nothing on if @connection wasn't
1135 * created with this flag or if the method has already been called.
1140 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1142 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1144 /* do not use g_return_val_if_fail(), we want the memory barrier */
1145 if (!check_initialized (connection))
1148 g_assert (connection->worker != NULL);
1149 _g_dbus_worker_unfreeze (connection->worker);
1153 * g_dbus_connection_is_closed:
1154 * @connection: a #GDBusConnection
1156 * Gets whether @connection is closed.
1158 * Returns: %TRUE if the connection is closed, %FALSE otherwise
1163 g_dbus_connection_is_closed (GDBusConnection *connection)
1167 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1169 flags = g_atomic_int_get (&connection->atomic_flags);
1171 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1175 * g_dbus_connection_get_capabilities:
1176 * @connection: a #GDBusConnection
1178 * Gets the capabilities negotiated with the remote peer
1180 * Returns: zero or more flags from the #GDBusCapabilityFlags enumeration
1184 GDBusCapabilityFlags
1185 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1187 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1189 /* do not use g_return_val_if_fail(), we want the memory barrier */
1190 if (!check_initialized (connection))
1191 return G_DBUS_CAPABILITY_FLAGS_NONE;
1193 return connection->capabilities;
1196 /* ---------------------------------------------------------------------------------------------------- */
1198 /* Called in a temporary thread without holding locks. */
1200 flush_in_thread_func (GSimpleAsyncResult *res,
1202 GCancellable *cancellable)
1207 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1210 g_simple_async_result_take_error (res, error);
1214 * g_dbus_connection_flush:
1215 * @connection: a #GDBusConnection
1216 * @cancellable: (allow-none): a #GCancellable or %NULL
1217 * @callback: (allow-none): a #GAsyncReadyCallback to call when the
1218 * request is satisfied or %NULL if you don't care about the result
1219 * @user_data: The data to pass to @callback
1221 * Asynchronously flushes @connection, that is, writes all queued
1222 * outgoing message to the transport and then flushes the transport
1223 * (using g_output_stream_flush_async()). This is useful in programs
1224 * that wants to emit a D-Bus signal and then exit immediately. Without
1225 * flushing the connection, there is no guaranteed that the message has
1226 * been sent to the networking buffers in the OS kernel.
1228 * This is an asynchronous method. When the operation is finished,
1229 * @callback will be invoked in the
1230 * [thread-default main context][g-main-context-push-thread-default]
1231 * of the thread you are calling this method from. You can
1232 * then call g_dbus_connection_flush_finish() to get the result of the
1233 * operation. See g_dbus_connection_flush_sync() for the synchronous
1239 g_dbus_connection_flush (GDBusConnection *connection,
1240 GCancellable *cancellable,
1241 GAsyncReadyCallback callback,
1244 GSimpleAsyncResult *simple;
1246 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1248 simple = g_simple_async_result_new (G_OBJECT (connection),
1251 g_dbus_connection_flush);
1252 g_simple_async_result_set_check_cancellable (simple, cancellable);
1253 g_simple_async_result_run_in_thread (simple,
1254 flush_in_thread_func,
1257 g_object_unref (simple);
1261 * g_dbus_connection_flush_finish:
1262 * @connection: a #GDBusConnection
1263 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1264 * to g_dbus_connection_flush()
1265 * @error: return location for error or %NULL
1267 * Finishes an operation started with g_dbus_connection_flush().
1269 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1274 g_dbus_connection_flush_finish (GDBusConnection *connection,
1278 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1283 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1284 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1285 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1287 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1289 if (g_simple_async_result_propagate_error (simple, error))
1299 * g_dbus_connection_flush_sync:
1300 * @connection: a #GDBusConnection
1301 * @cancellable: (allow-none): a #GCancellable or %NULL
1302 * @error: return location for error or %NULL
1304 * Synchronously flushes @connection. The calling thread is blocked
1305 * until this is done. See g_dbus_connection_flush() for the
1306 * asynchronous version of this method and more details about what it
1309 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1314 g_dbus_connection_flush_sync (GDBusConnection *connection,
1315 GCancellable *cancellable,
1320 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1321 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1325 /* This is only a best-effort attempt to see whether the connection is
1326 * closed, so it doesn't need the lock. If the connection closes just
1327 * after this check, but before scheduling the flush operation, the
1328 * result will be more or less the same as if the connection closed while
1329 * the flush operation was pending - it'll fail with either CLOSED or
1332 if (!check_unclosed (connection, 0, error))
1335 g_assert (connection->worker != NULL);
1337 ret = _g_dbus_worker_flush_sync (connection->worker,
1345 /* ---------------------------------------------------------------------------------------------------- */
1349 GDBusConnection *connection;
1351 gboolean remote_peer_vanished;
1355 emit_closed_data_free (EmitClosedData *data)
1357 g_object_unref (data->connection);
1358 if (data->error != NULL)
1359 g_error_free (data->error);
1363 /* Called in a user thread that has acquired the main context that was
1364 * thread-default when the object was constructed
1367 emit_closed_in_idle (gpointer user_data)
1369 EmitClosedData *data = user_data;
1372 g_object_notify (G_OBJECT (data->connection), "closed");
1373 g_signal_emit (data->connection,
1374 signals[CLOSED_SIGNAL],
1376 data->remote_peer_vanished,
1382 /* Can be called from any thread, must hold lock.
1383 * FLAG_CLOSED must already have been set.
1386 schedule_closed_unlocked (GDBusConnection *connection,
1387 gboolean remote_peer_vanished,
1390 GSource *idle_source;
1391 EmitClosedData *data;
1393 CONNECTION_ENSURE_LOCK (connection);
1395 data = g_new0 (EmitClosedData, 1);
1396 data->connection = g_object_ref (connection);
1397 data->remote_peer_vanished = remote_peer_vanished;
1398 data->error = error != NULL ? g_error_copy (error) : NULL;
1400 idle_source = g_idle_source_new ();
1401 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1402 g_source_set_callback (idle_source,
1403 emit_closed_in_idle,
1405 (GDestroyNotify) emit_closed_data_free);
1406 g_source_attach (idle_source, connection->main_context_at_construction);
1407 g_source_unref (idle_source);
1410 /* ---------------------------------------------------------------------------------------------------- */
1413 * g_dbus_connection_close:
1414 * @connection: a #GDBusConnection
1415 * @cancellable: (allow-none): a #GCancellable or %NULL
1416 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
1417 * satisfied or %NULL if you don't care about the result
1418 * @user_data: The data to pass to @callback
1420 * Closes @connection. Note that this never causes the process to
1421 * exit (this might only happen if the other end of a shared message
1422 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1424 * Once the connection is closed, operations such as sending a message
1425 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1426 * will not automatically flush the connection so queued messages may
1427 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1429 * If @connection is already closed, this method fails with
1430 * %G_IO_ERROR_CLOSED.
1432 * When @connection has been closed, the #GDBusConnection::closed
1433 * signal is emitted in the
1434 * [thread-default main context][g-main-context-push-thread-default]
1435 * of the thread that @connection was constructed in.
1437 * This is an asynchronous method. When the operation is finished,
1438 * @callback will be invoked in the
1439 * [thread-default main context][g-main-context-push-thread-default]
1440 * of the thread you are calling this method from. You can
1441 * then call g_dbus_connection_close_finish() to get the result of the
1442 * operation. See g_dbus_connection_close_sync() for the synchronous
1448 g_dbus_connection_close (GDBusConnection *connection,
1449 GCancellable *cancellable,
1450 GAsyncReadyCallback callback,
1453 GSimpleAsyncResult *simple;
1455 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1457 /* do not use g_return_val_if_fail(), we want the memory barrier */
1458 if (!check_initialized (connection))
1461 g_assert (connection->worker != NULL);
1463 simple = g_simple_async_result_new (G_OBJECT (connection),
1466 g_dbus_connection_close);
1467 g_simple_async_result_set_check_cancellable (simple, cancellable);
1468 _g_dbus_worker_close (connection->worker, cancellable, simple);
1469 g_object_unref (simple);
1473 * g_dbus_connection_close_finish:
1474 * @connection: a #GDBusConnection
1475 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
1476 * to g_dbus_connection_close()
1477 * @error: return location for error or %NULL
1479 * Finishes an operation started with g_dbus_connection_close().
1481 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1486 g_dbus_connection_close_finish (GDBusConnection *connection,
1490 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1495 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1496 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1497 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1499 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1501 if (g_simple_async_result_propagate_error (simple, error))
1512 GAsyncResult *result;
1515 /* Can be called by any thread, without the connection lock */
1517 sync_close_cb (GObject *source_object,
1521 SyncCloseData *data = user_data;
1523 data->result = g_object_ref (res);
1524 g_main_loop_quit (data->loop);
1528 * g_dbus_connection_close_sync:
1529 * @connection: a #GDBusConnection
1530 * @cancellable: (allow-none): a #GCancellable or %NULL
1531 * @error: return location for error or %NULL
1533 * Synchronously closees @connection. The calling thread is blocked
1534 * until this is done. See g_dbus_connection_close() for the
1535 * asynchronous version of this method and more details about what it
1538 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set
1543 g_dbus_connection_close_sync (GDBusConnection *connection,
1544 GCancellable *cancellable,
1549 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1550 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1554 if (check_unclosed (connection, 0, error))
1556 GMainContext *context;
1559 context = g_main_context_new ();
1560 g_main_context_push_thread_default (context);
1561 data.loop = g_main_loop_new (context, TRUE);
1564 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1565 g_main_loop_run (data.loop);
1566 ret = g_dbus_connection_close_finish (connection, data.result, error);
1568 g_object_unref (data.result);
1569 g_main_loop_unref (data.loop);
1570 g_main_context_pop_thread_default (context);
1571 g_main_context_unref (context);
1577 /* ---------------------------------------------------------------------------------------------------- */
1580 * g_dbus_connection_get_last_serial:
1581 * @connection: a #GDBusConnection
1583 * Retrieves the last serial number assigned to a #GDBusMessage on
1584 * the current thread. This includes messages sent via both low-level
1585 * API such as g_dbus_connection_send_message() as well as
1586 * high-level API such as g_dbus_connection_emit_signal(),
1587 * g_dbus_connection_call() or g_dbus_proxy_call().
1589 * Returns: the last used serial or zero when no message has been sent
1590 * within the current thread
1595 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1599 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1601 CONNECTION_LOCK (connection);
1602 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1604 CONNECTION_UNLOCK (connection);
1609 /* ---------------------------------------------------------------------------------------------------- */
1611 /* Can be called by any thread, with the connection lock held */
1613 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1614 GDBusMessage *message,
1615 GDBusSendMessageFlags flags,
1616 volatile guint32 *out_serial,
1621 guint32 serial_to_use;
1624 CONNECTION_ENSURE_LOCK (connection);
1626 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1627 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1629 /* TODO: check all necessary headers are present */
1634 if (out_serial != NULL)
1637 /* If we're in initable_init(), don't check for being initialized, to avoid
1638 * chicken-and-egg problems. initable_init() is responsible for setting up
1639 * our prerequisites (mainly connection->worker), and only calling us
1640 * from its own thread (so no memory barrier is needed).
1642 if (!check_unclosed (connection,
1643 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1647 blob = g_dbus_message_to_blob (message,
1649 connection->capabilities,
1654 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1655 serial_to_use = g_dbus_message_get_serial (message);
1657 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1662 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1665 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1668 g_assert_not_reached ();
1673 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1674 blob_size, serial_to_use, connection);
1675 g_printerr ("----\n");
1676 hexdump (blob, blob_size);
1677 g_printerr ("----\n");
1680 /* TODO: use connection->auth to encode the blob */
1682 if (out_serial != NULL)
1683 *out_serial = serial_to_use;
1685 /* store used serial for the current thread */
1686 /* TODO: watch the thread disposal and remove associated record
1688 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1690 g_hash_table_replace (connection->map_thread_to_last_serial,
1692 GUINT_TO_POINTER (serial_to_use));
1694 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1695 g_dbus_message_set_serial (message, serial_to_use);
1697 g_dbus_message_lock (message);
1698 _g_dbus_worker_send_message (connection->worker,
1702 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1713 * g_dbus_connection_send_message:
1714 * @connection: a #GDBusConnection
1715 * @message: a #GDBusMessage
1716 * @flags: flags affecting how the message is sent
1717 * @out_serial: (out) (allow-none): return location for serial number assigned
1718 * to @message when sending it or %NULL
1719 * @error: Return location for error or %NULL
1721 * Asynchronously sends @message to the peer represented by @connection.
1723 * Unless @flags contain the
1724 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1725 * will be assigned by @connection and set on @message via
1726 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1727 * serial number used will be written to this location prior to
1728 * submitting the message to the underlying transport.
1730 * If @connection is closed then the operation will fail with
1731 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1732 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1734 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
1735 * for an example of how to use this low-level API to send and receive
1736 * UNIX file descriptors.
1738 * Note that @message must be unlocked, unless @flags contain the
1739 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1741 * Returns: %TRUE if the message was well-formed and queued for
1742 * transmission, %FALSE if @error is set
1747 g_dbus_connection_send_message (GDBusConnection *connection,
1748 GDBusMessage *message,
1749 GDBusSendMessageFlags flags,
1750 volatile guint32 *out_serial,
1755 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1756 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1757 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1758 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1760 CONNECTION_LOCK (connection);
1761 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1762 CONNECTION_UNLOCK (connection);
1766 /* ---------------------------------------------------------------------------------------------------- */
1770 volatile gint ref_count;
1771 GDBusConnection *connection;
1773 GSimpleAsyncResult *simple;
1775 GMainContext *main_context;
1777 GCancellable *cancellable;
1779 gulong cancellable_handler_id;
1781 GSource *timeout_source;
1786 /* Can be called from any thread with or without lock held */
1787 static SendMessageData *
1788 send_message_data_ref (SendMessageData *data)
1790 g_atomic_int_inc (&data->ref_count);
1794 /* Can be called from any thread with or without lock held */
1796 send_message_data_unref (SendMessageData *data)
1798 if (g_atomic_int_dec_and_test (&data->ref_count))
1800 g_assert (data->timeout_source == NULL);
1801 g_assert (data->simple == NULL);
1802 g_assert (data->cancellable_handler_id == 0);
1803 g_object_unref (data->connection);
1804 if (data->cancellable != NULL)
1805 g_object_unref (data->cancellable);
1806 g_main_context_unref (data->main_context);
1811 /* ---------------------------------------------------------------------------------------------------- */
1813 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1815 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1817 CONNECTION_ENSURE_LOCK (data->connection);
1819 g_assert (!data->delivered);
1821 data->delivered = TRUE;
1823 g_simple_async_result_complete_in_idle (data->simple);
1824 g_object_unref (data->simple);
1825 data->simple = NULL;
1827 if (data->timeout_source != NULL)
1829 g_source_destroy (data->timeout_source);
1830 data->timeout_source = NULL;
1832 if (data->cancellable_handler_id > 0)
1834 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1835 data->cancellable_handler_id = 0;
1840 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1841 GUINT_TO_POINTER (data->serial)));
1844 send_message_data_unref (data);
1847 /* ---------------------------------------------------------------------------------------------------- */
1849 /* Can be called from any thread with lock held */
1851 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1852 GDBusMessage *reply)
1854 if (data->delivered)
1857 g_simple_async_result_set_op_res_gpointer (data->simple,
1858 g_object_ref (reply),
1861 send_message_with_reply_deliver (data, TRUE);
1867 /* ---------------------------------------------------------------------------------------------------- */
1869 /* Called from a user thread, lock is not held */
1871 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1873 SendMessageData *data = user_data;
1875 CONNECTION_LOCK (data->connection);
1876 if (data->delivered)
1879 g_simple_async_result_set_error (data->simple,
1881 G_IO_ERROR_CANCELLED,
1882 _("Operation was cancelled"));
1884 send_message_with_reply_deliver (data, TRUE);
1887 CONNECTION_UNLOCK (data->connection);
1891 /* Can be called from any thread with or without lock held */
1893 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1896 SendMessageData *data = user_data;
1897 GSource *idle_source;
1899 /* postpone cancellation to idle handler since we may be called directly
1900 * via g_cancellable_connect() (e.g. holding lock)
1902 idle_source = g_idle_source_new ();
1903 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1904 g_source_set_callback (idle_source,
1905 send_message_with_reply_cancelled_idle_cb,
1906 send_message_data_ref (data),
1907 (GDestroyNotify) send_message_data_unref);
1908 g_source_attach (idle_source, data->main_context);
1909 g_source_unref (idle_source);
1912 /* ---------------------------------------------------------------------------------------------------- */
1914 /* Called from a user thread, lock is not held */
1916 send_message_with_reply_timeout_cb (gpointer user_data)
1918 SendMessageData *data = user_data;
1920 CONNECTION_LOCK (data->connection);
1921 if (data->delivered)
1924 g_simple_async_result_set_error (data->simple,
1926 G_IO_ERROR_TIMED_OUT,
1927 _("Timeout was reached"));
1929 send_message_with_reply_deliver (data, TRUE);
1932 CONNECTION_UNLOCK (data->connection);
1937 /* ---------------------------------------------------------------------------------------------------- */
1939 /* Called from a user thread, connection's lock is held */
1941 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1942 GDBusMessage *message,
1943 GDBusSendMessageFlags flags,
1945 volatile guint32 *out_serial,
1946 GCancellable *cancellable,
1947 GAsyncReadyCallback callback,
1950 GSimpleAsyncResult *simple;
1951 SendMessageData *data;
1953 volatile guint32 serial;
1957 if (out_serial == NULL)
1958 out_serial = &serial;
1960 if (timeout_msec == -1)
1961 timeout_msec = 25 * 1000;
1963 simple = g_simple_async_result_new (G_OBJECT (connection),
1966 g_dbus_connection_send_message_with_reply);
1967 g_simple_async_result_set_check_cancellable (simple, cancellable);
1969 if (g_cancellable_is_cancelled (cancellable))
1971 g_simple_async_result_set_error (simple,
1973 G_IO_ERROR_CANCELLED,
1974 _("Operation was cancelled"));
1975 g_simple_async_result_complete_in_idle (simple);
1976 g_object_unref (simple);
1981 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1983 g_simple_async_result_take_error (simple, error);
1984 g_simple_async_result_complete_in_idle (simple);
1985 g_object_unref (simple);
1989 data = g_new0 (SendMessageData, 1);
1990 data->ref_count = 1;
1991 data->connection = g_object_ref (connection);
1992 data->simple = simple;
1993 data->serial = *out_serial;
1994 data->main_context = g_main_context_ref_thread_default ();
1996 if (cancellable != NULL)
1998 data->cancellable = g_object_ref (cancellable);
1999 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2000 G_CALLBACK (send_message_with_reply_cancelled_cb),
2001 send_message_data_ref (data),
2002 (GDestroyNotify) send_message_data_unref);
2005 if (timeout_msec != G_MAXINT)
2007 data->timeout_source = g_timeout_source_new (timeout_msec);
2008 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2009 g_source_set_callback (data->timeout_source,
2010 send_message_with_reply_timeout_cb,
2011 send_message_data_ref (data),
2012 (GDestroyNotify) send_message_data_unref);
2013 g_source_attach (data->timeout_source, data->main_context);
2014 g_source_unref (data->timeout_source);
2017 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2018 GUINT_TO_POINTER (*out_serial),
2026 * g_dbus_connection_send_message_with_reply:
2027 * @connection: a #GDBusConnection
2028 * @message: a #GDBusMessage
2029 * @flags: flags affecting how the message is sent
2030 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2031 * timeout or %G_MAXINT for no timeout
2032 * @out_serial: (out) (allow-none): return location for serial number assigned
2033 * to @message when sending it or %NULL
2034 * @cancellable: (allow-none): a #GCancellable or %NULL
2035 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
2036 * is satisfied or %NULL if you don't care about the result
2037 * @user_data: The data to pass to @callback
2039 * Asynchronously sends @message to the peer represented by @connection.
2041 * Unless @flags contain the
2042 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2043 * will be assigned by @connection and set on @message via
2044 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2045 * serial number used will be written to this location prior to
2046 * submitting the message to the underlying transport.
2048 * If @connection is closed then the operation will fail with
2049 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2050 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2051 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2053 * This is an asynchronous method. When the operation is finished, @callback
2054 * will be invoked in the
2055 * [thread-default main context][g-main-context-push-thread-default]
2056 * of the thread you are calling this method from. You can then call
2057 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2058 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2060 * Note that @message must be unlocked, unless @flags contain the
2061 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2063 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2064 * for an example of how to use this low-level API to send and receive
2065 * UNIX file descriptors.
2070 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2071 GDBusMessage *message,
2072 GDBusSendMessageFlags flags,
2074 volatile guint32 *out_serial,
2075 GCancellable *cancellable,
2076 GAsyncReadyCallback callback,
2079 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2080 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2081 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2082 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2084 CONNECTION_LOCK (connection);
2085 g_dbus_connection_send_message_with_reply_unlocked (connection,
2093 CONNECTION_UNLOCK (connection);
2097 * g_dbus_connection_send_message_with_reply_finish:
2098 * @connection: a #GDBusConnection
2099 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
2100 * g_dbus_connection_send_message_with_reply()
2101 * @error: teturn location for error or %NULL
2103 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2105 * Note that @error is only set if a local in-process error
2106 * occurred. That is to say that the returned #GDBusMessage object may
2107 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2108 * g_dbus_message_to_gerror() to transcode this to a #GError.
2110 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2111 * for an example of how to use this low-level API to send and receive
2112 * UNIX file descriptors.
2114 * Returns: (transfer full): a locked #GDBusMessage or %NULL if @error is set
2119 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2123 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2124 GDBusMessage *reply;
2126 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2127 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2131 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2133 if (g_simple_async_result_propagate_error (simple, error))
2136 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2142 /* ---------------------------------------------------------------------------------------------------- */
2147 GMainContext *context;
2149 } SendMessageSyncData;
2151 /* Called from a user thread, lock is not held */
2153 send_message_with_reply_sync_cb (GDBusConnection *connection,
2157 SendMessageSyncData *data = user_data;
2158 data->res = g_object_ref (res);
2159 g_main_loop_quit (data->loop);
2163 * g_dbus_connection_send_message_with_reply_sync:
2164 * @connection: a #GDBusConnection
2165 * @message: a #GDBusMessage
2166 * @flags: flags affecting how the message is sent.
2167 * @timeout_msec: the timeout in milliseconds, -1 to use the default
2168 * timeout or %G_MAXINT for no timeout
2169 * @out_serial: (out) (allow-none): return location for serial number
2170 * assigned to @message when sending it or %NULL
2171 * @cancellable: (allow-none): a #GCancellable or %NULL
2172 * @error: return location for error or %NULL
2174 * Synchronously sends @message to the peer represented by @connection
2175 * and blocks the calling thread until a reply is received or the
2176 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2177 * for the asynchronous version of this method.
2179 * Unless @flags contain the
2180 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2181 * will be assigned by @connection and set on @message via
2182 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2183 * serial number used will be written to this location prior to
2184 * submitting the message to the underlying transport.
2186 * If @connection is closed then the operation will fail with
2187 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2188 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2189 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2191 * Note that @error is only set if a local in-process error
2192 * occurred. That is to say that the returned #GDBusMessage object may
2193 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2194 * g_dbus_message_to_gerror() to transcode this to a #GError.
2196 * See this [server][gdbus-server] and [client][gdbus-unix-fd-client]
2197 * for an example of how to use this low-level API to send and receive
2198 * UNIX file descriptors.
2200 * Note that @message must be unlocked, unless @flags contain the
2201 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2203 * Returns: (transfer full): a locked #GDBusMessage that is the reply
2204 * to @message or %NULL if @error is set
2209 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2210 GDBusMessage *message,
2211 GDBusSendMessageFlags flags,
2213 volatile guint32 *out_serial,
2214 GCancellable *cancellable,
2217 SendMessageSyncData *data;
2218 GDBusMessage *reply;
2220 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2221 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2222 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2223 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2224 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2226 data = g_new0 (SendMessageSyncData, 1);
2227 data->context = g_main_context_new ();
2228 data->loop = g_main_loop_new (data->context, FALSE);
2230 g_main_context_push_thread_default (data->context);
2232 g_dbus_connection_send_message_with_reply (connection,
2238 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2240 g_main_loop_run (data->loop);
2241 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2245 g_main_context_pop_thread_default (data->context);
2247 g_main_context_unref (data->context);
2248 g_main_loop_unref (data->loop);
2249 g_object_unref (data->res);
2255 /* ---------------------------------------------------------------------------------------------------- */
2259 GDBusMessageFilterFunction func;
2266 GDBusMessageFilterFunction filter_function;
2268 GDestroyNotify user_data_free_func;
2271 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2273 on_worker_message_received (GDBusWorker *worker,
2274 GDBusMessage *message,
2277 GDBusConnection *connection;
2278 FilterCallback *filters;
2283 G_LOCK (message_bus_lock);
2284 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2287 G_UNLOCK (message_bus_lock);
2290 connection = G_DBUS_CONNECTION (user_data);
2291 g_object_ref (connection);
2292 G_UNLOCK (message_bus_lock);
2294 //g_debug ("in on_worker_message_received");
2296 g_object_ref (message);
2297 g_dbus_message_lock (message);
2299 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2301 /* First collect the set of callback functions */
2302 CONNECTION_LOCK (connection);
2303 num_filters = connection->filters->len;
2304 filters = g_new0 (FilterCallback, num_filters);
2305 for (n = 0; n < num_filters; n++)
2307 FilterData *data = connection->filters->pdata[n];
2308 filters[n].func = data->filter_function;
2309 filters[n].user_data = data->user_data;
2311 CONNECTION_UNLOCK (connection);
2313 /* then call the filters in order (without holding the lock) */
2314 for (n = 0; n < num_filters; n++)
2316 message = filters[n].func (connection,
2319 filters[n].user_data);
2320 if (message == NULL)
2322 g_dbus_message_lock (message);
2325 /* Standard dispatch unless the filter ate the message - no need to
2326 * do anything if the message was altered
2328 if (message != NULL)
2330 GDBusMessageType message_type;
2332 message_type = g_dbus_message_get_message_type (message);
2333 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2335 guint32 reply_serial;
2336 SendMessageData *send_message_data;
2338 reply_serial = g_dbus_message_get_reply_serial (message);
2339 CONNECTION_LOCK (connection);
2340 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2341 GUINT_TO_POINTER (reply_serial));
2342 if (send_message_data != NULL)
2344 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2345 send_message_data_deliver_reply_unlocked (send_message_data, message);
2349 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2351 CONNECTION_UNLOCK (connection);
2353 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2355 CONNECTION_LOCK (connection);
2356 distribute_signals (connection, message);
2357 CONNECTION_UNLOCK (connection);
2359 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2361 CONNECTION_LOCK (connection);
2362 distribute_method_call (connection, message);
2363 CONNECTION_UNLOCK (connection);
2367 if (message != NULL)
2368 g_object_unref (message);
2369 g_object_unref (connection);
2373 /* Called in GDBusWorker's thread, lock is not held */
2374 static GDBusMessage *
2375 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2376 GDBusMessage *message,
2379 GDBusConnection *connection;
2380 FilterCallback *filters;
2385 G_LOCK (message_bus_lock);
2386 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2389 G_UNLOCK (message_bus_lock);
2392 connection = G_DBUS_CONNECTION (user_data);
2393 g_object_ref (connection);
2394 G_UNLOCK (message_bus_lock);
2396 //g_debug ("in on_worker_message_about_to_be_sent");
2398 /* First collect the set of callback functions */
2399 CONNECTION_LOCK (connection);
2400 num_filters = connection->filters->len;
2401 filters = g_new0 (FilterCallback, num_filters);
2402 for (n = 0; n < num_filters; n++)
2404 FilterData *data = connection->filters->pdata[n];
2405 filters[n].func = data->filter_function;
2406 filters[n].user_data = data->user_data;
2408 CONNECTION_UNLOCK (connection);
2410 /* then call the filters in order (without holding the lock) */
2411 for (n = 0; n < num_filters; n++)
2413 g_dbus_message_lock (message);
2414 message = filters[n].func (connection,
2417 filters[n].user_data);
2418 if (message == NULL)
2422 g_object_unref (connection);
2428 /* called with connection lock held, in GDBusWorker thread */
2430 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2432 SendMessageData *data = value;
2434 if (data->delivered)
2437 g_simple_async_result_set_error (data->simple,
2440 _("The connection is closed"));
2442 /* Ask send_message_with_reply_deliver not to remove the element from the
2443 * hash table - we're in the middle of a foreach; that would be unsafe.
2444 * Instead, return TRUE from this function so that it gets removed safely.
2446 send_message_with_reply_deliver (data, FALSE);
2450 /* Called in GDBusWorker's thread - we must not block - without lock held */
2452 on_worker_closed (GDBusWorker *worker,
2453 gboolean remote_peer_vanished,
2457 GDBusConnection *connection;
2459 guint old_atomic_flags;
2461 G_LOCK (message_bus_lock);
2462 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2465 G_UNLOCK (message_bus_lock);
2468 connection = G_DBUS_CONNECTION (user_data);
2469 g_object_ref (connection);
2470 G_UNLOCK (message_bus_lock);
2472 //g_debug ("in on_worker_closed: %s", error->message);
2474 CONNECTION_LOCK (connection);
2475 /* Even though this is atomic, we do it inside the lock to avoid breaking
2476 * assumptions in remove_match_rule(). We'd need the lock in a moment
2477 * anyway, so, no loss.
2479 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2481 if (!(old_atomic_flags & FLAG_CLOSED))
2483 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2484 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2486 CONNECTION_UNLOCK (connection);
2488 g_object_unref (connection);
2491 /* ---------------------------------------------------------------------------------------------------- */
2493 /* Determines the biggest set of capabilities we can support on this
2496 * Called with the init_lock held.
2498 static GDBusCapabilityFlags
2499 get_offered_capabilities_max (GDBusConnection *connection)
2501 GDBusCapabilityFlags ret;
2502 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2504 if (G_IS_UNIX_CONNECTION (connection->stream))
2505 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2510 /* Called in a user thread, lock is not held */
2512 initable_init (GInitable *initable,
2513 GCancellable *cancellable,
2516 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2519 /* This method needs to be idempotent to work with the singleton
2520 * pattern. See the docs for g_initable_init(). We implement this by
2523 * Unfortunately we can't use the main lock since the on_worker_*()
2524 * callbacks above needs the lock during initialization (for message
2525 * bus connections we do a synchronous Hello() call on the bus).
2527 g_mutex_lock (&connection->init_lock);
2531 /* Make this a no-op if we're already initialized (successfully or
2534 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2536 ret = (connection->initialization_error == NULL);
2540 /* Because of init_lock, we can't get here twice in different threads */
2541 g_assert (connection->initialization_error == NULL);
2543 /* The user can pass multiple (but mutally exclusive) construct
2546 * - stream (of type GIOStream)
2547 * - address (of type gchar*)
2549 * At the end of the day we end up with a non-NULL GIOStream
2550 * object in connection->stream.
2552 if (connection->address != NULL)
2554 g_assert (connection->stream == NULL);
2556 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2557 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2559 g_set_error_literal (&connection->initialization_error,
2561 G_IO_ERROR_INVALID_ARGUMENT,
2562 _("Unsupported flags encountered when constructing a client-side connection"));
2566 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2567 NULL, /* TODO: out_guid */
2569 &connection->initialization_error);
2570 if (connection->stream == NULL)
2573 else if (connection->stream != NULL)
2579 g_assert_not_reached ();
2582 /* Authenticate the connection */
2583 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2585 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2586 g_assert (connection->guid != NULL);
2587 connection->auth = _g_dbus_auth_new (connection->stream);
2588 if (!_g_dbus_auth_run_server (connection->auth,
2589 connection->authentication_observer,
2591 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2592 get_offered_capabilities_max (connection),
2593 &connection->capabilities,
2594 &connection->credentials,
2596 &connection->initialization_error))
2599 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2601 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2602 g_assert (connection->guid == NULL);
2603 connection->auth = _g_dbus_auth_new (connection->stream);
2604 connection->guid = _g_dbus_auth_run_client (connection->auth,
2605 connection->authentication_observer,
2606 get_offered_capabilities_max (connection),
2607 &connection->capabilities,
2609 &connection->initialization_error);
2610 if (connection->guid == NULL)
2614 if (connection->authentication_observer != NULL)
2616 g_object_unref (connection->authentication_observer);
2617 connection->authentication_observer = NULL;
2620 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2622 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2625 /* We want all IO operations to be non-blocking since they happen in
2626 * the worker thread which is shared by _all_ connections.
2628 if (G_IS_SOCKET_CONNECTION (connection->stream))
2630 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2634 G_LOCK (message_bus_lock);
2635 if (alive_connections == NULL)
2636 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2637 g_hash_table_insert (alive_connections, connection, connection);
2638 G_UNLOCK (message_bus_lock);
2640 connection->worker = _g_dbus_worker_new (connection->stream,
2641 connection->capabilities,
2642 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2643 on_worker_message_received,
2644 on_worker_message_about_to_be_sent,
2648 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2649 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2651 GVariant *hello_result;
2653 /* we could lift this restriction by adding code in gdbusprivate.c */
2654 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2656 g_set_error_literal (&connection->initialization_error,
2659 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2663 hello_result = g_dbus_connection_call_sync (connection,
2664 "org.freedesktop.DBus", /* name */
2665 "/org/freedesktop/DBus", /* path */
2666 "org.freedesktop.DBus", /* interface */
2668 NULL, /* parameters */
2669 G_VARIANT_TYPE ("(s)"),
2670 CALL_FLAGS_INITIALIZING,
2672 NULL, /* TODO: cancellable */
2673 &connection->initialization_error);
2674 if (hello_result == NULL)
2677 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2678 g_variant_unref (hello_result);
2679 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2686 g_assert (connection->initialization_error != NULL);
2687 g_propagate_error (error, g_error_copy (connection->initialization_error));
2690 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2691 g_mutex_unlock (&connection->init_lock);
2697 initable_iface_init (GInitableIface *initable_iface)
2699 initable_iface->init = initable_init;
2702 /* ---------------------------------------------------------------------------------------------------- */
2705 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2710 /* ---------------------------------------------------------------------------------------------------- */
2713 * g_dbus_connection_new:
2714 * @stream: a #GIOStream
2715 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2716 * @flags: flags describing how to make the connection
2717 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2718 * @cancellable: (allow-none): a #GCancellable or %NULL
2719 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2720 * @user_data: the data to pass to @callback
2722 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2723 * with the end represented by @stream.
2725 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2726 * will be put into non-blocking mode.
2728 * The D-Bus connection will interact with @stream from a worker thread.
2729 * As a result, the caller should not interact with @stream after this
2730 * method has been called, except by calling g_object_unref() on it.
2732 * If @observer is not %NULL it may be used to control the
2733 * authentication process.
2735 * When the operation is finished, @callback will be invoked. You can
2736 * then call g_dbus_connection_new_finish() to get the result of the
2739 * This is a asynchronous failable constructor. See
2740 * g_dbus_connection_new_sync() for the synchronous
2746 g_dbus_connection_new (GIOStream *stream,
2748 GDBusConnectionFlags flags,
2749 GDBusAuthObserver *observer,
2750 GCancellable *cancellable,
2751 GAsyncReadyCallback callback,
2754 g_return_if_fail (G_IS_IO_STREAM (stream));
2755 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2763 "authentication-observer", observer,
2768 * g_dbus_connection_new_finish:
2769 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback
2770 * passed to g_dbus_connection_new().
2771 * @error: return location for error or %NULL
2773 * Finishes an operation started with g_dbus_connection_new().
2775 * Returns: a #GDBusConnection or %NULL if @error is set. Free
2776 * with g_object_unref().
2781 g_dbus_connection_new_finish (GAsyncResult *res,
2785 GObject *source_object;
2787 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2788 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2790 source_object = g_async_result_get_source_object (res);
2791 g_assert (source_object != NULL);
2792 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2795 g_object_unref (source_object);
2797 return G_DBUS_CONNECTION (object);
2803 * g_dbus_connection_new_sync:
2804 * @stream: a #GIOStream
2805 * @guid: (allow-none): the GUID to use if a authenticating as a server or %NULL
2806 * @flags: flags describing how to make the connection
2807 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2808 * @cancellable: (allow-none): a #GCancellable or %NULL
2809 * @error: return location for error or %NULL
2811 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2812 * with the end represented by @stream.
2814 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2815 * will be put into non-blocking mode.
2817 * The D-Bus connection will interact with @stream from a worker thread.
2818 * As a result, the caller should not interact with @stream after this
2819 * method has been called, except by calling g_object_unref() on it.
2821 * If @observer is not %NULL it may be used to control the
2822 * authentication process.
2824 * This is a synchronous failable constructor. See
2825 * g_dbus_connection_new() for the asynchronous version.
2827 * Returns: a #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2832 g_dbus_connection_new_sync (GIOStream *stream,
2834 GDBusConnectionFlags flags,
2835 GDBusAuthObserver *observer,
2836 GCancellable *cancellable,
2839 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2840 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2841 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2847 "authentication-observer", observer,
2851 /* ---------------------------------------------------------------------------------------------------- */
2854 * g_dbus_connection_new_for_address:
2855 * @address: a D-Bus address
2856 * @flags: flags describing how to make the connection
2857 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2858 * @cancellable: (allow-none): a #GCancellable or %NULL
2859 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
2860 * @user_data: the data to pass to @callback
2862 * Asynchronously connects and sets up a D-Bus client connection for
2863 * exchanging D-Bus messages with an endpoint specified by @address
2864 * which must be in the D-Bus address format.
2866 * This constructor can only be used to initiate client-side
2867 * connections - use g_dbus_connection_new() if you need to act as the
2868 * server. In particular, @flags cannot contain the
2869 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2870 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2872 * When the operation is finished, @callback will be invoked. You can
2873 * then call g_dbus_connection_new_finish() to get the result of the
2876 * If @observer is not %NULL it may be used to control the
2877 * authentication process.
2879 * This is a asynchronous failable constructor. See
2880 * g_dbus_connection_new_for_address_sync() for the synchronous
2886 g_dbus_connection_new_for_address (const gchar *address,
2887 GDBusConnectionFlags flags,
2888 GDBusAuthObserver *observer,
2889 GCancellable *cancellable,
2890 GAsyncReadyCallback callback,
2893 g_return_if_fail (address != NULL);
2894 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2901 "authentication-observer", observer,
2906 * g_dbus_connection_new_for_address_finish:
2907 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
2908 * to g_dbus_connection_new()
2909 * @error: return location for error or %NULL
2911 * Finishes an operation started with g_dbus_connection_new_for_address().
2913 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2919 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2923 GObject *source_object;
2925 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2926 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2928 source_object = g_async_result_get_source_object (res);
2929 g_assert (source_object != NULL);
2930 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2933 g_object_unref (source_object);
2935 return G_DBUS_CONNECTION (object);
2941 * g_dbus_connection_new_for_address_sync:
2942 * @address: a D-Bus address
2943 * @flags: flags describing how to make the connection
2944 * @observer: (allow-none): a #GDBusAuthObserver or %NULL
2945 * @cancellable: (allow-none): a #GCancellable or %NULL
2946 * @error: return location for error or %NULL
2948 * Synchronously connects and sets up a D-Bus client connection for
2949 * exchanging D-Bus messages with an endpoint specified by @address
2950 * which must be in the D-Bus address format.
2952 * This constructor can only be used to initiate client-side
2953 * connections - use g_dbus_connection_new_sync() if you need to act
2954 * as the server. In particular, @flags cannot contain the
2955 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2956 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2958 * This is a synchronous failable constructor. See
2959 * g_dbus_connection_new_for_address() for the asynchronous version.
2961 * If @observer is not %NULL it may be used to control the
2962 * authentication process.
2964 * Returns: a #GDBusConnection or %NULL if @error is set. Free with
2970 g_dbus_connection_new_for_address_sync (const gchar *address,
2971 GDBusConnectionFlags flags,
2972 GDBusAuthObserver *observer,
2973 GCancellable *cancellable,
2976 g_return_val_if_fail (address != NULL, NULL);
2977 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2978 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2983 "authentication-observer", observer,
2987 /* ---------------------------------------------------------------------------------------------------- */
2990 * g_dbus_connection_set_exit_on_close:
2991 * @connection: a #GDBusConnection
2992 * @exit_on_close: whether the process should be terminated
2993 * when @connection is closed by the remote peer
2995 * Sets whether the process should be terminated when @connection is
2996 * closed by the remote peer. See #GDBusConnection:exit-on-close for
2999 * Note that this function should be used with care. Most modern UNIX
3000 * desktops tie the notion of a user session the session bus, and expect
3001 * all of a users applications to quit when their bus connection goes away.
3002 * If you are setting @exit_on_close to %FALSE for the shared session
3003 * bus connection, you should make sure that your application exits
3004 * when the user session ends.
3009 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3010 gboolean exit_on_close)
3012 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3015 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3017 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3022 * g_dbus_connection_get_exit_on_close:
3023 * @connection: a #GDBusConnection
3025 * Gets whether the process is terminated when @connection is
3026 * closed by the remote peer. See
3027 * #GDBusConnection:exit-on-close for more details.
3029 * Returns: whether the process is terminated when @connection is
3030 * closed by the remote peer
3035 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3037 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3039 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3046 * g_dbus_connection_get_guid:
3047 * @connection: a #GDBusConnection
3049 * The GUID of the peer performing the role of server when
3050 * authenticating. See #GDBusConnection:guid for more details.
3052 * Returns: The GUID. Do not free this string, it is owned by
3058 g_dbus_connection_get_guid (GDBusConnection *connection)
3060 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3061 return connection->guid;
3065 * g_dbus_connection_get_unique_name:
3066 * @connection: a #GDBusConnection
3068 * Gets the unique name of @connection as assigned by the message
3069 * bus. This can also be used to figure out if @connection is a
3070 * message bus connection.
3072 * Returns: the unique name or %NULL if @connection is not a message
3073 * bus connection. Do not free this string, it is owned by
3079 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3081 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3083 /* do not use g_return_val_if_fail(), we want the memory barrier */
3084 if (!check_initialized (connection))
3087 return connection->bus_unique_name;
3091 * g_dbus_connection_get_peer_credentials:
3092 * @connection: a #GDBusConnection
3094 * Gets the credentials of the authenticated peer. This will always
3095 * return %NULL unless @connection acted as a server
3096 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3097 * when set up and the client passed credentials as part of the
3098 * authentication process.
3100 * In a message bus setup, the message bus is always the server and
3101 * each application is a client. So this method will always return
3102 * %NULL for message bus clients.
3104 * Returns: (transfer none): a #GCredentials or %NULL if not available.
3105 * Do not free this object, it is owned by @connection.
3110 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3112 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3114 /* do not use g_return_val_if_fail(), we want the memory barrier */
3115 if (!check_initialized (connection))
3118 return connection->credentials;
3121 /* ---------------------------------------------------------------------------------------------------- */
3123 static guint _global_filter_id = 1;
3126 * g_dbus_connection_add_filter:
3127 * @connection: a #GDBusConnection
3128 * @filter_function: a filter function
3129 * @user_data: user data to pass to @filter_function
3130 * @user_data_free_func: function to free @user_data with when filter
3131 * is removed or %NULL
3133 * Adds a message filter. Filters are handlers that are run on all
3134 * incoming and outgoing messages, prior to standard dispatch. Filters
3135 * are run in the order that they were added. The same handler can be
3136 * added as a filter more than once, in which case it will be run more
3137 * than once. Filters added during a filter callback won't be run on
3138 * the message being processed. Filter functions are allowed to modify
3139 * and even drop messages.
3141 * Note that filters are run in a dedicated message handling thread so
3142 * they can't block and, generally, can't do anything but signal a
3143 * worker thread. Also note that filters are rarely needed - use API
3144 * such as g_dbus_connection_send_message_with_reply(),
3145 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3147 * If a filter consumes an incoming message the message is not
3148 * dispatched anywhere else - not even the standard dispatch machinery
3149 * (that API such as g_dbus_connection_signal_subscribe() and
3150 * g_dbus_connection_send_message_with_reply() relies on) will see the
3151 * message. Similary, if a filter consumes an outgoing message, the
3152 * message will not be sent to the other peer.
3154 * Returns: a filter identifier that can be used with
3155 * g_dbus_connection_remove_filter()
3160 g_dbus_connection_add_filter (GDBusConnection *connection,
3161 GDBusMessageFilterFunction filter_function,
3163 GDestroyNotify user_data_free_func)
3167 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3168 g_return_val_if_fail (filter_function != NULL, 0);
3169 g_return_val_if_fail (check_initialized (connection), 0);
3171 CONNECTION_LOCK (connection);
3172 data = g_new0 (FilterData, 1);
3173 data->id = _global_filter_id++; /* TODO: overflow etc. */
3174 data->filter_function = filter_function;
3175 data->user_data = user_data;
3176 data->user_data_free_func = user_data_free_func;
3177 g_ptr_array_add (connection->filters, data);
3178 CONNECTION_UNLOCK (connection);
3183 /* only called from finalize(), removes all filters */
3185 purge_all_filters (GDBusConnection *connection)
3188 for (n = 0; n < connection->filters->len; n++)
3190 FilterData *data = connection->filters->pdata[n];
3191 if (data->user_data_free_func != NULL)
3192 data->user_data_free_func (data->user_data);
3198 * g_dbus_connection_remove_filter:
3199 * @connection: a #GDBusConnection
3200 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3207 g_dbus_connection_remove_filter (GDBusConnection *connection,
3211 FilterData *to_destroy;
3213 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3214 g_return_if_fail (check_initialized (connection));
3216 CONNECTION_LOCK (connection);
3218 for (n = 0; n < connection->filters->len; n++)
3220 FilterData *data = connection->filters->pdata[n];
3221 if (data->id == filter_id)
3223 g_ptr_array_remove_index (connection->filters, n);
3228 CONNECTION_UNLOCK (connection);
3230 /* do free without holding lock */
3231 if (to_destroy != NULL)
3233 if (to_destroy->user_data_free_func != NULL)
3234 to_destroy->user_data_free_func (to_destroy->user_data);
3235 g_free (to_destroy);
3239 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3243 /* ---------------------------------------------------------------------------------------------------- */
3249 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3250 gchar *interface_name;
3254 GDBusSignalFlags flags;
3255 GArray *subscribers;
3260 GDBusSignalCallback callback;
3262 GDestroyNotify user_data_free_func;
3264 GMainContext *context;
3268 signal_data_free (SignalData *signal_data)
3270 g_free (signal_data->rule);
3271 g_free (signal_data->sender);
3272 g_free (signal_data->sender_unique_name);
3273 g_free (signal_data->interface_name);
3274 g_free (signal_data->member);
3275 g_free (signal_data->object_path);
3276 g_free (signal_data->arg0);
3277 g_array_free (signal_data->subscribers, TRUE);
3278 g_free (signal_data);
3282 args_to_rule (const gchar *sender,
3283 const gchar *interface_name,
3284 const gchar *member,
3285 const gchar *object_path,
3287 GDBusSignalFlags flags)
3291 rule = g_string_new ("type='signal'");
3292 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3293 g_string_prepend_c (rule, '-');
3295 g_string_append_printf (rule, ",sender='%s'", sender);
3296 if (interface_name != NULL)
3297 g_string_append_printf (rule, ",interface='%s'", interface_name);
3299 g_string_append_printf (rule, ",member='%s'", member);
3300 if (object_path != NULL)
3301 g_string_append_printf (rule, ",path='%s'", object_path);
3305 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3306 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3307 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3308 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3310 g_string_append_printf (rule, ",arg0='%s'", arg0);
3313 return g_string_free (rule, FALSE);
3316 static guint _global_subscriber_id = 1;
3317 static guint _global_registration_id = 1;
3318 static guint _global_subtree_registration_id = 1;
3320 /* ---------------------------------------------------------------------------------------------------- */
3322 /* Called in a user thread, lock is held */
3324 add_match_rule (GDBusConnection *connection,
3325 const gchar *match_rule)
3328 GDBusMessage *message;
3330 if (match_rule[0] == '-')
3333 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3334 "/org/freedesktop/DBus", /* path */
3335 "org.freedesktop.DBus", /* interface */
3337 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3339 if (!g_dbus_connection_send_message_unlocked (connection,
3341 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3345 g_critical ("Error while sending AddMatch() message: %s", error->message);
3346 g_error_free (error);
3348 g_object_unref (message);
3351 /* ---------------------------------------------------------------------------------------------------- */
3353 /* Called in a user thread, lock is held */
3355 remove_match_rule (GDBusConnection *connection,
3356 const gchar *match_rule)
3359 GDBusMessage *message;
3361 if (match_rule[0] == '-')
3364 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3365 "/org/freedesktop/DBus", /* path */
3366 "org.freedesktop.DBus", /* interface */
3368 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3371 if (!g_dbus_connection_send_message_unlocked (connection,
3373 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3377 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3378 * critical; but we're holding the lock, and our caller checked whether
3379 * we were already closed, so we can't get that error.
3381 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3382 g_error_free (error);
3384 g_object_unref (message);
3387 /* ---------------------------------------------------------------------------------------------------- */
3390 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3392 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3393 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3394 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3395 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3396 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3399 /* ---------------------------------------------------------------------------------------------------- */
3402 * g_dbus_connection_signal_subscribe:
3403 * @connection: a #GDBusConnection
3404 * @sender: (allow-none): sender name to match on (unique or well-known name)
3405 * or %NULL to listen from all senders
3406 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3407 * match on all interfaces
3408 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on
3410 * @object_path: (allow-none): object path to match on or %NULL to match on
3412 * @arg0: (allow-none): contents of first string argument to match on or %NULL
3413 * to match on all kinds of arguments
3414 * @flags: flags describing how to subscribe to the signal (currently unused)
3415 * @callback: callback to invoke when there is a signal matching the requested data
3416 * @user_data: user data to pass to @callback
3417 * @user_data_free_func: (allow-none): function to free @user_data with when
3418 * subscription is removed or %NULL
3420 * Subscribes to signals on @connection and invokes @callback with a whenever
3421 * the signal is received. Note that @callback will be invoked in the
3422 * [thread-default main context][g-main-context-push-thread-default]
3423 * of the thread you are calling this method from.
3425 * If @connection is not a message bus connection, @sender must be
3428 * If @sender is a well-known name note that @callback is invoked with
3429 * the unique name for the owner of @sender, not the well-known name
3430 * as one would expect. This is because the message bus rewrites the
3431 * name. As such, to avoid certain race conditions, users should be
3432 * tracking the name owner of the well-known name and use that when
3433 * processing the received signal.
3435 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3436 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3437 * interpreted as part of a namespace or path. The first argument
3438 * of a signal is matched against that part as specified by D-Bus.
3440 * Returns: a subscription identifier that can be used with g_dbus_connection_signal_unsubscribe()
3445 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3446 const gchar *sender,
3447 const gchar *interface_name,
3448 const gchar *member,
3449 const gchar *object_path,
3451 GDBusSignalFlags flags,
3452 GDBusSignalCallback callback,
3454 GDestroyNotify user_data_free_func)
3457 SignalData *signal_data;
3458 SignalSubscriber subscriber;
3459 GPtrArray *signal_data_array;
3460 const gchar *sender_unique_name;
3462 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3463 * an OOM condition. We might want to change that but that would involve making
3464 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3465 * handle that. And there's really no sensible way of handling this short of retrying
3466 * to add the match rule... and then there's the little thing that, hey, maybe there's
3467 * a reason the bus in an OOM condition.
3469 * Doable, but not really sure it's worth it...
3472 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3473 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3474 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3475 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3476 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3477 g_return_val_if_fail (callback != NULL, 0);
3478 g_return_val_if_fail (check_initialized (connection), 0);
3479 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3480 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3482 CONNECTION_LOCK (connection);
3484 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3485 * with a '-' character to prefix the rule (which will otherwise be
3488 * This allows us to hash the rule and do our lifecycle tracking in
3489 * the usual way, but the '-' prevents the match rule from ever
3490 * actually being send to the bus (either for add or remove).
3492 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3494 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3495 sender_unique_name = sender;
3497 sender_unique_name = "";
3499 subscriber.callback = callback;
3500 subscriber.user_data = user_data;
3501 subscriber.user_data_free_func = user_data_free_func;
3502 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3503 subscriber.context = g_main_context_ref_thread_default ();
3505 /* see if we've already have this rule */
3506 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3507 if (signal_data != NULL)
3509 g_array_append_val (signal_data->subscribers, subscriber);
3514 signal_data = g_new0 (SignalData, 1);
3515 signal_data->rule = rule;
3516 signal_data->sender = g_strdup (sender);
3517 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3518 signal_data->interface_name = g_strdup (interface_name);
3519 signal_data->member = g_strdup (member);
3520 signal_data->object_path = g_strdup (object_path);
3521 signal_data->arg0 = g_strdup (arg0);
3522 signal_data->flags = flags;
3523 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3524 g_array_append_val (signal_data->subscribers, subscriber);
3526 g_hash_table_insert (connection->map_rule_to_signal_data,
3530 /* Add the match rule to the bus...
3532 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3533 * always send such messages to us.
3535 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3537 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3538 add_match_rule (connection, signal_data->rule);
3541 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3542 signal_data->sender_unique_name);
3543 if (signal_data_array == NULL)
3545 signal_data_array = g_ptr_array_new ();
3546 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3547 g_strdup (signal_data->sender_unique_name),
3550 g_ptr_array_add (signal_data_array, signal_data);
3553 g_hash_table_insert (connection->map_id_to_signal_data,
3554 GUINT_TO_POINTER (subscriber.id),
3557 CONNECTION_UNLOCK (connection);
3559 return subscriber.id;
3562 /* ---------------------------------------------------------------------------------------------------- */
3564 /* called in any thread */
3565 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3567 unsubscribe_id_internal (GDBusConnection *connection,
3568 guint subscription_id,
3569 GArray *out_removed_subscribers)
3571 SignalData *signal_data;
3572 GPtrArray *signal_data_array;
3575 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3576 GUINT_TO_POINTER (subscription_id));
3577 if (signal_data == NULL)
3579 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3583 for (n = 0; n < signal_data->subscribers->len; n++)
3585 SignalSubscriber *subscriber;
3587 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3588 if (subscriber->id != subscription_id)
3591 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3592 GUINT_TO_POINTER (subscription_id)));
3593 g_array_append_val (out_removed_subscribers, *subscriber);
3594 g_array_remove_index (signal_data->subscribers, n);
3596 if (signal_data->subscribers->len == 0)
3598 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3600 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3601 signal_data->sender_unique_name);
3602 g_warn_if_fail (signal_data_array != NULL);
3603 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3605 if (signal_data_array->len == 0)
3607 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3608 signal_data->sender_unique_name));
3611 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3612 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3613 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3614 !g_dbus_connection_is_closed (connection) &&
3615 !connection->finalizing)
3617 /* The check for g_dbus_connection_is_closed() means that
3618 * sending the RemoveMatch message can't fail with
3619 * G_IO_ERROR_CLOSED, because we're holding the lock,
3620 * so on_worker_closed() can't happen between the check we just
3621 * did, and releasing the lock later.
3623 remove_match_rule (connection, signal_data->rule);
3626 signal_data_free (signal_data);
3632 g_assert_not_reached ();
3639 * g_dbus_connection_signal_unsubscribe:
3640 * @connection: a #GDBusConnection
3641 * @subscription_id: a subscription id obtained from
3642 * g_dbus_connection_signal_subscribe()
3644 * Unsubscribes from signals.
3649 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3650 guint subscription_id)
3652 GArray *subscribers;
3655 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3656 g_return_if_fail (check_initialized (connection));
3658 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3660 CONNECTION_LOCK (connection);
3661 unsubscribe_id_internal (connection,
3664 CONNECTION_UNLOCK (connection);
3667 g_assert (subscribers->len == 0 || subscribers->len == 1);
3669 /* call GDestroyNotify without lock held */
3670 for (n = 0; n < subscribers->len; n++)
3672 SignalSubscriber *subscriber;
3673 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3674 call_destroy_notify (subscriber->context,
3675 subscriber->user_data_free_func,
3676 subscriber->user_data);
3677 g_main_context_unref (subscriber->context);
3680 g_array_free (subscribers, TRUE);
3683 /* ---------------------------------------------------------------------------------------------------- */
3687 guint subscription_id;
3688 GDBusSignalCallback callback;
3690 GDBusMessage *message;
3691 GDBusConnection *connection;
3692 const gchar *sender;
3694 const gchar *interface;
3695 const gchar *member;
3698 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3702 emit_signal_instance_in_idle_cb (gpointer data)
3704 SignalInstance *signal_instance = data;
3705 GVariant *parameters;
3706 gboolean has_subscription;
3708 parameters = g_dbus_message_get_body (signal_instance->message);
3709 if (parameters == NULL)
3711 parameters = g_variant_new ("()");
3712 g_variant_ref_sink (parameters);
3716 g_variant_ref_sink (parameters);
3720 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3721 signal_instance->subscription_id,
3722 signal_instance->sender,
3723 signal_instance->path,
3724 signal_instance->interface,
3725 signal_instance->member,
3726 g_variant_print (parameters, TRUE));
3729 /* Careful here, don't do the callback if we no longer has the subscription */
3730 CONNECTION_LOCK (signal_instance->connection);
3731 has_subscription = FALSE;
3732 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3733 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3734 has_subscription = TRUE;
3735 CONNECTION_UNLOCK (signal_instance->connection);
3737 if (has_subscription)
3738 signal_instance->callback (signal_instance->connection,
3739 signal_instance->sender,
3740 signal_instance->path,
3741 signal_instance->interface,
3742 signal_instance->member,
3744 signal_instance->user_data);
3746 g_variant_unref (parameters);
3752 signal_instance_free (SignalInstance *signal_instance)
3754 g_object_unref (signal_instance->message);
3755 g_object_unref (signal_instance->connection);
3756 g_free (signal_instance);
3760 namespace_rule_matches (const gchar *namespace,
3766 len_namespace = strlen (namespace);
3767 len_name = strlen (name);
3769 if (len_name < len_namespace)
3772 if (memcmp (namespace, name, len_namespace) != 0)
3775 return len_namespace == len_name || name[len_namespace] == '.';
3779 path_rule_matches (const gchar *path_a,
3780 const gchar *path_b)
3784 len_a = strlen (path_a);
3785 len_b = strlen (path_b);
3787 if (len_a < len_b && path_a[len_a - 1] != '/')
3790 if (len_b < len_a && path_b[len_b - 1] != '/')
3793 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3796 /* called in GDBusWorker thread WITH lock held */
3798 schedule_callbacks (GDBusConnection *connection,
3799 GPtrArray *signal_data_array,
3800 GDBusMessage *message,
3801 const gchar *sender)
3804 const gchar *interface;
3805 const gchar *member;
3814 interface = g_dbus_message_get_interface (message);
3815 member = g_dbus_message_get_member (message);
3816 path = g_dbus_message_get_path (message);
3817 arg0 = g_dbus_message_get_arg0 (message);
3820 g_print ("In schedule_callbacks:\n"
3822 " interface = '%s'\n"
3833 /* TODO: if this is slow, then we can change signal_data_array into
3834 * map_object_path_to_signal_data_array or something.
3836 for (n = 0; n < signal_data_array->len; n++)
3838 SignalData *signal_data = signal_data_array->pdata[n];
3840 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3843 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3846 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3849 if (signal_data->arg0 != NULL)
3854 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3856 if (!namespace_rule_matches (signal_data->arg0, arg0))
3859 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3861 if (!path_rule_matches (signal_data->arg0, arg0))
3864 else if (!g_str_equal (signal_data->arg0, arg0))
3868 for (m = 0; m < signal_data->subscribers->len; m++)
3870 SignalSubscriber *subscriber;
3871 GSource *idle_source;
3872 SignalInstance *signal_instance;
3874 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3876 signal_instance = g_new0 (SignalInstance, 1);
3877 signal_instance->subscription_id = subscriber->id;
3878 signal_instance->callback = subscriber->callback;
3879 signal_instance->user_data = subscriber->user_data;
3880 signal_instance->message = g_object_ref (message);
3881 signal_instance->connection = g_object_ref (connection);
3882 signal_instance->sender = sender;
3883 signal_instance->path = path;
3884 signal_instance->interface = interface;
3885 signal_instance->member = member;
3887 idle_source = g_idle_source_new ();
3888 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3889 g_source_set_callback (idle_source,
3890 emit_signal_instance_in_idle_cb,
3892 (GDestroyNotify) signal_instance_free);
3893 g_source_attach (idle_source, subscriber->context);
3894 g_source_unref (idle_source);
3899 /* called in GDBusWorker thread with lock held */
3901 distribute_signals (GDBusConnection *connection,
3902 GDBusMessage *message)
3904 GPtrArray *signal_data_array;
3905 const gchar *sender;
3907 sender = g_dbus_message_get_sender (message);
3909 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3911 _g_dbus_debug_print_lock ();
3912 g_print ("========================================================================\n"
3913 "GDBus-debug:Signal:\n"
3914 " <<<< RECEIVED SIGNAL %s.%s\n"
3916 " sent by name %s\n",
3917 g_dbus_message_get_interface (message),
3918 g_dbus_message_get_member (message),
3919 g_dbus_message_get_path (message),
3920 sender != NULL ? sender : "(none)");
3921 _g_dbus_debug_print_unlock ();
3924 /* collect subscribers that match on sender */
3927 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3928 if (signal_data_array != NULL)
3929 schedule_callbacks (connection, signal_data_array, message, sender);
3932 /* collect subscribers not matching on sender */
3933 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3934 if (signal_data_array != NULL)
3935 schedule_callbacks (connection, signal_data_array, message, sender);
3938 /* ---------------------------------------------------------------------------------------------------- */
3940 /* only called from finalize(), removes all subscriptions */
3942 purge_all_signal_subscriptions (GDBusConnection *connection)
3944 GHashTableIter iter;
3947 GArray *subscribers;
3950 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3951 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3952 while (g_hash_table_iter_next (&iter, &key, NULL))
3954 guint subscription_id = GPOINTER_TO_UINT (key);
3955 g_array_append_val (ids, subscription_id);
3958 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3959 for (n = 0; n < ids->len; n++)
3961 guint subscription_id = g_array_index (ids, guint, n);
3962 unsubscribe_id_internal (connection,
3966 g_array_free (ids, TRUE);
3968 /* call GDestroyNotify without lock held */
3969 for (n = 0; n < subscribers->len; n++)
3971 SignalSubscriber *subscriber;
3972 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3973 call_destroy_notify (subscriber->context,
3974 subscriber->user_data_free_func,
3975 subscriber->user_data);
3976 g_main_context_unref (subscriber->context);
3979 g_array_free (subscribers, TRUE);
3982 /* ---------------------------------------------------------------------------------------------------- */
3984 static GDBusInterfaceVTable *
3985 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3987 /* Don't waste memory by copying padding - remember to update this
3988 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3990 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3994 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
3999 /* ---------------------------------------------------------------------------------------------------- */
4001 static GDBusSubtreeVTable *
4002 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4004 /* Don't waste memory by copying padding - remember to update this
4005 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4007 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4011 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4016 /* ---------------------------------------------------------------------------------------------------- */
4018 struct ExportedObject
4021 GDBusConnection *connection;
4023 /* maps gchar* -> ExportedInterface* */
4024 GHashTable *map_if_name_to_ei;
4027 /* only called with lock held */
4029 exported_object_free (ExportedObject *eo)
4031 g_free (eo->object_path);
4032 g_hash_table_unref (eo->map_if_name_to_ei);
4041 gchar *interface_name;
4042 GDBusInterfaceVTable *vtable;
4043 GDBusInterfaceInfo *interface_info;
4045 GMainContext *context;
4047 GDestroyNotify user_data_free_func;
4048 } ExportedInterface;
4050 /* called with lock held */
4052 exported_interface_free (ExportedInterface *ei)
4054 g_dbus_interface_info_cache_release (ei->interface_info);
4055 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4057 call_destroy_notify (ei->context,
4058 ei->user_data_free_func,
4061 g_main_context_unref (ei->context);
4063 g_free (ei->interface_name);
4064 _g_dbus_interface_vtable_free (ei->vtable);
4068 /* ---------------------------------------------------------------------------------------------------- */
4070 /* Convenience function to check if @registration_id (if not zero) or
4071 * @subtree_registration_id (if not zero) has been unregistered. If
4072 * so, returns %TRUE.
4074 * May be called by any thread. Caller must *not* hold lock.
4077 has_object_been_unregistered (GDBusConnection *connection,
4078 guint registration_id,
4079 guint subtree_registration_id)
4083 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4087 CONNECTION_LOCK (connection);
4088 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4089 GUINT_TO_POINTER (registration_id)) == NULL)
4093 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4094 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4098 CONNECTION_UNLOCK (connection);
4103 /* ---------------------------------------------------------------------------------------------------- */
4107 GDBusConnection *connection;
4108 GDBusMessage *message;
4110 const gchar *property_name;
4111 const GDBusInterfaceVTable *vtable;
4112 GDBusInterfaceInfo *interface_info;
4113 const GDBusPropertyInfo *property_info;
4114 guint registration_id;
4115 guint subtree_registration_id;
4119 property_data_free (PropertyData *data)
4121 g_object_unref (data->connection);
4122 g_object_unref (data->message);
4126 /* called in thread where object was registered - no locks held */
4128 invoke_get_property_in_idle_cb (gpointer _data)
4130 PropertyData *data = _data;
4133 GDBusMessage *reply;
4135 if (has_object_been_unregistered (data->connection,
4136 data->registration_id,
4137 data->subtree_registration_id))
4139 reply = g_dbus_message_new_method_error (data->message,
4140 "org.freedesktop.DBus.Error.UnknownMethod",
4141 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4142 g_dbus_message_get_path (data->message));
4143 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4144 g_object_unref (reply);
4149 value = data->vtable->get_property (data->connection,
4150 g_dbus_message_get_sender (data->message),
4151 g_dbus_message_get_path (data->message),
4152 data->interface_info->name,
4153 data->property_name,
4160 g_assert_no_error (error);
4162 g_variant_take_ref (value);
4163 reply = g_dbus_message_new_method_reply (data->message);
4164 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4165 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4166 g_variant_unref (value);
4167 g_object_unref (reply);
4171 gchar *dbus_error_name;
4172 g_assert (error != NULL);
4173 dbus_error_name = g_dbus_error_encode_gerror (error);
4174 reply = g_dbus_message_new_method_error_literal (data->message,
4177 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4178 g_free (dbus_error_name);
4179 g_error_free (error);
4180 g_object_unref (reply);
4187 /* called in thread where object was registered - no locks held */
4189 invoke_set_property_in_idle_cb (gpointer _data)
4191 PropertyData *data = _data;
4193 GDBusMessage *reply;
4199 g_variant_get (g_dbus_message_get_body (data->message),
4205 if (!data->vtable->set_property (data->connection,
4206 g_dbus_message_get_sender (data->message),
4207 g_dbus_message_get_path (data->message),
4208 data->interface_info->name,
4209 data->property_name,
4214 gchar *dbus_error_name;
4215 g_assert (error != NULL);
4216 dbus_error_name = g_dbus_error_encode_gerror (error);
4217 reply = g_dbus_message_new_method_error_literal (data->message,
4220 g_free (dbus_error_name);
4221 g_error_free (error);
4225 reply = g_dbus_message_new_method_reply (data->message);
4228 g_assert (reply != NULL);
4229 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4230 g_object_unref (reply);
4231 g_variant_unref (value);
4236 /* called in any thread with connection's lock held */
4238 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4239 GDBusMessage *message,
4240 guint registration_id,
4241 guint subtree_registration_id,
4243 GDBusInterfaceInfo *interface_info,
4244 const GDBusInterfaceVTable *vtable,
4245 GMainContext *main_context,
4249 const char *interface_name;
4250 const char *property_name;
4251 const GDBusPropertyInfo *property_info;
4252 GSource *idle_source;
4253 PropertyData *property_data;
4254 GDBusMessage *reply;
4259 g_variant_get (g_dbus_message_get_body (message),
4264 g_variant_get (g_dbus_message_get_body (message),
4273 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4275 property_info = NULL;
4277 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4278 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4279 if (property_info == NULL)
4281 reply = g_dbus_message_new_method_error (message,
4282 "org.freedesktop.DBus.Error.InvalidArgs",
4283 _("No such property '%s'"),
4285 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4286 g_object_unref (reply);
4291 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4293 reply = g_dbus_message_new_method_error (message,
4294 "org.freedesktop.DBus.Error.InvalidArgs",
4295 _("Property '%s' is not readable"),
4297 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4298 g_object_unref (reply);
4302 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4304 reply = g_dbus_message_new_method_error (message,
4305 "org.freedesktop.DBus.Error.InvalidArgs",
4306 _("Property '%s' is not writable"),
4308 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4309 g_object_unref (reply);
4318 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4319 * of the given value is wrong
4321 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4322 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4324 reply = g_dbus_message_new_method_error (message,
4325 "org.freedesktop.DBus.Error.InvalidArgs",
4326 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4327 property_name, property_info->signature,
4328 g_variant_get_type_string (value));
4329 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4330 g_variant_unref (value);
4331 g_object_unref (reply);
4336 g_variant_unref (value);
4339 /* If the vtable pointer for get_property() resp. set_property() is
4340 * NULL then dispatch the call via the method_call() handler.
4344 if (vtable->get_property == NULL)
4346 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4347 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4348 vtable, main_context, user_data);
4355 if (vtable->set_property == NULL)
4357 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4358 interface_info, NULL, property_info, g_dbus_message_get_body (message),
4359 vtable, main_context, user_data);
4365 /* ok, got the property info - call user code in an idle handler */
4366 property_data = g_new0 (PropertyData, 1);
4367 property_data->connection = g_object_ref (connection);
4368 property_data->message = g_object_ref (message);
4369 property_data->user_data = user_data;
4370 property_data->property_name = property_name;
4371 property_data->vtable = vtable;
4372 property_data->interface_info = interface_info;
4373 property_data->property_info = property_info;
4374 property_data->registration_id = registration_id;
4375 property_data->subtree_registration_id = subtree_registration_id;
4377 idle_source = g_idle_source_new ();
4378 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4379 g_source_set_callback (idle_source,
4380 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4382 (GDestroyNotify) property_data_free);
4383 g_source_attach (idle_source, main_context);
4384 g_source_unref (idle_source);
4392 /* called in GDBusWorker thread with connection's lock held */
4394 handle_getset_property (GDBusConnection *connection,
4396 GDBusMessage *message,
4399 ExportedInterface *ei;
4401 const char *interface_name;
4402 const char *property_name;
4407 g_variant_get (g_dbus_message_get_body (message),
4412 g_variant_get (g_dbus_message_get_body (message),
4418 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4419 * no such interface registered
4421 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4424 GDBusMessage *reply;
4425 reply = g_dbus_message_new_method_error (message,
4426 "org.freedesktop.DBus.Error.InvalidArgs",
4427 _("No such interface '%s'"),
4429 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4430 g_object_unref (reply);
4435 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4448 /* ---------------------------------------------------------------------------------------------------- */
4452 GDBusConnection *connection;
4453 GDBusMessage *message;
4455 const GDBusInterfaceVTable *vtable;
4456 GDBusInterfaceInfo *interface_info;
4457 guint registration_id;
4458 guint subtree_registration_id;
4459 } PropertyGetAllData;
4462 property_get_all_data_free (PropertyData *data)
4464 g_object_unref (data->connection);
4465 g_object_unref (data->message);
4469 /* called in thread where object was registered - no locks held */
4471 invoke_get_all_properties_in_idle_cb (gpointer _data)
4473 PropertyGetAllData *data = _data;
4474 GVariantBuilder builder;
4475 GDBusMessage *reply;
4478 if (has_object_been_unregistered (data->connection,
4479 data->registration_id,
4480 data->subtree_registration_id))
4482 reply = g_dbus_message_new_method_error (data->message,
4483 "org.freedesktop.DBus.Error.UnknownMethod",
4484 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4485 g_dbus_message_get_path (data->message));
4486 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4487 g_object_unref (reply);
4491 /* TODO: Right now we never fail this call - we just omit values if
4492 * a get_property() call is failing.
4494 * We could fail the whole call if just a single get_property() call
4495 * returns an error. We need clarification in the D-Bus spec about this.
4497 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4498 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4499 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4501 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4504 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4507 value = data->vtable->get_property (data->connection,
4508 g_dbus_message_get_sender (data->message),
4509 g_dbus_message_get_path (data->message),
4510 data->interface_info->name,
4511 property_info->name,
4518 g_variant_take_ref (value);
4519 g_variant_builder_add (&builder,
4521 property_info->name,
4523 g_variant_unref (value);
4525 g_variant_builder_close (&builder);
4527 reply = g_dbus_message_new_method_reply (data->message);
4528 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4529 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4530 g_object_unref (reply);
4537 interface_has_readable_properties (GDBusInterfaceInfo *interface_info)
4541 if (!interface_info->properties)
4544 for (i = 0; interface_info->properties[i]; i++)
4545 if (interface_info->properties[i]->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
4551 /* called in any thread with connection's lock held */
4553 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4554 GDBusMessage *message,
4555 guint registration_id,
4556 guint subtree_registration_id,
4557 GDBusInterfaceInfo *interface_info,
4558 const GDBusInterfaceVTable *vtable,
4559 GMainContext *main_context,
4563 GSource *idle_source;
4564 PropertyGetAllData *property_get_all_data;
4571 /* If the vtable pointer for get_property() is NULL but we have a
4572 * non-zero number of readable properties, then dispatch the call via
4573 * the method_call() handler.
4575 if (vtable->get_property == NULL && interface_has_readable_properties (interface_info))
4577 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4578 interface_info, NULL, NULL, g_dbus_message_get_body (message),
4579 vtable, main_context, user_data);
4584 /* ok, got the property info - call user in an idle handler */
4585 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4586 property_get_all_data->connection = g_object_ref (connection);
4587 property_get_all_data->message = g_object_ref (message);
4588 property_get_all_data->user_data = user_data;
4589 property_get_all_data->vtable = vtable;
4590 property_get_all_data->interface_info = interface_info;
4591 property_get_all_data->registration_id = registration_id;
4592 property_get_all_data->subtree_registration_id = subtree_registration_id;
4594 idle_source = g_idle_source_new ();
4595 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4596 g_source_set_callback (idle_source,
4597 invoke_get_all_properties_in_idle_cb,
4598 property_get_all_data,
4599 (GDestroyNotify) property_get_all_data_free);
4600 g_source_attach (idle_source, main_context);
4601 g_source_unref (idle_source);
4609 /* called in GDBusWorker thread with connection's lock held */
4611 handle_get_all_properties (GDBusConnection *connection,
4613 GDBusMessage *message)
4615 ExportedInterface *ei;
4617 const char *interface_name;
4621 g_variant_get (g_dbus_message_get_body (message),
4625 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4626 * no such interface registered
4628 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4631 GDBusMessage *reply;
4632 reply = g_dbus_message_new_method_error (message,
4633 "org.freedesktop.DBus.Error.InvalidArgs",
4634 _("No such interface"),
4636 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4637 g_object_unref (reply);
4642 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4654 /* ---------------------------------------------------------------------------------------------------- */
4656 static const gchar introspect_header[] =
4657 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4658 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4659 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4662 static const gchar introspect_tail[] =
4665 static const gchar introspect_properties_interface[] =
4666 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4667 " <method name=\"Get\">\n"
4668 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4669 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4670 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4672 " <method name=\"GetAll\">\n"
4673 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4674 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4676 " <method name=\"Set\">\n"
4677 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4678 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4679 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4681 " <signal name=\"PropertiesChanged\">\n"
4682 " <arg type=\"s\" name=\"interface_name\"/>\n"
4683 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4684 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4688 static const gchar introspect_introspectable_interface[] =
4689 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4690 " <method name=\"Introspect\">\n"
4691 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4694 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4695 " <method name=\"Ping\"/>\n"
4696 " <method name=\"GetMachineId\">\n"
4697 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4702 introspect_append_header (GString *s)
4704 g_string_append (s, introspect_header);
4708 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4710 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4716 begin = object_path + path_len;
4717 end = strchr (begin, '/');
4719 s = g_strndup (begin, end - begin);
4721 s = g_strdup (begin);
4723 if (g_hash_table_lookup (set, s) == NULL)
4724 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4730 /* TODO: we want a nicer public interface for this */
4731 /* called in any thread with connection's lock held */
4733 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4738 GHashTableIter hash_iter;
4739 const gchar *object_path;
4745 CONNECTION_ENSURE_LOCK (connection);
4747 path_len = strlen (path);
4751 set = g_hash_table_new (g_str_hash, g_str_equal);
4753 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4754 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4755 maybe_add_path (path, path_len, object_path, set);
4757 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4758 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4759 maybe_add_path (path, path_len, object_path, set);
4761 p = g_ptr_array_new ();
4762 keys = g_hash_table_get_keys (set);
4763 for (l = keys; l != NULL; l = l->next)
4764 g_ptr_array_add (p, l->data);
4765 g_hash_table_unref (set);
4768 g_ptr_array_add (p, NULL);
4769 ret = (gchar **) g_ptr_array_free (p, FALSE);
4773 /* called in any thread with connection's lock not held */
4775 g_dbus_connection_list_registered (GDBusConnection *connection,
4779 CONNECTION_LOCK (connection);
4780 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4781 CONNECTION_UNLOCK (connection);
4785 /* called in GDBusWorker thread with connection's lock held */
4787 handle_introspect (GDBusConnection *connection,
4789 GDBusMessage *message)
4793 GDBusMessage *reply;
4794 GHashTableIter hash_iter;
4795 ExportedInterface *ei;
4798 /* first the header with the standard interfaces */
4799 s = g_string_sized_new (sizeof (introspect_header) +
4800 sizeof (introspect_properties_interface) +
4801 sizeof (introspect_introspectable_interface) +
4802 sizeof (introspect_tail));
4803 introspect_append_header (s);
4804 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4805 "org.freedesktop.DBus.Properties"))
4806 g_string_append (s, introspect_properties_interface);
4808 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4809 "org.freedesktop.DBus.Introspectable"))
4810 g_string_append (s, introspect_introspectable_interface);
4812 /* then include the registered interfaces */
4813 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4814 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4815 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4817 /* finally include nodes registered below us */
4818 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4819 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4820 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4821 g_strfreev (registered);
4822 g_string_append (s, introspect_tail);
4824 reply = g_dbus_message_new_method_reply (message);
4825 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4826 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4827 g_object_unref (reply);
4828 g_string_free (s, TRUE);
4833 /* called in thread where object was registered - no locks held */
4835 call_in_idle_cb (gpointer user_data)
4837 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4838 GDBusInterfaceVTable *vtable;
4839 guint registration_id;
4840 guint subtree_registration_id;
4842 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4843 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4845 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4847 subtree_registration_id))
4849 GDBusMessage *reply;
4850 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4851 "org.freedesktop.DBus.Error.UnknownMethod",
4852 _("No such interface '%s' on object at path %s"),
4853 g_dbus_method_invocation_get_interface_name (invocation),
4854 g_dbus_method_invocation_get_object_path (invocation));
4855 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4856 g_object_unref (reply);
4860 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4861 g_assert (vtable != NULL && vtable->method_call != NULL);
4863 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4864 g_dbus_method_invocation_get_sender (invocation),
4865 g_dbus_method_invocation_get_object_path (invocation),
4866 g_dbus_method_invocation_get_interface_name (invocation),
4867 g_dbus_method_invocation_get_method_name (invocation),
4868 g_dbus_method_invocation_get_parameters (invocation),
4869 g_object_ref (invocation),
4870 g_dbus_method_invocation_get_user_data (invocation));
4876 /* called in GDBusWorker thread with connection's lock held */
4878 schedule_method_call (GDBusConnection *connection,
4879 GDBusMessage *message,
4880 guint registration_id,
4881 guint subtree_registration_id,
4882 const GDBusInterfaceInfo *interface_info,
4883 const GDBusMethodInfo *method_info,
4884 const GDBusPropertyInfo *property_info,
4885 GVariant *parameters,
4886 const GDBusInterfaceVTable *vtable,
4887 GMainContext *main_context,
4890 GDBusMethodInvocation *invocation;
4891 GSource *idle_source;
4893 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4894 g_dbus_message_get_path (message),
4895 g_dbus_message_get_interface (message),
4896 g_dbus_message_get_member (message),
4904 /* TODO: would be nicer with a real MethodData like we already
4905 * have PropertyData and PropertyGetAllData... */
4906 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4907 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4908 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4910 idle_source = g_idle_source_new ();
4911 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4912 g_source_set_callback (idle_source,
4916 g_source_attach (idle_source, main_context);
4917 g_source_unref (idle_source);
4920 /* called in GDBusWorker thread with connection's lock held */
4922 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4923 GDBusMessage *message,
4924 guint registration_id,
4925 guint subtree_registration_id,
4926 GDBusInterfaceInfo *interface_info,
4927 const GDBusInterfaceVTable *vtable,
4928 GMainContext *main_context,
4931 GDBusMethodInfo *method_info;
4932 GDBusMessage *reply;
4933 GVariant *parameters;
4935 GVariantType *in_type;
4939 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4940 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4942 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4943 * error to the caller
4945 if (method_info == NULL)
4947 reply = g_dbus_message_new_method_error (message,
4948 "org.freedesktop.DBus.Error.UnknownMethod",
4949 _("No such method '%s'"),
4950 g_dbus_message_get_member (message));
4951 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4952 g_object_unref (reply);
4957 parameters = g_dbus_message_get_body (message);
4958 if (parameters == NULL)
4960 parameters = g_variant_new ("()");
4961 g_variant_ref_sink (parameters);
4965 g_variant_ref (parameters);
4968 /* Check that the incoming args are of the right type - if they are not, return
4969 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4971 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4972 if (!g_variant_is_of_type (parameters, in_type))
4976 type_string = g_variant_type_dup_string (in_type);
4978 reply = g_dbus_message_new_method_error (message,
4979 "org.freedesktop.DBus.Error.InvalidArgs",
4980 _("Type of message, '%s', does not match expected type '%s'"),
4981 g_variant_get_type_string (parameters),
4983 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4984 g_variant_type_free (in_type);
4985 g_variant_unref (parameters);
4986 g_object_unref (reply);
4987 g_free (type_string);
4991 g_variant_type_free (in_type);
4993 /* schedule the call in idle */
4994 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4995 interface_info, method_info, NULL, parameters,
4996 vtable, main_context, user_data);
4997 g_variant_unref (parameters);
5004 /* ---------------------------------------------------------------------------------------------------- */
5006 /* called in GDBusWorker thread with connection's lock held */
5008 obj_message_func (GDBusConnection *connection,
5010 GDBusMessage *message)
5012 const gchar *interface_name;
5013 const gchar *member;
5014 const gchar *signature;
5019 interface_name = g_dbus_message_get_interface (message);
5020 member = g_dbus_message_get_member (message);
5021 signature = g_dbus_message_get_signature (message);
5023 /* see if we have an interface for handling this call */
5024 if (interface_name != NULL)
5026 ExportedInterface *ei;
5027 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
5030 /* we do - invoke the handler in idle in the right thread */
5032 /* handle no vtable or handler being present */
5033 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
5036 handled = validate_and_maybe_schedule_method_call (connection,
5048 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5049 g_strcmp0 (member, "Introspect") == 0 &&
5050 g_strcmp0 (signature, "") == 0)
5052 handled = handle_introspect (connection, eo, message);
5055 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5056 g_strcmp0 (member, "Get") == 0 &&
5057 g_strcmp0 (signature, "ss") == 0)
5059 handled = handle_getset_property (connection, eo, message, TRUE);
5062 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5063 g_strcmp0 (member, "Set") == 0 &&
5064 g_strcmp0 (signature, "ssv") == 0)
5066 handled = handle_getset_property (connection, eo, message, FALSE);
5069 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5070 g_strcmp0 (member, "GetAll") == 0 &&
5071 g_strcmp0 (signature, "s") == 0)
5073 handled = handle_get_all_properties (connection, eo, message);
5082 * g_dbus_connection_register_object:
5083 * @connection: a #GDBusConnection
5084 * @object_path: the object path to register at
5085 * @interface_info: introspection data for the interface
5086 * @vtable: (allow-none): a #GDBusInterfaceVTable to call into or %NULL
5087 * @user_data: (allow-none): data to pass to functions in @vtable
5088 * @user_data_free_func: function to call when the object path is unregistered
5089 * @error: return location for error or %NULL
5091 * Registers callbacks for exported objects at @object_path with the
5092 * D-Bus interface that is described in @interface_info.
5094 * Calls to functions in @vtable (and @user_data_free_func) will happen
5096 * [thread-default main context][g-main-context-push-thread-default]
5097 * of the thread you are calling this method from.
5099 * Note that all #GVariant values passed to functions in @vtable will match
5100 * the signature given in @interface_info - if a remote caller passes
5101 * incorrect values, the `org.freedesktop.DBus.Error.InvalidArgs`
5102 * is returned to the remote caller.
5104 * Additionally, if the remote caller attempts to invoke methods or
5105 * access properties not mentioned in @interface_info the
5106 * `org.freedesktop.DBus.Error.UnknownMethod` resp.
5107 * `org.freedesktop.DBus.Error.InvalidArgs` errors
5108 * are returned to the caller.
5110 * It is considered a programming error if the
5111 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5112 * #GVariant of incorrect type.
5114 * If an existing callback is already registered at @object_path and
5115 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5117 * GDBus automatically implements the standard D-Bus interfaces
5118 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5119 * and org.freedesktop.Peer, so you don't have to implement those for the
5120 * objects you export. You can implement org.freedesktop.DBus.Properties
5121 * yourself, e.g. to handle getting and setting of properties asynchronously.
5123 * Note that the reference count on @interface_info will be
5124 * incremented by 1 (unless allocated statically, e.g. if the
5125 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5126 * as the object is exported. Also note that @vtable will be copied.
5128 * See this [server][gdbus-server] for an example of how to use this method.
5130 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5131 * that can be used with g_dbus_connection_unregister_object()
5136 g_dbus_connection_register_object (GDBusConnection *connection,
5137 const gchar *object_path,
5138 GDBusInterfaceInfo *interface_info,
5139 const GDBusInterfaceVTable *vtable,
5141 GDestroyNotify user_data_free_func,
5145 ExportedInterface *ei;
5148 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5149 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5150 g_return_val_if_fail (interface_info != NULL, 0);
5151 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5152 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5153 g_return_val_if_fail (check_initialized (connection), 0);
5157 CONNECTION_LOCK (connection);
5159 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5162 eo = g_new0 (ExportedObject, 1);
5163 eo->object_path = g_strdup (object_path);
5164 eo->connection = connection;
5165 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5168 (GDestroyNotify) exported_interface_free);
5169 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5172 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5178 _("An object is already exported for the interface %s at %s"),
5179 interface_info->name,
5184 ei = g_new0 (ExportedInterface, 1);
5185 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5187 ei->user_data = user_data;
5188 ei->user_data_free_func = user_data_free_func;
5189 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5190 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5191 g_dbus_interface_info_cache_build (ei->interface_info);
5192 ei->interface_name = g_strdup (interface_info->name);
5193 ei->context = g_main_context_ref_thread_default ();
5195 g_hash_table_insert (eo->map_if_name_to_ei,
5196 (gpointer) ei->interface_name,
5198 g_hash_table_insert (connection->map_id_to_ei,
5199 GUINT_TO_POINTER (ei->id),
5205 CONNECTION_UNLOCK (connection);
5211 * g_dbus_connection_unregister_object:
5212 * @connection: a #GDBusConnection
5213 * @registration_id: a registration id obtained from
5214 * g_dbus_connection_register_object()
5216 * Unregisters an object.
5218 * Returns: %TRUE if the object was unregistered, %FALSE otherwise
5223 g_dbus_connection_unregister_object (GDBusConnection *connection,
5224 guint registration_id)
5226 ExportedInterface *ei;
5230 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5231 g_return_val_if_fail (check_initialized (connection), FALSE);
5235 CONNECTION_LOCK (connection);
5237 ei = g_hash_table_lookup (connection->map_id_to_ei,
5238 GUINT_TO_POINTER (registration_id));
5244 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5245 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5246 /* unregister object path if we have no more exported interfaces */
5247 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5248 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5254 CONNECTION_UNLOCK (connection);
5259 /* ---------------------------------------------------------------------------------------------------- */
5262 * g_dbus_connection_emit_signal:
5263 * @connection: a #GDBusConnection
5264 * @destination_bus_name: (allow-none): the unique bus name for the destination
5265 * for the signal or %NULL to emit to all listeners
5266 * @object_path: path of remote object
5267 * @interface_name: D-Bus interface to emit a signal on
5268 * @signal_name: the name of the signal to emit
5269 * @parameters: (allow-none): a #GVariant tuple with parameters for the signal
5270 * or %NULL if not passing parameters
5271 * @error: Return location for error or %NULL
5275 * If the parameters GVariant is floating, it is consumed.
5277 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5279 * Returns: %TRUE unless @error is set
5284 g_dbus_connection_emit_signal (GDBusConnection *connection,
5285 const gchar *destination_bus_name,
5286 const gchar *object_path,
5287 const gchar *interface_name,
5288 const gchar *signal_name,
5289 GVariant *parameters,
5292 GDBusMessage *message;
5298 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5299 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5300 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5301 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5302 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5303 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5304 g_return_val_if_fail (check_initialized (connection), FALSE);
5306 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5308 _g_dbus_debug_print_lock ();
5309 g_print ("========================================================================\n"
5310 "GDBus-debug:Emission:\n"
5311 " >>>> SIGNAL EMISSION %s.%s()\n"
5313 " destination %s\n",
5314 interface_name, signal_name,
5316 destination_bus_name != NULL ? destination_bus_name : "(none)");
5317 _g_dbus_debug_print_unlock ();
5320 message = g_dbus_message_new_signal (object_path,
5324 if (destination_bus_name != NULL)
5325 g_dbus_message_set_header (message,
5326 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5327 g_variant_new_string (destination_bus_name));
5329 if (parameters != NULL)
5330 g_dbus_message_set_body (message, parameters);
5332 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5333 g_object_unref (message);
5339 add_call_flags (GDBusMessage *message,
5340 GDBusCallFlags flags)
5342 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5343 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5347 decode_method_reply (GDBusMessage *reply,
5348 const gchar *method_name,
5349 const GVariantType *reply_type,
5350 GUnixFDList **out_fd_list,
5356 switch (g_dbus_message_get_message_type (reply))
5358 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5359 result = g_dbus_message_get_body (reply);
5362 result = g_variant_new ("()");
5363 g_variant_ref_sink (result);
5367 g_variant_ref (result);
5370 if (!g_variant_is_of_type (result, reply_type))
5372 gchar *type_string = g_variant_type_dup_string (reply_type);
5376 G_IO_ERROR_INVALID_ARGUMENT,
5377 _("Method '%s' returned type '%s', but expected '%s'"),
5378 method_name, g_variant_get_type_string (result), type_string);
5380 g_variant_unref (result);
5381 g_free (type_string);
5388 if (out_fd_list != NULL)
5390 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5391 if (*out_fd_list != NULL)
5392 g_object_ref (*out_fd_list);
5398 case G_DBUS_MESSAGE_TYPE_ERROR:
5399 g_dbus_message_to_gerror (reply, error);
5403 g_assert_not_reached ();
5413 GSimpleAsyncResult *simple;
5414 GVariantType *reply_type;
5415 gchar *method_name; /* for error message */
5419 GUnixFDList *fd_list;
5423 call_state_free (CallState *state)
5425 g_variant_type_free (state->reply_type);
5426 g_free (state->method_name);
5428 if (state->value != NULL)
5429 g_variant_unref (state->value);
5430 if (state->fd_list != NULL)
5431 g_object_unref (state->fd_list);
5432 g_slice_free (CallState, state);
5435 /* called in any thread, with the connection's lock not held */
5437 g_dbus_connection_call_done (GObject *source,
5438 GAsyncResult *result,
5441 GSimpleAsyncResult *simple;
5442 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5443 CallState *state = user_data;
5445 GDBusMessage *reply;
5448 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5452 if (G_UNLIKELY (_g_dbus_debug_call ()))
5454 _g_dbus_debug_print_lock ();
5455 g_print ("========================================================================\n"
5456 "GDBus-debug:Call:\n"
5457 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5463 g_print ("SUCCESS\n");
5467 g_print ("FAILED: %s\n",
5470 _g_dbus_debug_print_unlock ();
5474 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5476 simple = state->simple; /* why? because state is freed before we unref simple.. */
5479 g_simple_async_result_take_error (state->simple, error);
5480 g_simple_async_result_complete (state->simple);
5481 call_state_free (state);
5485 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5486 g_simple_async_result_complete (state->simple);
5488 g_clear_object (&reply);
5489 g_object_unref (simple);
5492 /* called in any thread, with the connection's lock not held */
5494 g_dbus_connection_call_internal (GDBusConnection *connection,
5495 const gchar *bus_name,
5496 const gchar *object_path,
5497 const gchar *interface_name,
5498 const gchar *method_name,
5499 GVariant *parameters,
5500 const GVariantType *reply_type,
5501 GDBusCallFlags flags,
5503 GUnixFDList *fd_list,
5504 GCancellable *cancellable,
5505 GAsyncReadyCallback callback,
5508 GDBusMessage *message;
5511 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5512 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5513 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5514 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5515 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5516 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5517 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5518 g_return_if_fail (check_initialized (connection));
5520 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5522 g_return_if_fail (fd_list == NULL);
5525 message = g_dbus_message_new_method_call (bus_name,
5529 add_call_flags (message, flags);
5530 if (parameters != NULL)
5531 g_dbus_message_set_body (message, parameters);
5534 if (fd_list != NULL)
5535 g_dbus_message_set_unix_fd_list (message, fd_list);
5538 /* If the user has no callback then we can just send the message with
5539 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5540 * the logic for processing the reply. If the service sends the reply
5541 * anyway then it will just be ignored.
5543 if (callback != NULL)
5547 state = g_slice_new0 (CallState);
5548 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5549 callback, user_data,
5550 g_dbus_connection_call_internal);
5551 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5552 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5554 if (reply_type == NULL)
5555 reply_type = G_VARIANT_TYPE_ANY;
5557 state->reply_type = g_variant_type_copy (reply_type);
5559 g_dbus_connection_send_message_with_reply (connection,
5561 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5565 g_dbus_connection_call_done,
5567 serial = state->serial;
5571 GDBusMessageFlags flags;
5573 flags = g_dbus_message_get_flags (message);
5574 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5575 g_dbus_message_set_flags (message, flags);
5577 g_dbus_connection_send_message (connection,
5579 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5583 if (G_UNLIKELY (_g_dbus_debug_call ()))
5585 _g_dbus_debug_print_lock ();
5586 g_print ("========================================================================\n"
5587 "GDBus-debug:Call:\n"
5588 " >>>> ASYNC %s.%s()\n"
5590 " owned by name %s (serial %d)\n",
5594 bus_name != NULL ? bus_name : "(none)",
5596 _g_dbus_debug_print_unlock ();
5599 if (message != NULL)
5600 g_object_unref (message);
5603 /* called in any thread, with the connection's lock not held */
5605 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5606 GUnixFDList **out_fd_list,
5610 GSimpleAsyncResult *simple;
5613 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5614 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5615 g_dbus_connection_call_internal), NULL);
5616 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5618 simple = G_SIMPLE_ASYNC_RESULT (res);
5620 if (g_simple_async_result_propagate_error (simple, error))
5623 state = g_simple_async_result_get_op_res_gpointer (simple);
5624 if (out_fd_list != NULL)
5625 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5626 return g_variant_ref (state->value);
5629 /* called in any user thread, with the connection's lock not held */
5631 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5632 const gchar *bus_name,
5633 const gchar *object_path,
5634 const gchar *interface_name,
5635 const gchar *method_name,
5636 GVariant *parameters,
5637 const GVariantType *reply_type,
5638 GDBusCallFlags flags,
5640 GUnixFDList *fd_list,
5641 GUnixFDList **out_fd_list,
5642 GCancellable *cancellable,
5645 GDBusMessage *message;
5646 GDBusMessage *reply;
5648 GError *local_error;
5649 GDBusSendMessageFlags send_flags;
5655 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5656 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5657 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5658 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5659 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5660 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5661 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5663 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5665 g_return_val_if_fail (fd_list == NULL, NULL);
5667 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5669 if (!(flags & CALL_FLAGS_INITIALIZING))
5670 g_return_val_if_fail (check_initialized (connection), FALSE);
5672 if (reply_type == NULL)
5673 reply_type = G_VARIANT_TYPE_ANY;
5675 message = g_dbus_message_new_method_call (bus_name,
5679 add_call_flags (message, flags);
5680 if (parameters != NULL)
5681 g_dbus_message_set_body (message, parameters);
5684 if (fd_list != NULL)
5685 g_dbus_message_set_unix_fd_list (message, fd_list);
5688 if (G_UNLIKELY (_g_dbus_debug_call ()))
5690 _g_dbus_debug_print_lock ();
5691 g_print ("========================================================================\n"
5692 "GDBus-debug:Call:\n"
5693 " >>>> SYNC %s.%s()\n"
5695 " owned by name %s\n",
5699 bus_name != NULL ? bus_name : "(none)");
5700 _g_dbus_debug_print_unlock ();
5705 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5707 /* translate from one flavour of flags to another... */
5708 if (flags & CALL_FLAGS_INITIALIZING)
5709 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5711 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5715 NULL, /* volatile guint32 *out_serial */
5719 if (G_UNLIKELY (_g_dbus_debug_call ()))
5721 _g_dbus_debug_print_lock ();
5722 g_print ("========================================================================\n"
5723 "GDBus-debug:Call:\n"
5724 " <<<< SYNC COMPLETE %s.%s()\n"
5730 g_print ("SUCCESS\n");
5734 g_print ("FAILED: %s\n",
5735 local_error->message);
5737 _g_dbus_debug_print_unlock ();
5743 *error = local_error;
5745 g_error_free (local_error);
5749 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5752 if (message != NULL)
5753 g_object_unref (message);
5755 g_object_unref (reply);
5760 /* ---------------------------------------------------------------------------------------------------- */
5763 * g_dbus_connection_call:
5764 * @connection: a #GDBusConnection
5765 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5766 * @connection is not a message bus connection
5767 * @object_path: path of remote object
5768 * @interface_name: D-Bus interface to invoke method on
5769 * @method_name: the name of the method to invoke
5770 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5771 * or %NULL if not passing parameters
5772 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5773 * @flags: flags from the #GDBusCallFlags enumeration
5774 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5775 * timeout or %G_MAXINT for no timeout
5776 * @cancellable: (allow-none): a #GCancellable or %NULL
5777 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request
5778 * is satisfied or %NULL if you don't care about the result of the
5780 * @user_data: the data to pass to @callback
5782 * Asynchronously invokes the @method_name method on the
5783 * @interface_name D-Bus interface on the remote object at
5784 * @object_path owned by @bus_name.
5786 * If @connection is closed then the operation will fail with
5787 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5788 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5789 * not compatible with the D-Bus protocol, the operation fails with
5790 * %G_IO_ERROR_INVALID_ARGUMENT.
5792 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5793 * error will be raised if it does not match. Said another way, if you give a @reply_type
5794 * then any non-%NULL return value will be of this type.
5796 * If the @parameters #GVariant is floating, it is consumed. This allows
5797 * convenient 'inline' use of g_variant_new(), e.g.:
5798 * |[<!-- language="C" -->
5799 * g_dbus_connection_call (connection,
5800 * "org.freedesktop.StringThings",
5801 * "/org/freedesktop/StringThings",
5802 * "org.freedesktop.StringThings",
5804 * g_variant_new ("(ss)",
5808 * G_DBUS_CALL_FLAGS_NONE,
5811 * (GAsyncReadyCallback) two_strings_done,
5815 * This is an asynchronous method. When the operation is finished,
5816 * @callback will be invoked in the
5817 * [thread-default main context][g-main-context-push-thread-default]
5818 * of the thread you are calling this method from. You can then call
5819 * g_dbus_connection_call_finish() to get the result of the operation.
5820 * See g_dbus_connection_call_sync() for the synchronous version of this
5823 * If @callback is %NULL then the D-Bus method call message will be sent with
5824 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5829 g_dbus_connection_call (GDBusConnection *connection,
5830 const gchar *bus_name,
5831 const gchar *object_path,
5832 const gchar *interface_name,
5833 const gchar *method_name,
5834 GVariant *parameters,
5835 const GVariantType *reply_type,
5836 GDBusCallFlags flags,
5838 GCancellable *cancellable,
5839 GAsyncReadyCallback callback,
5842 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);
5846 * g_dbus_connection_call_finish:
5847 * @connection: a #GDBusConnection
5848 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call()
5849 * @error: return location for error or %NULL
5851 * Finishes an operation started with g_dbus_connection_call().
5853 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5854 * return values. Free with g_variant_unref().
5859 g_dbus_connection_call_finish (GDBusConnection *connection,
5863 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5867 * g_dbus_connection_call_sync:
5868 * @connection: a #GDBusConnection
5869 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5870 * @connection is not a message bus connection
5871 * @object_path: path of remote object
5872 * @interface_name: D-Bus interface to invoke method on
5873 * @method_name: the name of the method to invoke
5874 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5875 * or %NULL if not passing parameters
5876 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5877 * @flags: flags from the #GDBusCallFlags enumeration
5878 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5879 * timeout or %G_MAXINT for no timeout
5880 * @cancellable: (allow-none): a #GCancellable or %NULL
5881 * @error: return location for error or %NULL
5883 * Synchronously invokes the @method_name method on the
5884 * @interface_name D-Bus interface on the remote object at
5885 * @object_path owned by @bus_name.
5887 * If @connection is closed then the operation will fail with
5888 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5889 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5890 * contains a value not compatible with the D-Bus protocol, the operation
5891 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5893 * If @reply_type is non-%NULL then the reply will be checked for having
5894 * this type and an error will be raised if it does not match. Said
5895 * another way, if you give a @reply_type then any non-%NULL return
5896 * value will be of this type.
5898 * If the @parameters #GVariant is floating, it is consumed.
5899 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5900 * |[<!-- language="C" -->
5901 * g_dbus_connection_call_sync (connection,
5902 * "org.freedesktop.StringThings",
5903 * "/org/freedesktop/StringThings",
5904 * "org.freedesktop.StringThings",
5906 * g_variant_new ("(ss)",
5910 * G_DBUS_CALL_FLAGS_NONE,
5916 * The calling thread is blocked until a reply is received. See
5917 * g_dbus_connection_call() for the asynchronous version of
5920 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5921 * return values. Free with g_variant_unref().
5926 g_dbus_connection_call_sync (GDBusConnection *connection,
5927 const gchar *bus_name,
5928 const gchar *object_path,
5929 const gchar *interface_name,
5930 const gchar *method_name,
5931 GVariant *parameters,
5932 const GVariantType *reply_type,
5933 GDBusCallFlags flags,
5935 GCancellable *cancellable,
5938 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);
5941 /* ---------------------------------------------------------------------------------------------------- */
5946 * g_dbus_connection_call_with_unix_fd_list:
5947 * @connection: a #GDBusConnection
5948 * @bus_name: (allow-none): a unique or well-known bus name or %NULL if
5949 * @connection is not a message bus connection
5950 * @object_path: path of remote object
5951 * @interface_name: D-Bus interface to invoke method on
5952 * @method_name: the name of the method to invoke
5953 * @parameters: (allow-none): a #GVariant tuple with parameters for the method
5954 * or %NULL if not passing parameters
5955 * @reply_type: (allow-none): the expected type of the reply, or %NULL
5956 * @flags: flags from the #GDBusCallFlags enumeration
5957 * @timeout_msec: the timeout in milliseconds, -1 to use the default
5958 * timeout or %G_MAXINT for no timeout
5959 * @fd_list: (allow-none): a #GUnixFDList or %NULL
5960 * @cancellable: (allow-none): a #GCancellable or %NULL
5961 * @callback: (allow-none): a #GAsyncReadyCallback to call when the request is
5962 * satisfied or %NULL if you don't * care about the result of the
5964 * @user_data: The data to pass to @callback.
5966 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5968 * This method is only available on UNIX.
5973 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5974 const gchar *bus_name,
5975 const gchar *object_path,
5976 const gchar *interface_name,
5977 const gchar *method_name,
5978 GVariant *parameters,
5979 const GVariantType *reply_type,
5980 GDBusCallFlags flags,
5982 GUnixFDList *fd_list,
5983 GCancellable *cancellable,
5984 GAsyncReadyCallback callback,
5987 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);
5991 * g_dbus_connection_call_with_unix_fd_list_finish:
5992 * @connection: a #GDBusConnection
5993 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
5994 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed to
5995 * g_dbus_connection_call_with_unix_fd_list()
5996 * @error: return location for error or %NULL
5998 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
6000 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6001 * return values. Free with g_variant_unref().
6006 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
6007 GUnixFDList **out_fd_list,
6011 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
6015 * g_dbus_connection_call_with_unix_fd_list_sync:
6016 * @connection: a #GDBusConnection
6017 * @bus_name: (allow-none): a unique or well-known bus name or %NULL
6018 * if @connection is not a message bus connection
6019 * @object_path: path of remote object
6020 * @interface_name: D-Bus interface to invoke method on
6021 * @method_name: the name of the method to invoke
6022 * @parameters: (allow-none): a #GVariant tuple with parameters for
6023 * the method or %NULL if not passing parameters
6024 * @reply_type: (allow-none): the expected type of the reply, or %NULL
6025 * @flags: flags from the #GDBusCallFlags enumeration
6026 * @timeout_msec: the timeout in milliseconds, -1 to use the default
6027 * timeout or %G_MAXINT for no timeout
6028 * @fd_list: (allow-none): a #GUnixFDList or %NULL
6029 * @out_fd_list: (out) (allow-none): return location for a #GUnixFDList or %NULL
6030 * @cancellable: (allow-none): a #GCancellable or %NULL
6031 * @error: return location for error or %NULL
6033 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
6035 * This method is only available on UNIX.
6037 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
6038 * return values. Free with g_variant_unref().
6043 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6044 const gchar *bus_name,
6045 const gchar *object_path,
6046 const gchar *interface_name,
6047 const gchar *method_name,
6048 GVariant *parameters,
6049 const GVariantType *reply_type,
6050 GDBusCallFlags flags,
6052 GUnixFDList *fd_list,
6053 GUnixFDList **out_fd_list,
6054 GCancellable *cancellable,
6057 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);
6060 #endif /* G_OS_UNIX */
6062 /* ---------------------------------------------------------------------------------------------------- */
6064 struct ExportedSubtree
6068 GDBusConnection *connection;
6069 GDBusSubtreeVTable *vtable;
6070 GDBusSubtreeFlags flags;
6072 GMainContext *context;
6074 GDestroyNotify user_data_free_func;
6078 exported_subtree_free (ExportedSubtree *es)
6080 call_destroy_notify (es->context,
6081 es->user_data_free_func,
6084 g_main_context_unref (es->context);
6086 _g_dbus_subtree_vtable_free (es->vtable);
6087 g_free (es->object_path);
6091 /* called without lock held in the thread where the caller registered
6095 handle_subtree_introspect (GDBusConnection *connection,
6096 ExportedSubtree *es,
6097 GDBusMessage *message)
6101 GDBusMessage *reply;
6104 const gchar *sender;
6105 const gchar *requested_object_path;
6106 const gchar *requested_node;
6107 GDBusInterfaceInfo **interfaces;
6109 gchar **subnode_paths;
6110 gboolean has_properties_interface;
6111 gboolean has_introspectable_interface;
6115 requested_object_path = g_dbus_message_get_path (message);
6116 sender = g_dbus_message_get_sender (message);
6117 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6119 s = g_string_new (NULL);
6120 introspect_append_header (s);
6122 /* Strictly we don't need the children in dynamic mode, but we avoid the
6123 * conditionals to preserve code clarity
6125 children = es->vtable->enumerate (es->connection,
6132 requested_node = strrchr (requested_object_path, '/') + 1;
6134 /* Assert existence of object if we are not dynamic */
6135 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6136 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6141 requested_node = NULL;
6144 interfaces = es->vtable->introspect (es->connection,
6149 if (interfaces != NULL)
6151 has_properties_interface = FALSE;
6152 has_introspectable_interface = FALSE;
6154 for (n = 0; interfaces[n] != NULL; n++)
6156 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6157 has_properties_interface = TRUE;
6158 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6159 has_introspectable_interface = TRUE;
6161 if (!has_properties_interface)
6162 g_string_append (s, introspect_properties_interface);
6163 if (!has_introspectable_interface)
6164 g_string_append (s, introspect_introspectable_interface);
6166 for (n = 0; interfaces[n] != NULL; n++)
6168 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6169 g_dbus_interface_info_unref (interfaces[n]);
6171 g_free (interfaces);
6174 /* then include <node> entries from the Subtree for the root */
6177 for (n = 0; children != NULL && children[n] != NULL; n++)
6178 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6181 /* finally include nodes registered below us */
6182 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6183 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6184 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6185 g_strfreev (subnode_paths);
6187 g_string_append (s, "</node>\n");
6189 reply = g_dbus_message_new_method_reply (message);
6190 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6191 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6192 g_object_unref (reply);
6197 g_string_free (s, TRUE);
6198 g_strfreev (children);
6202 /* called without lock held in the thread where the caller registered
6206 handle_subtree_method_invocation (GDBusConnection *connection,
6207 ExportedSubtree *es,
6208 GDBusMessage *message)
6211 const gchar *sender;
6212 const gchar *interface_name;
6213 const gchar *member;
6214 const gchar *signature;
6215 const gchar *requested_object_path;
6216 const gchar *requested_node;
6218 GDBusInterfaceInfo *interface_info;
6219 const GDBusInterfaceVTable *interface_vtable;
6220 gpointer interface_user_data;
6222 GDBusInterfaceInfo **interfaces;
6223 gboolean is_property_get;
6224 gboolean is_property_set;
6225 gboolean is_property_get_all;
6230 requested_object_path = g_dbus_message_get_path (message);
6231 sender = g_dbus_message_get_sender (message);
6232 interface_name = g_dbus_message_get_interface (message);
6233 member = g_dbus_message_get_member (message);
6234 signature = g_dbus_message_get_signature (message);
6235 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6237 is_property_get = FALSE;
6238 is_property_set = FALSE;
6239 is_property_get_all = FALSE;
6240 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6242 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6243 is_property_get = TRUE;
6244 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6245 is_property_set = TRUE;
6246 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6247 is_property_get_all = TRUE;
6252 requested_node = strrchr (requested_object_path, '/') + 1;
6254 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6256 /* We don't want to dispatch to unenumerated
6257 * nodes, so ensure that the child exists.
6262 children = es->vtable->enumerate (es->connection,
6267 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6268 g_strfreev (children);
6276 requested_node = NULL;
6279 /* get introspection data for the node */
6280 interfaces = es->vtable->introspect (es->connection,
6282 requested_object_path,
6286 if (interfaces == NULL)
6289 interface_info = NULL;
6290 for (n = 0; interfaces[n] != NULL; n++)
6292 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6293 interface_info = interfaces[n];
6296 /* dispatch the call if the user wants to handle it */
6297 if (interface_info != NULL)
6299 /* figure out where to dispatch the method call */
6300 interface_user_data = NULL;
6301 interface_vtable = es->vtable->dispatch (es->connection,
6306 &interface_user_data,
6308 if (interface_vtable == NULL)
6311 CONNECTION_LOCK (connection);
6312 handled = validate_and_maybe_schedule_method_call (es->connection,
6319 interface_user_data);
6320 CONNECTION_UNLOCK (connection);
6322 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6323 else if (is_property_get || is_property_set || is_property_get_all)
6325 if (is_property_get)
6326 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6327 else if (is_property_set)
6328 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6329 else if (is_property_get_all)
6330 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6332 g_assert_not_reached ();
6334 /* see if the object supports this interface at all */
6335 for (n = 0; interfaces[n] != NULL; n++)
6337 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6338 interface_info = interfaces[n];
6341 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6342 * claims it won't support the interface
6344 if (interface_info == NULL)
6346 GDBusMessage *reply;
6347 reply = g_dbus_message_new_method_error (message,
6348 "org.freedesktop.DBus.Error.InvalidArgs",
6349 _("No such interface '%s'"),
6351 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6352 g_object_unref (reply);
6357 /* figure out where to dispatch the property get/set/getall calls */
6358 interface_user_data = NULL;
6359 interface_vtable = es->vtable->dispatch (es->connection,
6364 &interface_user_data,
6366 if (interface_vtable == NULL)
6368 g_warning ("The subtree introspection function indicates that '%s' "
6369 "is a valid interface name, but calling the dispatch "
6370 "function on that interface gave us NULL", interface_name);
6374 if (is_property_get || is_property_set)
6376 CONNECTION_LOCK (connection);
6377 handled = validate_and_maybe_schedule_property_getset (es->connection,
6385 interface_user_data);
6386 CONNECTION_UNLOCK (connection);
6388 else if (is_property_get_all)
6390 CONNECTION_LOCK (connection);
6391 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6398 interface_user_data);
6399 CONNECTION_UNLOCK (connection);
6404 if (interfaces != NULL)
6406 for (n = 0; interfaces[n] != NULL; n++)
6407 g_dbus_interface_info_unref (interfaces[n]);
6408 g_free (interfaces);
6416 GDBusMessage *message;
6417 ExportedSubtree *es;
6418 } SubtreeDeferredData;
6421 subtree_deferred_data_free (SubtreeDeferredData *data)
6423 g_object_unref (data->message);
6427 /* called without lock held in the thread where the caller registered the subtree */
6429 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6431 SubtreeDeferredData *data = _data;
6436 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6437 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6438 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6439 handled = handle_subtree_introspect (data->es->connection,
6443 handled = handle_subtree_method_invocation (data->es->connection,
6449 CONNECTION_LOCK (data->es->connection);
6450 handled = handle_generic_unlocked (data->es->connection, data->message);
6451 CONNECTION_UNLOCK (data->es->connection);
6454 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6457 GDBusMessage *reply;
6458 reply = g_dbus_message_new_method_error (data->message,
6459 "org.freedesktop.DBus.Error.UnknownMethod",
6460 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6461 g_dbus_message_get_member (data->message),
6462 g_dbus_message_get_interface (data->message),
6463 g_dbus_message_get_signature (data->message));
6464 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6465 g_object_unref (reply);
6471 /* called in GDBusWorker thread with connection's lock held */
6473 subtree_message_func (GDBusConnection *connection,
6474 ExportedSubtree *es,
6475 GDBusMessage *message)
6477 GSource *idle_source;
6478 SubtreeDeferredData *data;
6480 data = g_new0 (SubtreeDeferredData, 1);
6481 data->message = g_object_ref (message);
6484 /* defer this call to an idle handler in the right thread */
6485 idle_source = g_idle_source_new ();
6486 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6487 g_source_set_callback (idle_source,
6488 process_subtree_vtable_message_in_idle_cb,
6490 (GDestroyNotify) subtree_deferred_data_free);
6491 g_source_attach (idle_source, es->context);
6492 g_source_unref (idle_source);
6494 /* since we own the entire subtree, handlers for objects not in the subtree have been
6495 * tried already by libdbus-1 - so we just need to ensure that we're always going
6496 * to reply to the message
6502 * g_dbus_connection_register_subtree:
6503 * @connection: a #GDBusConnection
6504 * @object_path: the object path to register the subtree at
6505 * @vtable: a #GDBusSubtreeVTable to enumerate, introspect and
6506 * dispatch nodes in the subtree
6507 * @flags: flags used to fine tune the behavior of the subtree
6508 * @user_data: data to pass to functions in @vtable
6509 * @user_data_free_func: function to call when the subtree is unregistered
6510 * @error: return location for error or %NULL
6512 * Registers a whole subtree of dynamic objects.
6514 * The @enumerate and @introspection functions in @vtable are used to
6515 * convey, to remote callers, what nodes exist in the subtree rooted
6518 * When handling remote calls into any node in the subtree, first the
6519 * @enumerate function is used to check if the node exists. If the node exists
6520 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6521 * the @introspection function is used to check if the node supports the
6522 * requested method. If so, the @dispatch function is used to determine
6523 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6524 * #gpointer will be used to call into the interface vtable for processing
6527 * All calls into user-provided code will be invoked in the
6528 * [thread-default main context][g-main-context-push-thread-default]
6529 * of the thread you are calling this method from.
6531 * If an existing subtree is already registered at @object_path or
6532 * then @error is set to #G_IO_ERROR_EXISTS.
6534 * Note that it is valid to register regular objects (using
6535 * g_dbus_connection_register_object()) in a subtree registered with
6536 * g_dbus_connection_register_subtree() - if so, the subtree handler
6537 * is tried as the last resort. One way to think about a subtree
6538 * handler is to consider it a fallback handler for object paths not
6539 * registered via g_dbus_connection_register_object() or other bindings.
6541 * Note that @vtable will be copied so you cannot change it after
6544 * See this [server][gdbus-subtree-server] for an example of how to use
6547 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6548 * that can be used with g_dbus_connection_unregister_subtree() .
6553 g_dbus_connection_register_subtree (GDBusConnection *connection,
6554 const gchar *object_path,
6555 const GDBusSubtreeVTable *vtable,
6556 GDBusSubtreeFlags flags,
6558 GDestroyNotify user_data_free_func,
6562 ExportedSubtree *es;
6564 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6565 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6566 g_return_val_if_fail (vtable != NULL, 0);
6567 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6568 g_return_val_if_fail (check_initialized (connection), 0);
6572 CONNECTION_LOCK (connection);
6574 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6580 _("A subtree is already exported for %s"),
6585 es = g_new0 (ExportedSubtree, 1);
6586 es->object_path = g_strdup (object_path);
6587 es->connection = connection;
6589 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6591 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6592 es->user_data = user_data;
6593 es->user_data_free_func = user_data_free_func;
6594 es->context = g_main_context_ref_thread_default ();
6596 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6597 g_hash_table_insert (connection->map_id_to_es,
6598 GUINT_TO_POINTER (es->id),
6604 CONNECTION_UNLOCK (connection);
6609 /* ---------------------------------------------------------------------------------------------------- */
6612 * g_dbus_connection_unregister_subtree:
6613 * @connection: a #GDBusConnection
6614 * @registration_id: a subtree registration id obtained from
6615 * g_dbus_connection_register_subtree()
6617 * Unregisters a subtree.
6619 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise
6624 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6625 guint registration_id)
6627 ExportedSubtree *es;
6630 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6631 g_return_val_if_fail (check_initialized (connection), FALSE);
6635 CONNECTION_LOCK (connection);
6637 es = g_hash_table_lookup (connection->map_id_to_es,
6638 GUINT_TO_POINTER (registration_id));
6642 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6643 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6648 CONNECTION_UNLOCK (connection);
6653 /* ---------------------------------------------------------------------------------------------------- */
6655 /* may be called in any thread, with connection's lock held */
6657 handle_generic_ping_unlocked (GDBusConnection *connection,
6658 const gchar *object_path,
6659 GDBusMessage *message)
6661 GDBusMessage *reply;
6662 reply = g_dbus_message_new_method_reply (message);
6663 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6664 g_object_unref (reply);
6667 /* may be called in any thread, with connection's lock held */
6669 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6670 const gchar *object_path,
6671 GDBusMessage *message)
6673 GDBusMessage *reply;
6676 if (connection->machine_id == NULL)
6681 connection->machine_id = _g_dbus_get_machine_id (&error);
6682 if (connection->machine_id == NULL)
6684 reply = g_dbus_message_new_method_error_literal (message,
6685 "org.freedesktop.DBus.Error.Failed",
6687 g_error_free (error);
6693 reply = g_dbus_message_new_method_reply (message);
6694 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6696 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6697 g_object_unref (reply);
6700 /* may be called in any thread, with connection's lock held */
6702 handle_generic_introspect_unlocked (GDBusConnection *connection,
6703 const gchar *object_path,
6704 GDBusMessage *message)
6709 GDBusMessage *reply;
6711 /* first the header */
6712 s = g_string_new (NULL);
6713 introspect_append_header (s);
6715 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6716 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6717 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6718 g_strfreev (registered);
6719 g_string_append (s, "</node>\n");
6721 reply = g_dbus_message_new_method_reply (message);
6722 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6723 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6724 g_object_unref (reply);
6725 g_string_free (s, TRUE);
6728 /* may be called in any thread, with connection's lock held */
6730 handle_generic_unlocked (GDBusConnection *connection,
6731 GDBusMessage *message)
6734 const gchar *interface_name;
6735 const gchar *member;
6736 const gchar *signature;
6739 CONNECTION_ENSURE_LOCK (connection);
6743 interface_name = g_dbus_message_get_interface (message);
6744 member = g_dbus_message_get_member (message);
6745 signature = g_dbus_message_get_signature (message);
6746 path = g_dbus_message_get_path (message);
6748 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6749 g_strcmp0 (member, "Introspect") == 0 &&
6750 g_strcmp0 (signature, "") == 0)
6752 handle_generic_introspect_unlocked (connection, path, message);
6755 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6756 g_strcmp0 (member, "Ping") == 0 &&
6757 g_strcmp0 (signature, "") == 0)
6759 handle_generic_ping_unlocked (connection, path, message);
6762 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6763 g_strcmp0 (member, "GetMachineId") == 0 &&
6764 g_strcmp0 (signature, "") == 0)
6766 handle_generic_get_machine_id_unlocked (connection, path, message);
6773 /* ---------------------------------------------------------------------------------------------------- */
6775 /* called in GDBusWorker thread with connection's lock held */
6777 distribute_method_call (GDBusConnection *connection,
6778 GDBusMessage *message)
6780 GDBusMessage *reply;
6782 ExportedSubtree *es;
6783 const gchar *object_path;
6784 const gchar *interface_name;
6785 const gchar *member;
6787 gchar *subtree_path;
6790 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6792 interface_name = g_dbus_message_get_interface (message);
6793 member = g_dbus_message_get_member (message);
6794 path = g_dbus_message_get_path (message);
6795 subtree_path = g_strdup (path);
6796 needle = strrchr (subtree_path, '/');
6797 if (needle != NULL && needle != subtree_path)
6803 g_free (subtree_path);
6804 subtree_path = NULL;
6808 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6810 _g_dbus_debug_print_lock ();
6811 g_print ("========================================================================\n"
6812 "GDBus-debug:Incoming:\n"
6813 " <<<< METHOD INVOCATION %s.%s()\n"
6815 " invoked by name %s\n"
6817 interface_name, member,
6819 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6820 g_dbus_message_get_serial (message));
6821 _g_dbus_debug_print_unlock ();
6824 object_path = g_dbus_message_get_path (message);
6825 g_assert (object_path != NULL);
6827 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6830 if (obj_message_func (connection, eo, message))
6834 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6837 if (subtree_message_func (connection, es, message))
6841 if (subtree_path != NULL)
6843 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6846 if (subtree_message_func (connection, es, message))
6851 if (handle_generic_unlocked (connection, message))
6854 /* if we end up here, the message has not been not handled - so return an error saying this */
6855 reply = g_dbus_message_new_method_error (message,
6856 "org.freedesktop.DBus.Error.UnknownMethod",
6857 _("No such interface '%s' on object at path %s"),
6860 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6861 g_object_unref (reply);
6864 g_free (subtree_path);
6867 /* ---------------------------------------------------------------------------------------------------- */
6869 /* Called in any user thread, with the message_bus_lock held. */
6871 message_bus_get_singleton (GBusType bus_type,
6875 const gchar *starter_bus;
6881 case G_BUS_TYPE_SESSION:
6882 ret = &the_session_bus;
6885 case G_BUS_TYPE_SYSTEM:
6886 ret = &the_system_bus;
6889 case G_BUS_TYPE_STARTER:
6890 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6891 if (g_strcmp0 (starter_bus, "session") == 0)
6893 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6896 else if (g_strcmp0 (starter_bus, "system") == 0)
6898 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6903 if (starter_bus != NULL)
6907 G_IO_ERROR_INVALID_ARGUMENT,
6908 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6909 " - unknown value '%s'"),
6914 g_set_error_literal (error,
6916 G_IO_ERROR_INVALID_ARGUMENT,
6917 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6918 "variable is not set"));
6924 g_assert_not_reached ();
6932 /* Called in any user thread, without holding locks. */
6933 static GDBusConnection *
6934 get_uninitialized_connection (GBusType bus_type,
6935 GCancellable *cancellable,
6938 GWeakRef *singleton;
6939 GDBusConnection *ret;
6943 G_LOCK (message_bus_lock);
6944 singleton = message_bus_get_singleton (bus_type, error);
6945 if (singleton == NULL)
6948 ret = g_weak_ref_get (singleton);
6953 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6954 if (address == NULL)
6956 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6958 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6959 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6960 "exit-on-close", TRUE,
6963 g_weak_ref_set (singleton, ret);
6967 g_assert (ret != NULL);
6970 G_UNLOCK (message_bus_lock);
6974 /* May be called from any thread. Must not hold message_bus_lock. */
6976 _g_bus_get_singleton_if_exists (GBusType bus_type)
6978 GWeakRef *singleton;
6979 GDBusConnection *ret = NULL;
6981 G_LOCK (message_bus_lock);
6982 singleton = message_bus_get_singleton (bus_type, NULL);
6983 if (singleton == NULL)
6986 ret = g_weak_ref_get (singleton);
6989 G_UNLOCK (message_bus_lock);
6995 * @bus_type: a #GBusType
6996 * @cancellable: (allow-none): a #GCancellable or %NULL
6997 * @error: return location for error or %NULL
6999 * Synchronously connects to the message bus specified by @bus_type.
7000 * Note that the returned object may shared with other callers,
7001 * e.g. if two separate parts of a process calls this function with
7002 * the same @bus_type, they will share the same object.
7004 * This is a synchronous failable function. See g_bus_get() and
7005 * g_bus_get_finish() for the asynchronous version.
7007 * The returned object is a singleton, that is, shared with other
7008 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7009 * event that you need a private message bus connection, use
7010 * g_dbus_address_get_for_bus_sync() and
7011 * g_dbus_connection_new_for_address().
7013 * Note that the returned #GDBusConnection object will (usually) have
7014 * the #GDBusConnection:exit-on-close property set to %TRUE.
7016 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7017 * Free with g_object_unref().
7022 g_bus_get_sync (GBusType bus_type,
7023 GCancellable *cancellable,
7026 GDBusConnection *connection;
7028 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7030 connection = get_uninitialized_connection (bus_type, cancellable, error);
7031 if (connection == NULL)
7034 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
7036 g_object_unref (connection);
7045 bus_get_async_initable_cb (GObject *source_object,
7049 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7053 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7057 g_assert (error != NULL);
7058 g_simple_async_result_take_error (simple, error);
7059 g_object_unref (source_object);
7063 g_simple_async_result_set_op_res_gpointer (simple,
7067 g_simple_async_result_complete_in_idle (simple);
7068 g_object_unref (simple);
7073 * @bus_type: a #GBusType
7074 * @cancellable: (allow-none): a #GCancellable or %NULL
7075 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
7076 * @user_data: the data to pass to @callback
7078 * Asynchronously connects to the message bus specified by @bus_type.
7080 * When the operation is finished, @callback will be invoked. You can
7081 * then call g_bus_get_finish() to get the result of the operation.
7083 * This is a asynchronous failable function. See g_bus_get_sync() for
7084 * the synchronous version.
7089 g_bus_get (GBusType bus_type,
7090 GCancellable *cancellable,
7091 GAsyncReadyCallback callback,
7094 GDBusConnection *connection;
7095 GSimpleAsyncResult *simple;
7098 simple = g_simple_async_result_new (NULL,
7102 g_simple_async_result_set_check_cancellable (simple, cancellable);
7105 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7106 if (connection == NULL)
7108 g_assert (error != NULL);
7109 g_simple_async_result_take_error (simple, error);
7110 g_simple_async_result_complete_in_idle (simple);
7111 g_object_unref (simple);
7115 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7118 bus_get_async_initable_cb,
7125 * @res: a #GAsyncResult obtained from the #GAsyncReadyCallback passed
7127 * @error: return location for error or %NULL
7129 * Finishes an operation started with g_bus_get().
7131 * The returned object is a singleton, that is, shared with other
7132 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7133 * event that you need a private message bus connection, use
7134 * g_dbus_address_get_for_bus_sync() and
7135 * g_dbus_connection_new_for_address().
7137 * Note that the returned #GDBusConnection object will (usually) have
7138 * the #GDBusConnection:exit-on-close property set to %TRUE.
7140 * Returns: (transfer full): a #GDBusConnection or %NULL if @error is set.
7141 * Free with g_object_unref().
7146 g_bus_get_finish (GAsyncResult *res,
7149 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7151 GDBusConnection *ret;
7153 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7155 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7159 if (g_simple_async_result_propagate_error (simple, error))
7162 object = g_simple_async_result_get_op_res_gpointer (simple);
7163 g_assert (object != NULL);
7164 ret = g_object_ref (G_DBUS_CONNECTION (object));
7170 /* ---------------------------------------------------------------------------------------------------- */