1 /* GDBus - GLib D-Bus Library
3 * Copyright (C) 2008-2010 Red Hat, Inc.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General
16 * Public License along with this library; if not, write to the
17 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18 * Boston, MA 02111-1307, USA.
20 * Author: David Zeuthen <davidz@redhat.com>
26 * - would be nice to expose GDBusAuthMechanism and an extension point
28 * - Need to rewrite GDBusAuth and rework GDBusAuthMechanism. In particular
29 * the mechanism VFuncs need to be able to set an error.
31 * - Need to document other mechanisms/sources for determining the D-Bus
32 * address of a well-known bus.
34 * - e.g. on Win32 we need code like from here
36 * http://cgit.freedesktop.org/~david/gdbus-standalone/tree/gdbus/gdbusaddress.c#n900
38 * that was never copied over here because it originally was copy-paste
39 * from the GPLv2 / AFL 2.1 libdbus sources.
41 * - on OS X we need to look in launchd for the address
43 * https://bugs.freedesktop.org/show_bug.cgi?id=14259
45 * - on X11 we need to look in a X11 property on the X server
46 * - (we can also just use dbus-launch(1) from the D-Bus
49 * - (ideally) this requires D-Bus spec work because none of
50 * this has never really been specced out properly (except
53 * - Related to the above, we also need to be able to launch a message bus
54 * instance.... Since we don't want to write our own bus daemon we should
55 * launch dbus-daemon(1) (thus: Win32 and OS X need to bundle it)
57 * - probably want a G_DBUS_NONCE_TCP_TMPDIR environment variable
58 * to specify where the nonce is stored. This will allow people to use
59 * G_DBUS_NONCE_TCP_TMPDIR=/mnt/secure.company.server/dbus-nonce-dir
60 * to easily achieve secure RPC via nonce-tcp.
62 * - need to expose an extension point for resolving D-Bus address and
63 * turning them into GIOStream objects. This will allow us to implement
64 * e.g. X11 D-Bus transports without dlopen()'ing or linking against
66 * - see g_dbus_address_connect() in gdbusaddress.c
68 * - would be cute to use kernel-specific APIs to resolve fds for
69 * debug output when using G_DBUS_DEBUG=message, e.g. in addition to
71 * fd 21: dev=8:1,mode=0100644,ino=1171231,uid=0,gid=0,rdev=0:0,size=234,atime=1273070640,mtime=1267126160,ctime=1267126160
73 * maybe we can show more information about what fd 21 really is.
74 * Ryan suggests looking in /proc/self/fd for clues / symlinks!
75 * Initial experiments on Linux 2.6 suggests that the symlink looks
80 * e.g. not of much use.
82 * - GDBus High-Level docs
83 * - Proxy: properties, signals...
84 * - Connection: IOStream based, ::close, connection setup steps
85 * mainloop integration, threading
86 * - Differences from libdbus (extend "Migrating from")
87 * - the message handling thread
88 * - Using GVariant instead of GValue
89 * - Explain why the high-level API is a good thing and what
90 * kind of pitfalls it avoids
91 * - Export objects before claiming names
92 * - Talk about auto-starting services (cf. GBusNameWatcherFlags)
94 * - use abstract sockets in test code
95 * - right now it doesn't work, dbus-daemon(1) fails with
97 * /gdbus/connection/filter: Failed to start message bus: Failed to bind
98 * socket "/tmp/g-dbus-tests-pid-28531": Address already in use
99 * ** WARNING **: Error reading address from dbus daemon, 0 bytes read
108 #include <sys/types.h>
113 #include "gdbusauth.h"
114 #include "gdbusutils.h"
115 #include "gdbusaddress.h"
116 #include "gdbusmessage.h"
117 #include "gdbusconnection.h"
118 #include "gdbuserror.h"
119 #include "gioenumtypes.h"
120 #include "gdbusintrospection.h"
121 #include "gdbusmethodinvocation.h"
122 #include "gdbusprivate.h"
123 #include "gdbusauthobserver.h"
124 #include "ginitable.h"
125 #include "gasyncinitable.h"
126 #include "giostream.h"
127 #include "gasyncresult.h"
128 #include "gsimpleasyncresult.h"
131 #include "gunixconnection.h"
132 #include "gunixfdmessage.h"
135 #include "glibintl.h"
138 * SECTION:gdbusconnection
139 * @short_description: D-Bus Connections
140 * @include: gio/gio.h
142 * The #GDBusConnection type is used for D-Bus connections to remote
143 * peers such as a message buses. It is a low-level API that offers a
144 * lot of flexibility. For instance, it lets you establish a connection
145 * over any transport that can by represented as an #GIOStream.
147 * This class is rarely used directly in D-Bus clients. If you are writing
148 * an D-Bus client, it is often easier to use the g_bus_own_name(),
149 * g_bus_watch_name() or g_dbus_proxy_new_for_bus() APIs.
151 * As an exception to the usual GLib rule that a particular object must not be
152 * used by two threads at the same time, #GDBusConnection's methods may be
153 * called from any thread<footnote>
155 * This is so that g_bus_get() and g_bus_get_sync() can safely return the
156 * same #GDBusConnection when called from any thread.
160 * Most of the ways to obtain a #GDBusConnection automatically initialize it
161 * (i.e. connect to D-Bus): for instance, g_dbus_connection_new() and
162 * g_bus_get(), and the synchronous versions of those methods, give you an
163 * initialized connection. Language bindings for GIO should use
164 * g_initable_new() or g_async_initable_new_async(), which also initialize the
167 * If you construct an uninitialized #GDBusConnection, such as via
168 * g_object_new(), you must initialize it via g_initable_init() or
169 * g_async_initable_init_async() before using its methods or properties.
170 * Calling methods or accessing properties on a #GDBusConnection that has not
171 * completed initialization successfully is considered to be invalid, and leads
172 * to undefined behaviour. In particular, if initialization fails with a
173 * #GError, the only valid thing you can do with that #GDBusConnection is to
174 * free it with g_object_unref().
176 * <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>
178 * <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>
180 * <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>
182 * <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>
185 /* ---------------------------------------------------------------------------------------------------- */
187 typedef struct _GDBusConnectionClass GDBusConnectionClass;
190 * GDBusConnectionClass:
191 * @closed: Signal class handler for the #GDBusConnection::closed signal.
193 * Class structure for #GDBusConnection.
197 struct _GDBusConnectionClass
200 GObjectClass parent_class;
204 void (*closed) (GDBusConnection *connection,
205 gboolean remote_peer_vanished,
209 G_LOCK_DEFINE_STATIC (message_bus_lock);
211 static GWeakRef the_session_bus;
212 static GWeakRef the_system_bus;
214 /* Extra pseudo-member of GDBusSendMessageFlags.
215 * Set by initable_init() to indicate that despite not being initialized yet,
216 * enough of the only-valid-after-init members are set that we can send a
217 * message, and we're being called from its thread, so no memory barrier is
218 * required before accessing them.
220 #define SEND_MESSAGE_FLAGS_INITIALIZING (1<<31)
222 /* Same as SEND_MESSAGE_FLAGS_INITIALIZING, but in GDBusCallFlags */
223 #define CALL_FLAGS_INITIALIZING (1<<31)
225 /* ---------------------------------------------------------------------------------------------------- */
229 GDestroyNotify callback;
231 GMainContext *context;
232 } CallDestroyNotifyData;
235 call_destroy_notify_data_in_idle (gpointer user_data)
237 CallDestroyNotifyData *data = user_data;
238 data->callback (data->user_data);
243 call_destroy_notify_data_free (CallDestroyNotifyData *data)
245 if (data->context != NULL)
246 g_main_context_unref (data->context);
251 * call_destroy_notify: <internal>
252 * @context: (allow-none): A #GMainContext or %NULL.
253 * @callback: (allow-none): A #GDestroyNotify or %NULL.
254 * @user_data: Data to pass to @callback.
256 * Schedules @callback to run in @context.
259 call_destroy_notify (GMainContext *context,
260 GDestroyNotify callback,
263 GSource *idle_source;
264 CallDestroyNotifyData *data;
266 if (callback == NULL)
269 data = g_new0 (CallDestroyNotifyData, 1);
270 data->callback = callback;
271 data->user_data = user_data;
272 data->context = context;
273 if (data->context != NULL)
274 g_main_context_ref (data->context);
276 idle_source = g_idle_source_new ();
277 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
278 g_source_set_callback (idle_source,
279 call_destroy_notify_data_in_idle,
281 (GDestroyNotify) call_destroy_notify_data_free);
282 g_source_attach (idle_source, data->context);
283 g_source_unref (idle_source);
289 /* ---------------------------------------------------------------------------------------------------- */
292 _g_strv_has_string (const gchar* const *haystack,
297 for (n = 0; haystack != NULL && haystack[n] != NULL; n++)
299 if (g_strcmp0 (haystack[n], needle) == 0)
305 /* ---------------------------------------------------------------------------------------------------- */
308 #define CONNECTION_ENSURE_LOCK(obj) do { ; } while (FALSE)
310 // TODO: for some reason this doesn't work on Windows
311 #define CONNECTION_ENSURE_LOCK(obj) do { \
312 if (G_UNLIKELY (g_mutex_trylock(&(obj)->lock))) \
314 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
315 "CONNECTION_ENSURE_LOCK: GDBusConnection object lock is not locked"); \
320 #define CONNECTION_LOCK(obj) do { \
321 g_mutex_lock (&(obj)->lock); \
324 #define CONNECTION_UNLOCK(obj) do { \
325 g_mutex_unlock (&(obj)->lock); \
328 /* Flags in connection->atomic_flags */
330 FLAG_INITIALIZED = 1 << 0,
331 FLAG_EXIT_ON_CLOSE = 1 << 1,
338 * The #GDBusConnection structure contains only private data and
339 * should only be accessed using the provided API.
343 struct _GDBusConnection
346 GObject parent_instance;
348 /* ------------------------------------------------------------------------ */
349 /* -- General object state ------------------------------------------------ */
350 /* ------------------------------------------------------------------------ */
352 /* General-purpose lock for most fields */
355 /* A lock used in the init() method of the GInitable interface - see comments
356 * in initable_init() for why a separate lock is needed.
358 * If you need both @lock and @init_lock, you must take @init_lock first.
362 /* Set (by loading the contents of /var/lib/dbus/machine-id) the first time
363 * someone calls org.freedesktop.DBus.GetMachineId(). Protected by @lock.
367 /* The underlying stream used for communication
368 * Read-only after initable_init(), so it may be read if you either
369 * hold @init_lock or check for initialization first.
373 /* The object used for authentication (if any).
374 * Read-only after initable_init(), so it may be read if you either
375 * hold @init_lock or check for initialization first.
379 /* Last serial used. Protected by @lock. */
382 /* The object used to send/receive messages.
383 * Read-only after initable_init(), so it may be read if you either
384 * hold @init_lock or check for initialization first.
388 /* If connected to a message bus, this contains the unique name assigned to
389 * us by the bus (e.g. ":1.42").
390 * Read-only after initable_init(), so it may be read if you either
391 * hold @init_lock or check for initialization first.
393 gchar *bus_unique_name;
395 /* The GUID returned by the other side if we authenticed as a client or
396 * the GUID to use if authenticating as a server.
397 * Read-only after initable_init(), so it may be read if you either
398 * hold @init_lock or check for initialization first.
402 /* FLAG_INITIALIZED is set exactly when initable_init() has finished running.
403 * Inspect @initialization_error to see whether it succeeded or failed.
405 * FLAG_EXIT_ON_CLOSE is the exit-on-close property.
407 * FLAG_CLOSED is the closed property. It may be read at any time, but
408 * may only be written while holding @lock.
410 volatile gint atomic_flags;
412 /* If the connection could not be established during initable_init(),
413 * this GError will be set.
414 * Read-only after initable_init(), so it may be read if you either
415 * hold @init_lock or check for initialization first.
417 GError *initialization_error;
419 /* The result of g_main_context_ref_thread_default() when the object
420 * was created (the GObject _init() function) - this is used for delivery
421 * of the :closed GObject signal.
423 * Only set in the GObject init function, so no locks are needed.
425 GMainContext *main_context_at_construction;
427 /* Read-only construct properties, no locks needed */
429 GDBusConnectionFlags flags;
431 /* Map used for managing method replies, protected by @lock */
432 GHashTable *map_method_serial_to_send_message_data; /* guint32 -> SendMessageData* */
434 /* Maps used for managing signal subscription, protected by @lock */
435 GHashTable *map_rule_to_signal_data; /* match rule (gchar*) -> SignalData */
436 GHashTable *map_id_to_signal_data; /* id (guint) -> SignalData */
437 GHashTable *map_sender_unique_name_to_signal_data_array; /* unique sender (gchar*) -> GPtrArray* of SignalData */
439 /* Maps used for managing exported objects and subtrees,
442 GHashTable *map_object_path_to_eo; /* gchar* -> ExportedObject* */
443 GHashTable *map_id_to_ei; /* guint -> ExportedInterface* */
444 GHashTable *map_object_path_to_es; /* gchar* -> ExportedSubtree* */
445 GHashTable *map_id_to_es; /* guint -> ExportedSubtree* */
447 /* Map used for storing last used serials for each thread, protected by @lock */
448 GHashTable *map_thread_to_last_serial;
450 /* Structure used for message filters, protected by @lock */
453 /* Capabilities negotiated during authentication
454 * Read-only after initable_init(), so it may be read without holding a
455 * lock, if you check for initialization first.
457 GDBusCapabilityFlags capabilities;
459 /* Protected by @init_lock */
460 GDBusAuthObserver *authentication_observer;
462 /* Read-only after initable_init(), so it may be read if you either
463 * hold @init_lock or check for initialization first.
465 GCredentials *credentials;
467 /* set to TRUE when finalizing */
471 typedef struct ExportedObject ExportedObject;
472 static void exported_object_free (ExportedObject *eo);
474 typedef struct ExportedSubtree ExportedSubtree;
475 static void exported_subtree_free (ExportedSubtree *es);
493 PROP_CAPABILITY_FLAGS,
494 PROP_AUTHENTICATION_OBSERVER,
497 static void distribute_signals (GDBusConnection *connection,
498 GDBusMessage *message);
500 static void distribute_method_call (GDBusConnection *connection,
501 GDBusMessage *message);
503 static gboolean handle_generic_unlocked (GDBusConnection *connection,
504 GDBusMessage *message);
507 static void purge_all_signal_subscriptions (GDBusConnection *connection);
508 static void purge_all_filters (GDBusConnection *connection);
510 static void schedule_method_call (GDBusConnection *connection,
511 GDBusMessage *message,
512 guint registration_id,
513 guint subtree_registration_id,
514 const GDBusInterfaceInfo *interface_info,
515 const GDBusMethodInfo *method_info,
516 const GDBusPropertyInfo *property_info,
517 GVariant *parameters,
518 const GDBusInterfaceVTable *vtable,
519 GMainContext *main_context,
522 #define _G_ENSURE_LOCK(name) do { \
523 if (G_UNLIKELY (G_TRYLOCK(name))) \
525 g_assertion_message (G_LOG_DOMAIN, __FILE__, __LINE__, G_STRFUNC, \
526 "_G_ENSURE_LOCK: Lock '" #name "' is not locked"); \
530 static guint signals[LAST_SIGNAL] = { 0 };
532 static void initable_iface_init (GInitableIface *initable_iface);
533 static void async_initable_iface_init (GAsyncInitableIface *async_initable_iface);
535 G_DEFINE_TYPE_WITH_CODE (GDBusConnection, g_dbus_connection, G_TYPE_OBJECT,
536 G_IMPLEMENT_INTERFACE (G_TYPE_INITABLE, initable_iface_init)
537 G_IMPLEMENT_INTERFACE (G_TYPE_ASYNC_INITABLE, async_initable_iface_init)
541 * Check that all members of @connection that can only be accessed after
542 * the connection is initialized can safely be accessed. If not,
543 * log a critical warning. This function is a memory barrier.
545 * Returns: %TRUE if initialized
548 check_initialized (GDBusConnection *connection)
550 /* The access to @atomic_flags isn't conditional, so that this function
551 * provides a memory barrier for thread-safety even if checks are disabled.
552 * (If you don't want this stricter guarantee, you can call
553 * g_return_if_fail (check_initialized (c)).)
555 * This isn't strictly necessary now that we've decided use of an
556 * uninitialized GDBusConnection is undefined behaviour, but it seems
557 * better to be as deterministic as is feasible.
559 * (Anything that could suffer a crash from seeing undefined values
560 * must have a race condition - thread A initializes the connection while
561 * thread B calls a method without initialization, hoping that thread A will
562 * win the race - so its behaviour is undefined anyway.)
564 gint flags = g_atomic_int_get (&connection->atomic_flags);
566 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
568 /* We can safely access this, due to the memory barrier above */
569 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
575 MAY_BE_UNINITIALIZED = (1<<1)
576 } CheckUnclosedFlags;
579 * Check the same thing as check_initialized(), and also that the
580 * connection is not closed. If the connection is uninitialized,
581 * raise a critical warning (it's programmer error); if it's closed,
582 * raise a recoverable GError (it's a runtime error).
584 * This function is a memory barrier.
586 * Returns: %TRUE if initialized and not closed
589 check_unclosed (GDBusConnection *connection,
590 CheckUnclosedFlags check,
593 /* check_initialized() is effectively inlined, so we don't waste time
594 * doing two memory barriers
596 gint flags = g_atomic_int_get (&connection->atomic_flags);
598 if (!(check & MAY_BE_UNINITIALIZED))
600 g_return_val_if_fail (flags & FLAG_INITIALIZED, FALSE);
601 g_return_val_if_fail (connection->initialization_error == NULL, FALSE);
604 if (flags & FLAG_CLOSED)
606 g_set_error_literal (error,
609 _("The connection is closed"));
616 static GHashTable *alive_connections = NULL;
619 g_dbus_connection_dispose (GObject *object)
621 GDBusConnection *connection = G_DBUS_CONNECTION (object);
623 G_LOCK (message_bus_lock);
624 CONNECTION_LOCK (connection);
625 if (connection->worker != NULL)
627 _g_dbus_worker_stop (connection->worker);
628 connection->worker = NULL;
629 if (alive_connections != NULL)
630 g_warn_if_fail (g_hash_table_remove (alive_connections, connection));
634 if (alive_connections != NULL)
635 g_warn_if_fail (g_hash_table_lookup (alive_connections, connection) == NULL);
637 CONNECTION_UNLOCK (connection);
638 G_UNLOCK (message_bus_lock);
640 if (G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose != NULL)
641 G_OBJECT_CLASS (g_dbus_connection_parent_class)->dispose (object);
645 g_dbus_connection_finalize (GObject *object)
647 GDBusConnection *connection = G_DBUS_CONNECTION (object);
649 connection->finalizing = TRUE;
651 purge_all_signal_subscriptions (connection);
653 purge_all_filters (connection);
654 g_ptr_array_unref (connection->filters);
656 if (connection->authentication_observer != NULL)
657 g_object_unref (connection->authentication_observer);
659 if (connection->auth != NULL)
660 g_object_unref (connection->auth);
662 if (connection->credentials)
663 g_object_unref (connection->credentials);
665 if (connection->stream != NULL)
667 g_object_unref (connection->stream);
668 connection->stream = NULL;
671 g_free (connection->address);
673 g_free (connection->guid);
674 g_free (connection->bus_unique_name);
676 if (connection->initialization_error != NULL)
677 g_error_free (connection->initialization_error);
679 g_hash_table_unref (connection->map_method_serial_to_send_message_data);
681 g_hash_table_unref (connection->map_rule_to_signal_data);
682 g_hash_table_unref (connection->map_id_to_signal_data);
683 g_hash_table_unref (connection->map_sender_unique_name_to_signal_data_array);
685 g_hash_table_unref (connection->map_id_to_ei);
686 g_hash_table_unref (connection->map_object_path_to_eo);
687 g_hash_table_unref (connection->map_id_to_es);
688 g_hash_table_unref (connection->map_object_path_to_es);
690 g_hash_table_unref (connection->map_thread_to_last_serial);
692 g_main_context_unref (connection->main_context_at_construction);
694 g_free (connection->machine_id);
696 g_mutex_clear (&connection->init_lock);
697 g_mutex_clear (&connection->lock);
699 G_OBJECT_CLASS (g_dbus_connection_parent_class)->finalize (object);
702 /* called in any user thread, with the connection's lock not held */
704 g_dbus_connection_get_property (GObject *object,
709 GDBusConnection *connection = G_DBUS_CONNECTION (object);
714 g_value_set_object (value, g_dbus_connection_get_stream (connection));
718 g_value_set_string (value, g_dbus_connection_get_guid (connection));
721 case PROP_UNIQUE_NAME:
722 g_value_set_string (value, g_dbus_connection_get_unique_name (connection));
726 g_value_set_boolean (value, g_dbus_connection_is_closed (connection));
729 case PROP_EXIT_ON_CLOSE:
730 g_value_set_boolean (value, g_dbus_connection_get_exit_on_close (connection));
733 case PROP_CAPABILITY_FLAGS:
734 g_value_set_flags (value, g_dbus_connection_get_capabilities (connection));
738 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
743 /* called in any user thread, with the connection's lock not held */
745 g_dbus_connection_set_property (GObject *object,
750 GDBusConnection *connection = G_DBUS_CONNECTION (object);
755 connection->stream = g_value_dup_object (value);
759 connection->guid = g_value_dup_string (value);
763 connection->address = g_value_dup_string (value);
767 connection->flags = g_value_get_flags (value);
770 case PROP_EXIT_ON_CLOSE:
771 g_dbus_connection_set_exit_on_close (connection, g_value_get_boolean (value));
774 case PROP_AUTHENTICATION_OBSERVER:
775 connection->authentication_observer = g_value_dup_object (value);
779 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
784 /* Base-class implementation of GDBusConnection::closed.
786 * Called in a user thread, by the main context that was thread-default when
787 * the object was constructed.
790 g_dbus_connection_real_closed (GDBusConnection *connection,
791 gboolean remote_peer_vanished,
794 gint flags = g_atomic_int_get (&connection->atomic_flags);
796 /* Because atomic int access is a memory barrier, we can safely read
797 * initialization_error without a lock, as long as we do it afterwards.
799 if (remote_peer_vanished &&
800 (flags & FLAG_EXIT_ON_CLOSE) != 0 &&
801 (flags & FLAG_INITIALIZED) != 0 &&
802 connection->initialization_error == NULL)
806 g_print ("%s: Remote peer vanished with error: %s (%s, %d). Exiting.\n",
809 g_quark_to_string (error->domain), error->code);
813 g_print ("%s: Remote peer vanished. Exiting.\n", G_STRFUNC);
820 g_dbus_connection_class_init (GDBusConnectionClass *klass)
822 GObjectClass *gobject_class;
824 gobject_class = G_OBJECT_CLASS (klass);
826 gobject_class->finalize = g_dbus_connection_finalize;
827 gobject_class->dispose = g_dbus_connection_dispose;
828 gobject_class->set_property = g_dbus_connection_set_property;
829 gobject_class->get_property = g_dbus_connection_get_property;
831 klass->closed = g_dbus_connection_real_closed;
834 * GDBusConnection:stream:
836 * The underlying #GIOStream used for I/O.
838 * If this is passed on construction and is a #GSocketConnection,
839 * then the corresponding #GSocket will be put into non-blocking mode.
841 * While the #GDBusConnection is active, it will interact with this
842 * stream from a worker thread, so it is not safe to interact with
843 * the stream directly.
847 g_object_class_install_property (gobject_class,
849 g_param_spec_object ("stream",
851 P_("The underlying streams used for I/O"),
855 G_PARAM_CONSTRUCT_ONLY |
856 G_PARAM_STATIC_NAME |
857 G_PARAM_STATIC_BLURB |
858 G_PARAM_STATIC_NICK));
861 * GDBusConnection:address:
863 * A D-Bus address specifying potential endpoints that can be used
864 * when establishing the connection.
868 g_object_class_install_property (gobject_class,
870 g_param_spec_string ("address",
872 P_("D-Bus address specifying potential socket endpoints"),
875 G_PARAM_CONSTRUCT_ONLY |
876 G_PARAM_STATIC_NAME |
877 G_PARAM_STATIC_BLURB |
878 G_PARAM_STATIC_NICK));
881 * GDBusConnection:flags:
883 * Flags from the #GDBusConnectionFlags enumeration.
887 g_object_class_install_property (gobject_class,
889 g_param_spec_flags ("flags",
892 G_TYPE_DBUS_CONNECTION_FLAGS,
893 G_DBUS_CONNECTION_FLAGS_NONE,
895 G_PARAM_CONSTRUCT_ONLY |
896 G_PARAM_STATIC_NAME |
897 G_PARAM_STATIC_BLURB |
898 G_PARAM_STATIC_NICK));
901 * GDBusConnection:guid:
903 * The GUID of the peer performing the role of server when
906 * If you are constructing a #GDBusConnection and pass
907 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER in the
908 * #GDBusConnection:flags property then you MUST also set this
909 * property to a valid guid.
911 * If you are constructing a #GDBusConnection and pass
912 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT in the
913 * #GDBusConnection:flags property you will be able to read the GUID
914 * of the other peer here after the connection has been successfully
919 g_object_class_install_property (gobject_class,
921 g_param_spec_string ("guid",
923 P_("GUID of the server peer"),
927 G_PARAM_CONSTRUCT_ONLY |
928 G_PARAM_STATIC_NAME |
929 G_PARAM_STATIC_BLURB |
930 G_PARAM_STATIC_NICK));
933 * GDBusConnection:unique-name:
935 * The unique name as assigned by the message bus or %NULL if the
936 * connection is not open or not a message bus connection.
940 g_object_class_install_property (gobject_class,
942 g_param_spec_string ("unique-name",
944 P_("Unique name of bus connection"),
947 G_PARAM_STATIC_NAME |
948 G_PARAM_STATIC_BLURB |
949 G_PARAM_STATIC_NICK));
952 * GDBusConnection:closed:
954 * A boolean specifying whether the connection has been closed.
958 g_object_class_install_property (gobject_class,
960 g_param_spec_boolean ("closed",
962 P_("Whether the connection is closed"),
965 G_PARAM_STATIC_NAME |
966 G_PARAM_STATIC_BLURB |
967 G_PARAM_STATIC_NICK));
970 * GDBusConnection:exit-on-close:
972 * A boolean specifying whether the process will be terminated (by
973 * calling <literal>raise(SIGTERM)</literal>) if the connection
974 * is closed by the remote peer.
976 * Note that #GDBusConnection objects returned by g_bus_get_finish() and
977 * g_bus_get_sync() will (usually) have this property set to %TRUE.
981 g_object_class_install_property (gobject_class,
983 g_param_spec_boolean ("exit-on-close",
985 P_("Whether the process is terminated when the connection is closed"),
989 G_PARAM_STATIC_NAME |
990 G_PARAM_STATIC_BLURB |
991 G_PARAM_STATIC_NICK));
994 * GDBusConnection:capabilities:
996 * Flags from the #GDBusCapabilityFlags enumeration
997 * representing connection features negotiated with the other peer.
1001 g_object_class_install_property (gobject_class,
1002 PROP_CAPABILITY_FLAGS,
1003 g_param_spec_flags ("capabilities",
1006 G_TYPE_DBUS_CAPABILITY_FLAGS,
1007 G_DBUS_CAPABILITY_FLAGS_NONE,
1009 G_PARAM_STATIC_NAME |
1010 G_PARAM_STATIC_BLURB |
1011 G_PARAM_STATIC_NICK));
1014 * GDBusConnection:authentication-observer:
1016 * A #GDBusAuthObserver object to assist in the authentication process or %NULL.
1020 g_object_class_install_property (gobject_class,
1021 PROP_AUTHENTICATION_OBSERVER,
1022 g_param_spec_object ("authentication-observer",
1023 P_("Authentication Observer"),
1024 P_("Object used to assist in the authentication process"),
1025 G_TYPE_DBUS_AUTH_OBSERVER,
1027 G_PARAM_CONSTRUCT_ONLY |
1028 G_PARAM_STATIC_NAME |
1029 G_PARAM_STATIC_BLURB |
1030 G_PARAM_STATIC_NICK));
1033 * GDBusConnection::closed:
1034 * @connection: The #GDBusConnection emitting the signal.
1035 * @remote_peer_vanished: %TRUE if @connection is closed because the
1036 * remote peer closed its end of the connection.
1037 * @error: (allow-none): A #GError with more details about the event or %NULL.
1039 * Emitted when the connection is closed.
1041 * The cause of this event can be
1044 * If g_dbus_connection_close() is called. In this case
1045 * @remote_peer_vanished is set to %FALSE and @error is %NULL.
1046 * </para></listitem>
1048 * If the remote peer closes the connection. In this case
1049 * @remote_peer_vanished is set to %TRUE and @error is set.
1050 * </para></listitem>
1052 * If the remote peer sends invalid or malformed data. In this
1053 * case @remote_peer_vanished is set to %FALSE and @error
1055 * </para></listitem>
1058 * Upon receiving this signal, you should give up your reference to
1059 * @connection. You are guaranteed that this signal is emitted only
1064 signals[CLOSED_SIGNAL] = g_signal_new ("closed",
1065 G_TYPE_DBUS_CONNECTION,
1067 G_STRUCT_OFFSET (GDBusConnectionClass, closed),
1078 g_dbus_connection_init (GDBusConnection *connection)
1080 g_mutex_init (&connection->lock);
1081 g_mutex_init (&connection->init_lock);
1083 connection->map_method_serial_to_send_message_data = g_hash_table_new (g_direct_hash, g_direct_equal);
1085 connection->map_rule_to_signal_data = g_hash_table_new (g_str_hash,
1087 connection->map_id_to_signal_data = g_hash_table_new (g_direct_hash,
1089 connection->map_sender_unique_name_to_signal_data_array = g_hash_table_new_full (g_str_hash,
1092 (GDestroyNotify) g_ptr_array_unref);
1094 connection->map_object_path_to_eo = g_hash_table_new_full (g_str_hash,
1097 (GDestroyNotify) exported_object_free);
1099 connection->map_id_to_ei = g_hash_table_new (g_direct_hash,
1102 connection->map_object_path_to_es = g_hash_table_new_full (g_str_hash,
1105 (GDestroyNotify) exported_subtree_free);
1107 connection->map_id_to_es = g_hash_table_new (g_direct_hash,
1110 connection->map_thread_to_last_serial = g_hash_table_new (g_direct_hash,
1113 connection->main_context_at_construction = g_main_context_ref_thread_default ();
1115 connection->filters = g_ptr_array_new ();
1119 * g_dbus_connection_get_stream:
1120 * @connection: a #GDBusConnection
1122 * Gets the underlying stream used for IO.
1124 * While the #GDBusConnection is active, it will interact with this
1125 * stream from a worker thread, so it is not safe to interact with
1126 * the stream directly.
1128 * Returns: (transfer none): the stream used for IO
1133 g_dbus_connection_get_stream (GDBusConnection *connection)
1135 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
1137 /* do not use g_return_val_if_fail(), we want the memory barrier */
1138 if (!check_initialized (connection))
1141 return connection->stream;
1145 * g_dbus_connection_start_message_processing:
1146 * @connection: A #GDBusConnection.
1148 * If @connection was created with
1149 * %G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING, this method
1150 * starts processing messages. Does nothing on if @connection wasn't
1151 * created with this flag or if the method has already been called.
1156 g_dbus_connection_start_message_processing (GDBusConnection *connection)
1158 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1160 /* do not use g_return_val_if_fail(), we want the memory barrier */
1161 if (!check_initialized (connection))
1164 g_assert (connection->worker != NULL);
1165 _g_dbus_worker_unfreeze (connection->worker);
1169 * g_dbus_connection_is_closed:
1170 * @connection: A #GDBusConnection.
1172 * Gets whether @connection is closed.
1174 * Returns: %TRUE if the connection is closed, %FALSE otherwise.
1179 g_dbus_connection_is_closed (GDBusConnection *connection)
1183 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1185 flags = g_atomic_int_get (&connection->atomic_flags);
1187 return (flags & FLAG_CLOSED) ? TRUE : FALSE;
1191 * g_dbus_connection_get_capabilities:
1192 * @connection: A #GDBusConnection.
1194 * Gets the capabilities negotiated with the remote peer
1196 * Returns: Zero or more flags from the #GDBusCapabilityFlags enumeration.
1200 GDBusCapabilityFlags
1201 g_dbus_connection_get_capabilities (GDBusConnection *connection)
1203 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), G_DBUS_CAPABILITY_FLAGS_NONE);
1205 /* do not use g_return_val_if_fail(), we want the memory barrier */
1206 if (!check_initialized (connection))
1207 return G_DBUS_CAPABILITY_FLAGS_NONE;
1209 return connection->capabilities;
1212 /* ---------------------------------------------------------------------------------------------------- */
1214 /* Called in a temporary thread without holding locks. */
1216 flush_in_thread_func (GSimpleAsyncResult *res,
1218 GCancellable *cancellable)
1223 if (!g_dbus_connection_flush_sync (G_DBUS_CONNECTION (object),
1226 g_simple_async_result_take_error (res, error);
1230 * g_dbus_connection_flush:
1231 * @connection: A #GDBusConnection.
1232 * @cancellable: (allow-none): A #GCancellable or %NULL.
1233 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1234 * satisfied or %NULL if you don't care about the result.
1235 * @user_data: The data to pass to @callback.
1237 * Asynchronously flushes @connection, that is, writes all queued
1238 * outgoing message to the transport and then flushes the transport
1239 * (using g_output_stream_flush_async()). This is useful in programs
1240 * that wants to emit a D-Bus signal and then exit
1241 * immediately. Without flushing the connection, there is no guarantee
1242 * that the message has been sent to the networking buffers in the OS
1245 * This is an asynchronous method. When the operation is finished,
1246 * @callback will be invoked in the <link
1247 * linkend="g-main-context-push-thread-default">thread-default main
1248 * loop</link> of the thread you are calling this method from. You can
1249 * then call g_dbus_connection_flush_finish() to get the result of the
1250 * operation. See g_dbus_connection_flush_sync() for the synchronous
1256 g_dbus_connection_flush (GDBusConnection *connection,
1257 GCancellable *cancellable,
1258 GAsyncReadyCallback callback,
1261 GSimpleAsyncResult *simple;
1263 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1265 simple = g_simple_async_result_new (G_OBJECT (connection),
1268 g_dbus_connection_flush);
1269 g_simple_async_result_set_check_cancellable (simple, cancellable);
1270 g_simple_async_result_run_in_thread (simple,
1271 flush_in_thread_func,
1274 g_object_unref (simple);
1278 * g_dbus_connection_flush_finish:
1279 * @connection: A #GDBusConnection.
1280 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_flush().
1281 * @error: Return location for error or %NULL.
1283 * Finishes an operation started with g_dbus_connection_flush().
1285 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1290 g_dbus_connection_flush_finish (GDBusConnection *connection,
1294 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1299 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1300 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1301 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1303 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_flush);
1305 if (g_simple_async_result_propagate_error (simple, error))
1315 * g_dbus_connection_flush_sync:
1316 * @connection: A #GDBusConnection.
1317 * @cancellable: (allow-none): A #GCancellable or %NULL.
1318 * @error: Return location for error or %NULL.
1320 * Synchronously flushes @connection. The calling thread is blocked
1321 * until this is done. See g_dbus_connection_flush() for the
1322 * asynchronous version of this method and more details about what it
1325 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1330 g_dbus_connection_flush_sync (GDBusConnection *connection,
1331 GCancellable *cancellable,
1336 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1337 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1341 /* This is only a best-effort attempt to see whether the connection is
1342 * closed, so it doesn't need the lock. If the connection closes just
1343 * after this check, but before scheduling the flush operation, the
1344 * result will be more or less the same as if the connection closed while
1345 * the flush operation was pending - it'll fail with either CLOSED or
1348 if (!check_unclosed (connection, 0, error))
1351 g_assert (connection->worker != NULL);
1353 ret = _g_dbus_worker_flush_sync (connection->worker,
1361 /* ---------------------------------------------------------------------------------------------------- */
1365 GDBusConnection *connection;
1367 gboolean remote_peer_vanished;
1371 emit_closed_data_free (EmitClosedData *data)
1373 g_object_unref (data->connection);
1374 if (data->error != NULL)
1375 g_error_free (data->error);
1379 /* Called in a user thread that has acquired the main context that was
1380 * thread-default when the object was constructed
1383 emit_closed_in_idle (gpointer user_data)
1385 EmitClosedData *data = user_data;
1388 g_object_notify (G_OBJECT (data->connection), "closed");
1389 g_signal_emit (data->connection,
1390 signals[CLOSED_SIGNAL],
1392 data->remote_peer_vanished,
1398 /* Can be called from any thread, must hold lock.
1399 * FLAG_CLOSED must already have been set.
1402 schedule_closed_unlocked (GDBusConnection *connection,
1403 gboolean remote_peer_vanished,
1406 GSource *idle_source;
1407 EmitClosedData *data;
1409 CONNECTION_ENSURE_LOCK (connection);
1411 data = g_new0 (EmitClosedData, 1);
1412 data->connection = g_object_ref (connection);
1413 data->remote_peer_vanished = remote_peer_vanished;
1414 data->error = error != NULL ? g_error_copy (error) : NULL;
1416 idle_source = g_idle_source_new ();
1417 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1418 g_source_set_callback (idle_source,
1419 emit_closed_in_idle,
1421 (GDestroyNotify) emit_closed_data_free);
1422 g_source_attach (idle_source, connection->main_context_at_construction);
1423 g_source_unref (idle_source);
1426 /* ---------------------------------------------------------------------------------------------------- */
1429 * g_dbus_connection_close:
1430 * @connection: A #GDBusConnection.
1431 * @cancellable: (allow-none): A #GCancellable or %NULL.
1432 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
1433 * satisfied or %NULL if you don't care about the result.
1434 * @user_data: The data to pass to @callback.
1436 * Closes @connection. Note that this never causes the process to
1437 * exit (this might only happen if the other end of a shared message
1438 * bus connection disconnects, see #GDBusConnection:exit-on-close).
1440 * Once the connection is closed, operations such as sending a message
1441 * will return with the error %G_IO_ERROR_CLOSED. Closing a connection
1442 * will not automatically flush the connection so queued messages may
1443 * be lost. Use g_dbus_connection_flush() if you need such guarantees.
1445 * If @connection is already closed, this method fails with
1446 * %G_IO_ERROR_CLOSED.
1448 * When @connection has been closed, the #GDBusConnection::closed
1449 * signal is emitted in the <link
1450 * linkend="g-main-context-push-thread-default">thread-default main
1451 * loop</link> of the thread that @connection was constructed in.
1453 * This is an asynchronous method. When the operation is finished,
1454 * @callback will be invoked in the <link
1455 * linkend="g-main-context-push-thread-default">thread-default main
1456 * loop</link> of the thread you are calling this method from. You can
1457 * then call g_dbus_connection_close_finish() to get the result of the
1458 * operation. See g_dbus_connection_close_sync() for the synchronous
1464 g_dbus_connection_close (GDBusConnection *connection,
1465 GCancellable *cancellable,
1466 GAsyncReadyCallback callback,
1469 GSimpleAsyncResult *simple;
1471 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
1473 /* do not use g_return_val_if_fail(), we want the memory barrier */
1474 if (!check_initialized (connection))
1477 g_assert (connection->worker != NULL);
1479 simple = g_simple_async_result_new (G_OBJECT (connection),
1482 g_dbus_connection_close);
1483 g_simple_async_result_set_check_cancellable (simple, cancellable);
1484 _g_dbus_worker_close (connection->worker, cancellable, simple);
1485 g_object_unref (simple);
1489 * g_dbus_connection_close_finish:
1490 * @connection: A #GDBusConnection.
1491 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_close().
1492 * @error: Return location for error or %NULL.
1494 * Finishes an operation started with g_dbus_connection_close().
1496 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1501 g_dbus_connection_close_finish (GDBusConnection *connection,
1505 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
1510 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1511 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), FALSE);
1512 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1514 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_close);
1516 if (g_simple_async_result_propagate_error (simple, error))
1527 GAsyncResult *result;
1530 /* Can be called by any thread, without the connection lock */
1532 sync_close_cb (GObject *source_object,
1536 SyncCloseData *data = user_data;
1538 data->result = g_object_ref (res);
1539 g_main_loop_quit (data->loop);
1543 * g_dbus_connection_close_sync:
1544 * @connection: A #GDBusConnection.
1545 * @cancellable: (allow-none): A #GCancellable or %NULL.
1546 * @error: Return location for error or %NULL.
1548 * Synchronously closees @connection. The calling thread is blocked
1549 * until this is done. See g_dbus_connection_close() for the
1550 * asynchronous version of this method and more details about what it
1553 * Returns: %TRUE if the operation succeeded, %FALSE if @error is set.
1558 g_dbus_connection_close_sync (GDBusConnection *connection,
1559 GCancellable *cancellable,
1564 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1565 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1569 if (check_unclosed (connection, 0, error))
1571 GMainContext *context;
1574 context = g_main_context_new ();
1575 g_main_context_push_thread_default (context);
1576 data.loop = g_main_loop_new (context, TRUE);
1579 g_dbus_connection_close (connection, cancellable, sync_close_cb, &data);
1580 g_main_loop_run (data.loop);
1581 ret = g_dbus_connection_close_finish (connection, data.result, error);
1583 g_object_unref (data.result);
1584 g_main_loop_unref (data.loop);
1585 g_main_context_pop_thread_default (context);
1586 g_main_context_unref (context);
1592 /* ---------------------------------------------------------------------------------------------------- */
1595 * g_dbus_connection_get_last_serial:
1596 * @connection: A #GDBusConnection.
1598 * Retrieves the last serial number assigned to a #GDBusMessage on
1599 * the current thread. This includes messages sent via both low-level
1600 * API such as g_dbus_connection_send_message() as well as
1601 * high-level API such as g_dbus_connection_emit_signal(),
1602 * g_dbus_connection_call() or g_dbus_proxy_call().
1604 * Returns: the last used serial or zero when no message has been sent
1605 * within the current thread.
1610 g_dbus_connection_get_last_serial (GDBusConnection *connection)
1614 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
1616 CONNECTION_LOCK (connection);
1617 ret = GPOINTER_TO_UINT (g_hash_table_lookup (connection->map_thread_to_last_serial,
1619 CONNECTION_UNLOCK (connection);
1624 /* ---------------------------------------------------------------------------------------------------- */
1626 /* Can be called by any thread, with the connection lock held */
1628 g_dbus_connection_send_message_unlocked (GDBusConnection *connection,
1629 GDBusMessage *message,
1630 GDBusSendMessageFlags flags,
1631 volatile guint32 *out_serial,
1636 guint32 serial_to_use;
1639 CONNECTION_ENSURE_LOCK (connection);
1641 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1642 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1644 /* TODO: check all necessary headers are present */
1649 if (out_serial != NULL)
1652 /* If we're in initable_init(), don't check for being initialized, to avoid
1653 * chicken-and-egg problems. initable_init() is responsible for setting up
1654 * our prerequisites (mainly connection->worker), and only calling us
1655 * from its own thread (so no memory barrier is needed).
1657 if (!check_unclosed (connection,
1658 (flags & SEND_MESSAGE_FLAGS_INITIALIZING) ? MAY_BE_UNINITIALIZED : 0,
1662 blob = g_dbus_message_to_blob (message,
1664 connection->capabilities,
1669 if (flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL)
1670 serial_to_use = g_dbus_message_get_serial (message);
1672 serial_to_use = ++connection->last_serial; /* TODO: handle overflow */
1677 ((guint32 *) blob)[2] = GUINT32_TO_LE (serial_to_use);
1680 ((guint32 *) blob)[2] = GUINT32_TO_BE (serial_to_use);
1683 g_assert_not_reached ();
1688 g_printerr ("Writing message of %" G_GSIZE_FORMAT " bytes (serial %d) on %p:\n",
1689 blob_size, serial_to_use, connection);
1690 g_printerr ("----\n");
1691 hexdump (blob, blob_size);
1692 g_printerr ("----\n");
1695 /* TODO: use connection->auth to encode the blob */
1697 if (out_serial != NULL)
1698 *out_serial = serial_to_use;
1700 /* store used serial for the current thread */
1701 /* TODO: watch the thread disposal and remove associated record
1703 * - see https://bugzilla.gnome.org/show_bug.cgi?id=676825#c7
1705 g_hash_table_replace (connection->map_thread_to_last_serial,
1707 GUINT_TO_POINTER (serial_to_use));
1709 if (!(flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL))
1710 g_dbus_message_set_serial (message, serial_to_use);
1712 g_dbus_message_lock (message);
1713 _g_dbus_worker_send_message (connection->worker,
1717 blob = NULL; /* since _g_dbus_worker_send_message() steals the blob */
1728 * g_dbus_connection_send_message:
1729 * @connection: A #GDBusConnection.
1730 * @message: A #GDBusMessage
1731 * @flags: Flags affecting how the message is sent.
1732 * @out_serial: (out) (allow-none): Return location for serial number assigned
1733 * to @message when sending it or %NULL.
1734 * @error: Return location for error or %NULL.
1736 * Asynchronously sends @message to the peer represented by @connection.
1738 * Unless @flags contain the
1739 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
1740 * will be assigned by @connection and set on @message via
1741 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
1742 * serial number used will be written to this location prior to
1743 * submitting the message to the underlying transport.
1745 * If @connection is closed then the operation will fail with
1746 * %G_IO_ERROR_CLOSED. If @message is not well-formed,
1747 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
1749 * See <xref linkend="gdbus-server"/> and <xref
1750 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
1751 * low-level API to send and receive UNIX file descriptors.
1753 * Note that @message must be unlocked, unless @flags contain the
1754 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
1756 * Returns: %TRUE if the message was well-formed and queued for
1757 * transmission, %FALSE if @error is set.
1762 g_dbus_connection_send_message (GDBusConnection *connection,
1763 GDBusMessage *message,
1764 GDBusSendMessageFlags flags,
1765 volatile guint32 *out_serial,
1770 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
1771 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), FALSE);
1772 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), FALSE);
1773 g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
1775 CONNECTION_LOCK (connection);
1776 ret = g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, error);
1777 CONNECTION_UNLOCK (connection);
1781 /* ---------------------------------------------------------------------------------------------------- */
1785 volatile gint ref_count;
1786 GDBusConnection *connection;
1788 GSimpleAsyncResult *simple;
1790 GMainContext *main_context;
1792 GCancellable *cancellable;
1794 gulong cancellable_handler_id;
1796 GSource *timeout_source;
1801 /* Can be called from any thread with or without lock held */
1802 static SendMessageData *
1803 send_message_data_ref (SendMessageData *data)
1805 g_atomic_int_inc (&data->ref_count);
1809 /* Can be called from any thread with or without lock held */
1811 send_message_data_unref (SendMessageData *data)
1813 if (g_atomic_int_dec_and_test (&data->ref_count))
1815 g_assert (data->timeout_source == NULL);
1816 g_assert (data->simple == NULL);
1817 g_assert (data->cancellable_handler_id == 0);
1818 g_object_unref (data->connection);
1819 if (data->cancellable != NULL)
1820 g_object_unref (data->cancellable);
1821 g_main_context_unref (data->main_context);
1826 /* ---------------------------------------------------------------------------------------------------- */
1828 /* can be called from any thread with lock held - caller must have prepared GSimpleAsyncResult already */
1830 send_message_with_reply_deliver (SendMessageData *data, gboolean remove)
1832 CONNECTION_ENSURE_LOCK (data->connection);
1834 g_assert (!data->delivered);
1836 data->delivered = TRUE;
1838 g_simple_async_result_complete_in_idle (data->simple);
1839 g_object_unref (data->simple);
1840 data->simple = NULL;
1842 if (data->timeout_source != NULL)
1844 g_source_destroy (data->timeout_source);
1845 data->timeout_source = NULL;
1847 if (data->cancellable_handler_id > 0)
1849 g_cancellable_disconnect (data->cancellable, data->cancellable_handler_id);
1850 data->cancellable_handler_id = 0;
1855 g_warn_if_fail (g_hash_table_remove (data->connection->map_method_serial_to_send_message_data,
1856 GUINT_TO_POINTER (data->serial)));
1859 send_message_data_unref (data);
1862 /* ---------------------------------------------------------------------------------------------------- */
1864 /* Can be called from any thread with lock held */
1866 send_message_data_deliver_reply_unlocked (SendMessageData *data,
1867 GDBusMessage *reply)
1869 if (data->delivered)
1872 g_simple_async_result_set_op_res_gpointer (data->simple,
1873 g_object_ref (reply),
1876 send_message_with_reply_deliver (data, TRUE);
1882 /* ---------------------------------------------------------------------------------------------------- */
1884 /* Called from a user thread, lock is not held */
1886 send_message_with_reply_cancelled_idle_cb (gpointer user_data)
1888 SendMessageData *data = user_data;
1890 CONNECTION_LOCK (data->connection);
1891 if (data->delivered)
1894 g_simple_async_result_set_error (data->simple,
1896 G_IO_ERROR_CANCELLED,
1897 _("Operation was cancelled"));
1899 send_message_with_reply_deliver (data, TRUE);
1902 CONNECTION_UNLOCK (data->connection);
1906 /* Can be called from any thread with or without lock held */
1908 send_message_with_reply_cancelled_cb (GCancellable *cancellable,
1911 SendMessageData *data = user_data;
1912 GSource *idle_source;
1914 /* postpone cancellation to idle handler since we may be called directly
1915 * via g_cancellable_connect() (e.g. holding lock)
1917 idle_source = g_idle_source_new ();
1918 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
1919 g_source_set_callback (idle_source,
1920 send_message_with_reply_cancelled_idle_cb,
1921 send_message_data_ref (data),
1922 (GDestroyNotify) send_message_data_unref);
1923 g_source_attach (idle_source, data->main_context);
1924 g_source_unref (idle_source);
1927 /* ---------------------------------------------------------------------------------------------------- */
1929 /* Called from a user thread, lock is not held */
1931 send_message_with_reply_timeout_cb (gpointer user_data)
1933 SendMessageData *data = user_data;
1935 CONNECTION_LOCK (data->connection);
1936 if (data->delivered)
1939 g_simple_async_result_set_error (data->simple,
1941 G_IO_ERROR_TIMED_OUT,
1942 _("Timeout was reached"));
1944 send_message_with_reply_deliver (data, TRUE);
1947 CONNECTION_UNLOCK (data->connection);
1952 /* ---------------------------------------------------------------------------------------------------- */
1954 /* Called from a user thread, connection's lock is held */
1956 g_dbus_connection_send_message_with_reply_unlocked (GDBusConnection *connection,
1957 GDBusMessage *message,
1958 GDBusSendMessageFlags flags,
1960 volatile guint32 *out_serial,
1961 GCancellable *cancellable,
1962 GAsyncReadyCallback callback,
1965 GSimpleAsyncResult *simple;
1966 SendMessageData *data;
1968 volatile guint32 serial;
1972 if (out_serial == NULL)
1973 out_serial = &serial;
1975 if (timeout_msec == -1)
1976 timeout_msec = 25 * 1000;
1978 simple = g_simple_async_result_new (G_OBJECT (connection),
1981 g_dbus_connection_send_message_with_reply);
1982 g_simple_async_result_set_check_cancellable (simple, cancellable);
1984 if (g_cancellable_is_cancelled (cancellable))
1986 g_simple_async_result_set_error (simple,
1988 G_IO_ERROR_CANCELLED,
1989 _("Operation was cancelled"));
1990 g_simple_async_result_complete_in_idle (simple);
1991 g_object_unref (simple);
1996 if (!g_dbus_connection_send_message_unlocked (connection, message, flags, out_serial, &error))
1998 g_simple_async_result_take_error (simple, error);
1999 g_simple_async_result_complete_in_idle (simple);
2000 g_object_unref (simple);
2004 data = g_new0 (SendMessageData, 1);
2005 data->ref_count = 1;
2006 data->connection = g_object_ref (connection);
2007 data->simple = simple;
2008 data->serial = *out_serial;
2009 data->main_context = g_main_context_ref_thread_default ();
2011 if (cancellable != NULL)
2013 data->cancellable = g_object_ref (cancellable);
2014 data->cancellable_handler_id = g_cancellable_connect (cancellable,
2015 G_CALLBACK (send_message_with_reply_cancelled_cb),
2016 send_message_data_ref (data),
2017 (GDestroyNotify) send_message_data_unref);
2020 if (timeout_msec != G_MAXINT)
2022 data->timeout_source = g_timeout_source_new (timeout_msec);
2023 g_source_set_priority (data->timeout_source, G_PRIORITY_DEFAULT);
2024 g_source_set_callback (data->timeout_source,
2025 send_message_with_reply_timeout_cb,
2026 send_message_data_ref (data),
2027 (GDestroyNotify) send_message_data_unref);
2028 g_source_attach (data->timeout_source, data->main_context);
2029 g_source_unref (data->timeout_source);
2032 g_hash_table_insert (connection->map_method_serial_to_send_message_data,
2033 GUINT_TO_POINTER (*out_serial),
2041 * g_dbus_connection_send_message_with_reply:
2042 * @connection: A #GDBusConnection.
2043 * @message: A #GDBusMessage.
2044 * @flags: Flags affecting how the message is sent.
2045 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2046 * timeout or %G_MAXINT for no timeout.
2047 * @out_serial: (out) (allow-none): Return location for serial number assigned
2048 * to @message when sending it or %NULL.
2049 * @cancellable: (allow-none): A #GCancellable or %NULL.
2050 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
2051 * satisfied or %NULL if you don't care about the result.
2052 * @user_data: The data to pass to @callback.
2054 * Asynchronously sends @message to the peer represented by @connection.
2056 * Unless @flags contain the
2057 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2058 * will be assigned by @connection and set on @message via
2059 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2060 * serial number used will be written to this location prior to
2061 * submitting the message to the underlying transport.
2063 * If @connection is closed then the operation will fail with
2064 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2065 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2066 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2068 * This is an asynchronous method. When the operation is finished, @callback will be invoked
2069 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
2070 * of the thread you are calling this method from. You can then call
2071 * g_dbus_connection_send_message_with_reply_finish() to get the result of the operation.
2072 * See g_dbus_connection_send_message_with_reply_sync() for the synchronous version.
2074 * Note that @message must be unlocked, unless @flags contain the
2075 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2077 * See <xref linkend="gdbus-server"/> and <xref
2078 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2079 * low-level API to send and receive UNIX file descriptors.
2084 g_dbus_connection_send_message_with_reply (GDBusConnection *connection,
2085 GDBusMessage *message,
2086 GDBusSendMessageFlags flags,
2088 volatile guint32 *out_serial,
2089 GCancellable *cancellable,
2090 GAsyncReadyCallback callback,
2093 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
2094 g_return_if_fail (G_IS_DBUS_MESSAGE (message));
2095 g_return_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message));
2096 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
2098 CONNECTION_LOCK (connection);
2099 g_dbus_connection_send_message_with_reply_unlocked (connection,
2107 CONNECTION_UNLOCK (connection);
2111 * g_dbus_connection_send_message_with_reply_finish:
2112 * @connection: a #GDBusConnection
2113 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_send_message_with_reply().
2114 * @error: Return location for error or %NULL.
2116 * Finishes an operation started with g_dbus_connection_send_message_with_reply().
2118 * Note that @error is only set if a local in-process error
2119 * occurred. That is to say that the returned #GDBusMessage object may
2120 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2121 * g_dbus_message_to_gerror() to transcode this to a #GError.
2123 * See <xref linkend="gdbus-server"/> and <xref
2124 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2125 * low-level API to send and receive UNIX file descriptors.
2127 * Returns: (transfer full): A locked #GDBusMessage or %NULL if @error is set.
2132 g_dbus_connection_send_message_with_reply_finish (GDBusConnection *connection,
2136 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
2137 GDBusMessage *reply;
2139 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2140 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2144 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_dbus_connection_send_message_with_reply);
2146 if (g_simple_async_result_propagate_error (simple, error))
2149 reply = g_object_ref (g_simple_async_result_get_op_res_gpointer (simple));
2155 /* ---------------------------------------------------------------------------------------------------- */
2160 GMainContext *context;
2162 } SendMessageSyncData;
2164 /* Called from a user thread, lock is not held */
2166 send_message_with_reply_sync_cb (GDBusConnection *connection,
2170 SendMessageSyncData *data = user_data;
2171 data->res = g_object_ref (res);
2172 g_main_loop_quit (data->loop);
2176 * g_dbus_connection_send_message_with_reply_sync:
2177 * @connection: A #GDBusConnection.
2178 * @message: A #GDBusMessage.
2179 * @flags: Flags affecting how the message is sent.
2180 * @timeout_msec: The timeout in milliseconds, -1 to use the default
2181 * timeout or %G_MAXINT for no timeout.
2182 * @out_serial: (out) (allow-none): Return location for serial number assigned
2183 * to @message when sending it or %NULL.
2184 * @cancellable: (allow-none): A #GCancellable or %NULL.
2185 * @error: Return location for error or %NULL.
2187 * Synchronously sends @message to the peer represented by @connection
2188 * and blocks the calling thread until a reply is received or the
2189 * timeout is reached. See g_dbus_connection_send_message_with_reply()
2190 * for the asynchronous version of this method.
2192 * Unless @flags contain the
2193 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag, the serial number
2194 * will be assigned by @connection and set on @message via
2195 * g_dbus_message_set_serial(). If @out_serial is not %NULL, then the
2196 * serial number used will be written to this location prior to
2197 * submitting the message to the underlying transport.
2199 * If @connection is closed then the operation will fail with
2200 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
2201 * fail with %G_IO_ERROR_CANCELLED. If @message is not well-formed,
2202 * the operation fails with %G_IO_ERROR_INVALID_ARGUMENT.
2204 * Note that @error is only set if a local in-process error
2205 * occurred. That is to say that the returned #GDBusMessage object may
2206 * be of type %G_DBUS_MESSAGE_TYPE_ERROR. Use
2207 * g_dbus_message_to_gerror() to transcode this to a #GError.
2209 * See <xref linkend="gdbus-server"/> and <xref
2210 * linkend="gdbus-unix-fd-client"/> for an example of how to use this
2211 * low-level API to send and receive UNIX file descriptors.
2213 * Note that @message must be unlocked, unless @flags contain the
2214 * %G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL flag.
2216 * Returns: (transfer full): A locked #GDBusMessage that is the reply to @message or %NULL if @error is set.
2221 g_dbus_connection_send_message_with_reply_sync (GDBusConnection *connection,
2222 GDBusMessage *message,
2223 GDBusSendMessageFlags flags,
2225 volatile guint32 *out_serial,
2226 GCancellable *cancellable,
2229 SendMessageSyncData *data;
2230 GDBusMessage *reply;
2232 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
2233 g_return_val_if_fail (G_IS_DBUS_MESSAGE (message), NULL);
2234 g_return_val_if_fail ((flags & G_DBUS_SEND_MESSAGE_FLAGS_PRESERVE_SERIAL) || !g_dbus_message_get_locked (message), NULL);
2235 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
2236 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2238 data = g_new0 (SendMessageSyncData, 1);
2239 data->context = g_main_context_new ();
2240 data->loop = g_main_loop_new (data->context, FALSE);
2242 g_main_context_push_thread_default (data->context);
2244 g_dbus_connection_send_message_with_reply (connection,
2250 (GAsyncReadyCallback) send_message_with_reply_sync_cb,
2252 g_main_loop_run (data->loop);
2253 reply = g_dbus_connection_send_message_with_reply_finish (connection,
2257 g_main_context_pop_thread_default (data->context);
2259 g_main_context_unref (data->context);
2260 g_main_loop_unref (data->loop);
2261 g_object_unref (data->res);
2267 /* ---------------------------------------------------------------------------------------------------- */
2271 GDBusMessageFilterFunction func;
2278 GDBusMessageFilterFunction filter_function;
2280 GDestroyNotify user_data_free_func;
2283 /* Called in GDBusWorker's thread - we must not block - with no lock held */
2285 on_worker_message_received (GDBusWorker *worker,
2286 GDBusMessage *message,
2289 GDBusConnection *connection;
2290 FilterCallback *filters;
2295 G_LOCK (message_bus_lock);
2296 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2299 G_UNLOCK (message_bus_lock);
2302 connection = G_DBUS_CONNECTION (user_data);
2303 g_object_ref (connection);
2304 G_UNLOCK (message_bus_lock);
2306 //g_debug ("in on_worker_message_received");
2308 g_object_ref (message);
2309 g_dbus_message_lock (message);
2311 //g_debug ("boo ref_count = %d %p %p", G_OBJECT (connection)->ref_count, connection, connection->worker);
2313 /* First collect the set of callback functions */
2314 CONNECTION_LOCK (connection);
2315 num_filters = connection->filters->len;
2316 filters = g_new0 (FilterCallback, num_filters);
2317 for (n = 0; n < num_filters; n++)
2319 FilterData *data = connection->filters->pdata[n];
2320 filters[n].func = data->filter_function;
2321 filters[n].user_data = data->user_data;
2323 CONNECTION_UNLOCK (connection);
2325 /* then call the filters in order (without holding the lock) */
2326 for (n = 0; n < num_filters; n++)
2328 message = filters[n].func (connection,
2331 filters[n].user_data);
2332 if (message == NULL)
2334 g_dbus_message_lock (message);
2337 /* Standard dispatch unless the filter ate the message - no need to
2338 * do anything if the message was altered
2340 if (message != NULL)
2342 GDBusMessageType message_type;
2344 message_type = g_dbus_message_get_message_type (message);
2345 if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_RETURN || message_type == G_DBUS_MESSAGE_TYPE_ERROR)
2347 guint32 reply_serial;
2348 SendMessageData *send_message_data;
2350 reply_serial = g_dbus_message_get_reply_serial (message);
2351 CONNECTION_LOCK (connection);
2352 send_message_data = g_hash_table_lookup (connection->map_method_serial_to_send_message_data,
2353 GUINT_TO_POINTER (reply_serial));
2354 if (send_message_data != NULL)
2356 //g_debug ("delivering reply/error for serial %d for %p", reply_serial, connection);
2357 send_message_data_deliver_reply_unlocked (send_message_data, message);
2361 //g_debug ("message reply/error for serial %d but no SendMessageData found for %p", reply_serial, connection);
2363 CONNECTION_UNLOCK (connection);
2365 else if (message_type == G_DBUS_MESSAGE_TYPE_SIGNAL)
2367 CONNECTION_LOCK (connection);
2368 distribute_signals (connection, message);
2369 CONNECTION_UNLOCK (connection);
2371 else if (message_type == G_DBUS_MESSAGE_TYPE_METHOD_CALL)
2373 CONNECTION_LOCK (connection);
2374 distribute_method_call (connection, message);
2375 CONNECTION_UNLOCK (connection);
2379 if (message != NULL)
2380 g_object_unref (message);
2381 g_object_unref (connection);
2385 /* Called in GDBusWorker's thread, lock is not held */
2386 static GDBusMessage *
2387 on_worker_message_about_to_be_sent (GDBusWorker *worker,
2388 GDBusMessage *message,
2391 GDBusConnection *connection;
2392 FilterCallback *filters;
2397 G_LOCK (message_bus_lock);
2398 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2401 G_UNLOCK (message_bus_lock);
2404 connection = G_DBUS_CONNECTION (user_data);
2405 g_object_ref (connection);
2406 G_UNLOCK (message_bus_lock);
2408 //g_debug ("in on_worker_message_about_to_be_sent");
2410 /* First collect the set of callback functions */
2411 CONNECTION_LOCK (connection);
2412 num_filters = connection->filters->len;
2413 filters = g_new0 (FilterCallback, num_filters);
2414 for (n = 0; n < num_filters; n++)
2416 FilterData *data = connection->filters->pdata[n];
2417 filters[n].func = data->filter_function;
2418 filters[n].user_data = data->user_data;
2420 CONNECTION_UNLOCK (connection);
2422 /* then call the filters in order (without holding the lock) */
2423 for (n = 0; n < num_filters; n++)
2425 g_dbus_message_lock (message);
2426 message = filters[n].func (connection,
2429 filters[n].user_data);
2430 if (message == NULL)
2434 g_object_unref (connection);
2440 /* called with connection lock held, in GDBusWorker thread */
2442 cancel_method_on_close (gpointer key, gpointer value, gpointer user_data)
2444 SendMessageData *data = value;
2446 if (data->delivered)
2449 g_simple_async_result_set_error (data->simple,
2452 _("The connection is closed"));
2454 /* Ask send_message_with_reply_deliver not to remove the element from the
2455 * hash table - we're in the middle of a foreach; that would be unsafe.
2456 * Instead, return TRUE from this function so that it gets removed safely.
2458 send_message_with_reply_deliver (data, FALSE);
2462 /* Called in GDBusWorker's thread - we must not block - without lock held */
2464 on_worker_closed (GDBusWorker *worker,
2465 gboolean remote_peer_vanished,
2469 GDBusConnection *connection;
2471 guint old_atomic_flags;
2473 G_LOCK (message_bus_lock);
2474 alive = (g_hash_table_lookup (alive_connections, user_data) != NULL);
2477 G_UNLOCK (message_bus_lock);
2480 connection = G_DBUS_CONNECTION (user_data);
2481 g_object_ref (connection);
2482 G_UNLOCK (message_bus_lock);
2484 //g_debug ("in on_worker_closed: %s", error->message);
2486 CONNECTION_LOCK (connection);
2487 /* Even though this is atomic, we do it inside the lock to avoid breaking
2488 * assumptions in remove_match_rule(). We'd need the lock in a moment
2489 * anyway, so, no loss.
2491 old_atomic_flags = g_atomic_int_or (&connection->atomic_flags, FLAG_CLOSED);
2493 if (!(old_atomic_flags & FLAG_CLOSED))
2495 g_hash_table_foreach_remove (connection->map_method_serial_to_send_message_data, cancel_method_on_close, NULL);
2496 schedule_closed_unlocked (connection, remote_peer_vanished, error);
2498 CONNECTION_UNLOCK (connection);
2500 g_object_unref (connection);
2503 /* ---------------------------------------------------------------------------------------------------- */
2505 /* Determines the biggest set of capabilities we can support on this
2508 * Called with the init_lock held.
2510 static GDBusCapabilityFlags
2511 get_offered_capabilities_max (GDBusConnection *connection)
2513 GDBusCapabilityFlags ret;
2514 ret = G_DBUS_CAPABILITY_FLAGS_NONE;
2516 if (G_IS_UNIX_CONNECTION (connection->stream))
2517 ret |= G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING;
2522 /* Called in a user thread, lock is not held */
2524 initable_init (GInitable *initable,
2525 GCancellable *cancellable,
2528 GDBusConnection *connection = G_DBUS_CONNECTION (initable);
2531 /* This method needs to be idempotent to work with the singleton
2532 * pattern. See the docs for g_initable_init(). We implement this by
2535 * Unfortunately we can't use the main lock since the on_worker_*()
2536 * callbacks above needs the lock during initialization (for message
2537 * bus connections we do a synchronous Hello() call on the bus).
2539 g_mutex_lock (&connection->init_lock);
2543 /* Make this a no-op if we're already initialized (successfully or
2546 if ((g_atomic_int_get (&connection->atomic_flags) & FLAG_INITIALIZED))
2548 ret = (connection->initialization_error == NULL);
2552 /* Because of init_lock, we can't get here twice in different threads */
2553 g_assert (connection->initialization_error == NULL);
2555 /* The user can pass multiple (but mutally exclusive) construct
2558 * - stream (of type GIOStream)
2559 * - address (of type gchar*)
2561 * At the end of the day we end up with a non-NULL GIOStream
2562 * object in connection->stream.
2564 if (connection->address != NULL)
2566 g_assert (connection->stream == NULL);
2568 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER) ||
2569 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS))
2571 g_set_error_literal (&connection->initialization_error,
2573 G_IO_ERROR_INVALID_ARGUMENT,
2574 _("Unsupported flags encountered when constructing a client-side connection"));
2578 connection->stream = g_dbus_address_get_stream_sync (connection->address,
2579 NULL, /* TODO: out_guid */
2581 &connection->initialization_error);
2582 if (connection->stream == NULL)
2585 else if (connection->stream != NULL)
2591 g_assert_not_reached ();
2594 /* Authenticate the connection */
2595 if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER)
2597 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT));
2598 g_assert (connection->guid != NULL);
2599 connection->auth = _g_dbus_auth_new (connection->stream);
2600 if (!_g_dbus_auth_run_server (connection->auth,
2601 connection->authentication_observer,
2603 (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS),
2604 get_offered_capabilities_max (connection),
2605 &connection->capabilities,
2606 &connection->credentials,
2608 &connection->initialization_error))
2611 else if (connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT)
2613 g_assert (!(connection->flags & G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER));
2614 g_assert (connection->guid == NULL);
2615 connection->auth = _g_dbus_auth_new (connection->stream);
2616 connection->guid = _g_dbus_auth_run_client (connection->auth,
2617 connection->authentication_observer,
2618 get_offered_capabilities_max (connection),
2619 &connection->capabilities,
2621 &connection->initialization_error);
2622 if (connection->guid == NULL)
2626 if (connection->authentication_observer != NULL)
2628 g_object_unref (connection->authentication_observer);
2629 connection->authentication_observer = NULL;
2632 //g_output_stream_flush (G_SOCKET_CONNECTION (connection->stream)
2634 //g_debug ("haz unix fd passing powers: %d", connection->capabilities & G_DBUS_CAPABILITY_FLAGS_UNIX_FD_PASSING);
2637 /* We want all IO operations to be non-blocking since they happen in
2638 * the worker thread which is shared by _all_ connections.
2640 if (G_IS_SOCKET_CONNECTION (connection->stream))
2642 g_socket_set_blocking (g_socket_connection_get_socket (G_SOCKET_CONNECTION (connection->stream)), FALSE);
2646 G_LOCK (message_bus_lock);
2647 if (alive_connections == NULL)
2648 alive_connections = g_hash_table_new (g_direct_hash, g_direct_equal);
2649 g_hash_table_insert (alive_connections, connection, connection);
2650 G_UNLOCK (message_bus_lock);
2652 connection->worker = _g_dbus_worker_new (connection->stream,
2653 connection->capabilities,
2654 ((connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING) != 0),
2655 on_worker_message_received,
2656 on_worker_message_about_to_be_sent,
2660 /* if a bus connection, call org.freedesktop.DBus.Hello - this is how we're getting a name */
2661 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
2663 GVariant *hello_result;
2665 /* we could lift this restriction by adding code in gdbusprivate.c */
2666 if (connection->flags & G_DBUS_CONNECTION_FLAGS_DELAY_MESSAGE_PROCESSING)
2668 g_set_error_literal (&connection->initialization_error,
2671 "Cannot use DELAY_MESSAGE_PROCESSING with MESSAGE_BUS_CONNECTION");
2675 hello_result = g_dbus_connection_call_sync (connection,
2676 "org.freedesktop.DBus", /* name */
2677 "/org/freedesktop/DBus", /* path */
2678 "org.freedesktop.DBus", /* interface */
2680 NULL, /* parameters */
2681 G_VARIANT_TYPE ("(s)"),
2682 CALL_FLAGS_INITIALIZING,
2684 NULL, /* TODO: cancellable */
2685 &connection->initialization_error);
2686 if (hello_result == NULL)
2689 g_variant_get (hello_result, "(s)", &connection->bus_unique_name);
2690 g_variant_unref (hello_result);
2691 //g_debug ("unique name is '%s'", connection->bus_unique_name);
2698 g_assert (connection->initialization_error != NULL);
2699 g_propagate_error (error, g_error_copy (connection->initialization_error));
2702 g_atomic_int_or (&connection->atomic_flags, FLAG_INITIALIZED);
2703 g_mutex_unlock (&connection->init_lock);
2709 initable_iface_init (GInitableIface *initable_iface)
2711 initable_iface->init = initable_init;
2714 /* ---------------------------------------------------------------------------------------------------- */
2717 async_initable_iface_init (GAsyncInitableIface *async_initable_iface)
2722 /* ---------------------------------------------------------------------------------------------------- */
2725 * g_dbus_connection_new:
2726 * @stream: A #GIOStream.
2727 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2728 * @flags: Flags describing how to make the connection.
2729 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2730 * @cancellable: (allow-none): A #GCancellable or %NULL.
2731 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2732 * @user_data: The data to pass to @callback.
2734 * Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
2735 * with the end represented by @stream.
2737 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2738 * will be put into non-blocking mode.
2740 * The D-Bus connection will interact with @stream from a worker thread.
2741 * As a result, the caller should not interact with @stream after this
2742 * method has been called, except by calling g_object_unref() on it.
2744 * If @observer is not %NULL it may be used to control the
2745 * authentication process.
2747 * When the operation is finished, @callback will be invoked. You can
2748 * then call g_dbus_connection_new_finish() to get the result of the
2751 * This is a asynchronous failable constructor. See
2752 * g_dbus_connection_new_sync() for the synchronous
2758 g_dbus_connection_new (GIOStream *stream,
2760 GDBusConnectionFlags flags,
2761 GDBusAuthObserver *observer,
2762 GCancellable *cancellable,
2763 GAsyncReadyCallback callback,
2766 g_return_if_fail (G_IS_IO_STREAM (stream));
2767 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2775 "authentication-observer", observer,
2780 * g_dbus_connection_new_finish:
2781 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2782 * @error: Return location for error or %NULL.
2784 * Finishes an operation started with g_dbus_connection_new().
2786 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2791 g_dbus_connection_new_finish (GAsyncResult *res,
2795 GObject *source_object;
2797 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2798 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2800 source_object = g_async_result_get_source_object (res);
2801 g_assert (source_object != NULL);
2802 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2805 g_object_unref (source_object);
2807 return G_DBUS_CONNECTION (object);
2813 * g_dbus_connection_new_sync:
2814 * @stream: A #GIOStream.
2815 * @guid: (allow-none): The GUID to use if a authenticating as a server or %NULL.
2816 * @flags: Flags describing how to make the connection.
2817 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2818 * @cancellable: (allow-none): A #GCancellable or %NULL.
2819 * @error: Return location for error or %NULL.
2821 * Synchronously sets up a D-Bus connection for exchanging D-Bus messages
2822 * with the end represented by @stream.
2824 * If @stream is a #GSocketConnection, then the corresponding #GSocket
2825 * will be put into non-blocking mode.
2827 * The D-Bus connection will interact with @stream from a worker thread.
2828 * As a result, the caller should not interact with @stream after this
2829 * method has been called, except by calling g_object_unref() on it.
2831 * If @observer is not %NULL it may be used to control the
2832 * authentication process.
2834 * This is a synchronous failable constructor. See
2835 * g_dbus_connection_new() for the asynchronous version.
2837 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2842 g_dbus_connection_new_sync (GIOStream *stream,
2844 GDBusConnectionFlags flags,
2845 GDBusAuthObserver *observer,
2846 GCancellable *cancellable,
2849 g_return_val_if_fail (G_IS_IO_STREAM (stream), NULL);
2850 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2851 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2857 "authentication-observer", observer,
2861 /* ---------------------------------------------------------------------------------------------------- */
2864 * g_dbus_connection_new_for_address:
2865 * @address: A D-Bus address.
2866 * @flags: Flags describing how to make the connection.
2867 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2868 * @cancellable: (allow-none): A #GCancellable or %NULL.
2869 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
2870 * @user_data: The data to pass to @callback.
2872 * Asynchronously connects and sets up a D-Bus client connection for
2873 * exchanging D-Bus messages with an endpoint specified by @address
2874 * which must be in the D-Bus address format.
2876 * This constructor can only be used to initiate client-side
2877 * connections - use g_dbus_connection_new() if you need to act as the
2878 * server. In particular, @flags cannot contain the
2879 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2880 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2882 * When the operation is finished, @callback will be invoked. You can
2883 * then call g_dbus_connection_new_finish() to get the result of the
2886 * If @observer is not %NULL it may be used to control the
2887 * authentication process.
2889 * This is a asynchronous failable constructor. See
2890 * g_dbus_connection_new_for_address_sync() for the synchronous
2896 g_dbus_connection_new_for_address (const gchar *address,
2897 GDBusConnectionFlags flags,
2898 GDBusAuthObserver *observer,
2899 GCancellable *cancellable,
2900 GAsyncReadyCallback callback,
2903 g_return_if_fail (address != NULL);
2904 g_async_initable_new_async (G_TYPE_DBUS_CONNECTION,
2911 "authentication-observer", observer,
2916 * g_dbus_connection_new_for_address_finish:
2917 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_new().
2918 * @error: Return location for error or %NULL.
2920 * Finishes an operation started with g_dbus_connection_new_for_address().
2922 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2927 g_dbus_connection_new_for_address_finish (GAsyncResult *res,
2931 GObject *source_object;
2933 g_return_val_if_fail (G_IS_ASYNC_RESULT (res), NULL);
2934 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2936 source_object = g_async_result_get_source_object (res);
2937 g_assert (source_object != NULL);
2938 object = g_async_initable_new_finish (G_ASYNC_INITABLE (source_object),
2941 g_object_unref (source_object);
2943 return G_DBUS_CONNECTION (object);
2949 * g_dbus_connection_new_for_address_sync:
2950 * @address: A D-Bus address.
2951 * @flags: Flags describing how to make the connection.
2952 * @observer: (allow-none): A #GDBusAuthObserver or %NULL.
2953 * @cancellable: (allow-none): A #GCancellable or %NULL.
2954 * @error: Return location for error or %NULL.
2956 * Synchronously connects and sets up a D-Bus client connection for
2957 * exchanging D-Bus messages with an endpoint specified by @address
2958 * which must be in the D-Bus address format.
2960 * This constructor can only be used to initiate client-side
2961 * connections - use g_dbus_connection_new_sync() if you need to act
2962 * as the server. In particular, @flags cannot contain the
2963 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER or
2964 * %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_ALLOW_ANONYMOUS flags.
2966 * This is a synchronous failable constructor. See
2967 * g_dbus_connection_new_for_address() for the asynchronous version.
2969 * If @observer is not %NULL it may be used to control the
2970 * authentication process.
2972 * Returns: A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
2977 g_dbus_connection_new_for_address_sync (const gchar *address,
2978 GDBusConnectionFlags flags,
2979 GDBusAuthObserver *observer,
2980 GCancellable *cancellable,
2983 g_return_val_if_fail (address != NULL, NULL);
2984 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
2985 return g_initable_new (G_TYPE_DBUS_CONNECTION,
2990 "authentication-observer", observer,
2994 /* ---------------------------------------------------------------------------------------------------- */
2997 * g_dbus_connection_set_exit_on_close:
2998 * @connection: A #GDBusConnection.
2999 * @exit_on_close: Whether the process should be terminated
3000 * when @connection is closed by the remote peer.
3002 * Sets whether the process should be terminated when @connection is
3003 * closed by the remote peer. See #GDBusConnection:exit-on-close for
3006 * Note that this function should be used with care. Most modern UNIX
3007 * desktops tie the notion of a user session the session bus, and expect
3008 * all of a users applications to quit when their bus connection goes away.
3009 * If you are setting @exit_on_close to %FALSE for the shared session
3010 * bus connection, you should make sure that your application exits
3011 * when the user session ends.
3016 g_dbus_connection_set_exit_on_close (GDBusConnection *connection,
3017 gboolean exit_on_close)
3019 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3022 g_atomic_int_or (&connection->atomic_flags, FLAG_EXIT_ON_CLOSE);
3024 g_atomic_int_and (&connection->atomic_flags, ~FLAG_EXIT_ON_CLOSE);
3029 * g_dbus_connection_get_exit_on_close:
3030 * @connection: A #GDBusConnection.
3032 * Gets whether the process is terminated when @connection is
3033 * closed by the remote peer. See
3034 * #GDBusConnection:exit-on-close for more details.
3036 * Returns: Whether the process is terminated when @connection is
3037 * closed by the remote peer.
3042 g_dbus_connection_get_exit_on_close (GDBusConnection *connection)
3044 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
3046 if (g_atomic_int_get (&connection->atomic_flags) & FLAG_EXIT_ON_CLOSE)
3053 * g_dbus_connection_get_guid:
3054 * @connection: A #GDBusConnection.
3056 * The GUID of the peer performing the role of server when
3057 * authenticating. See #GDBusConnection:guid for more details.
3059 * Returns: The GUID. Do not free this string, it is owned by
3065 g_dbus_connection_get_guid (GDBusConnection *connection)
3067 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3068 return connection->guid;
3072 * g_dbus_connection_get_unique_name:
3073 * @connection: A #GDBusConnection.
3075 * Gets the unique name of @connection as assigned by the message
3076 * bus. This can also be used to figure out if @connection is a
3077 * message bus connection.
3079 * Returns: The unique name or %NULL if @connection is not a message
3080 * bus connection. Do not free this string, it is owned by
3086 g_dbus_connection_get_unique_name (GDBusConnection *connection)
3088 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3090 /* do not use g_return_val_if_fail(), we want the memory barrier */
3091 if (!check_initialized (connection))
3094 return connection->bus_unique_name;
3098 * g_dbus_connection_get_peer_credentials:
3099 * @connection: A #GDBusConnection.
3101 * Gets the credentials of the authenticated peer. This will always
3102 * return %NULL unless @connection acted as a server
3103 * (e.g. %G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_SERVER was passed)
3104 * when set up and the client passed credentials as part of the
3105 * authentication process.
3107 * In a message bus setup, the message bus is always the server and
3108 * each application is a client. So this method will always return
3109 * %NULL for message bus clients.
3111 * Returns: (transfer none): A #GCredentials or %NULL if not available. Do not free
3112 * this object, it is owned by @connection.
3117 g_dbus_connection_get_peer_credentials (GDBusConnection *connection)
3119 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
3121 /* do not use g_return_val_if_fail(), we want the memory barrier */
3122 if (!check_initialized (connection))
3125 return connection->credentials;
3128 /* ---------------------------------------------------------------------------------------------------- */
3130 static guint _global_filter_id = 1;
3133 * g_dbus_connection_add_filter:
3134 * @connection: A #GDBusConnection.
3135 * @filter_function: A filter function.
3136 * @user_data: User data to pass to @filter_function.
3137 * @user_data_free_func: Function to free @user_data with when filter
3138 * is removed or %NULL.
3140 * Adds a message filter. Filters are handlers that are run on all
3141 * incoming and outgoing messages, prior to standard dispatch. Filters
3142 * are run in the order that they were added. The same handler can be
3143 * added as a filter more than once, in which case it will be run more
3144 * than once. Filters added during a filter callback won't be run on
3145 * the message being processed. Filter functions are allowed to modify
3146 * and even drop messages.
3148 * Note that filters are run in a dedicated message handling thread so
3149 * they can't block and, generally, can't do anything but signal a
3150 * worker thread. Also note that filters are rarely needed - use API
3151 * such as g_dbus_connection_send_message_with_reply(),
3152 * g_dbus_connection_signal_subscribe() or g_dbus_connection_call() instead.
3154 * If a filter consumes an incoming message the message is not
3155 * dispatched anywhere else - not even the standard dispatch machinery
3156 * (that API such as g_dbus_connection_signal_subscribe() and
3157 * g_dbus_connection_send_message_with_reply() relies on) will see the
3158 * message. Similary, if a filter consumes an outgoing message, the
3159 * message will not be sent to the other peer.
3161 * Returns: A filter identifier that can be used with
3162 * g_dbus_connection_remove_filter().
3167 g_dbus_connection_add_filter (GDBusConnection *connection,
3168 GDBusMessageFilterFunction filter_function,
3170 GDestroyNotify user_data_free_func)
3174 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3175 g_return_val_if_fail (filter_function != NULL, 0);
3176 g_return_val_if_fail (check_initialized (connection), 0);
3178 CONNECTION_LOCK (connection);
3179 data = g_new0 (FilterData, 1);
3180 data->id = _global_filter_id++; /* TODO: overflow etc. */
3181 data->filter_function = filter_function;
3182 data->user_data = user_data;
3183 data->user_data_free_func = user_data_free_func;
3184 g_ptr_array_add (connection->filters, data);
3185 CONNECTION_UNLOCK (connection);
3190 /* only called from finalize(), removes all filters */
3192 purge_all_filters (GDBusConnection *connection)
3195 for (n = 0; n < connection->filters->len; n++)
3197 FilterData *data = connection->filters->pdata[n];
3198 if (data->user_data_free_func != NULL)
3199 data->user_data_free_func (data->user_data);
3205 * g_dbus_connection_remove_filter:
3206 * @connection: a #GDBusConnection
3207 * @filter_id: an identifier obtained from g_dbus_connection_add_filter()
3214 g_dbus_connection_remove_filter (GDBusConnection *connection,
3218 FilterData *to_destroy;
3220 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3221 g_return_if_fail (check_initialized (connection));
3223 CONNECTION_LOCK (connection);
3225 for (n = 0; n < connection->filters->len; n++)
3227 FilterData *data = connection->filters->pdata[n];
3228 if (data->id == filter_id)
3230 g_ptr_array_remove_index (connection->filters, n);
3235 CONNECTION_UNLOCK (connection);
3237 /* do free without holding lock */
3238 if (to_destroy != NULL)
3240 if (to_destroy->user_data_free_func != NULL)
3241 to_destroy->user_data_free_func (to_destroy->user_data);
3242 g_free (to_destroy);
3246 g_warning ("g_dbus_connection_remove_filter: No filter found for filter_id %d", filter_id);
3250 /* ---------------------------------------------------------------------------------------------------- */
3256 gchar *sender_unique_name; /* if sender is unique or org.freedesktop.DBus, then that name... otherwise blank */
3257 gchar *interface_name;
3261 GDBusSignalFlags flags;
3262 GArray *subscribers;
3267 GDBusSignalCallback callback;
3269 GDestroyNotify user_data_free_func;
3271 GMainContext *context;
3275 signal_data_free (SignalData *signal_data)
3277 g_free (signal_data->rule);
3278 g_free (signal_data->sender);
3279 g_free (signal_data->sender_unique_name);
3280 g_free (signal_data->interface_name);
3281 g_free (signal_data->member);
3282 g_free (signal_data->object_path);
3283 g_free (signal_data->arg0);
3284 g_array_free (signal_data->subscribers, TRUE);
3285 g_free (signal_data);
3289 args_to_rule (const gchar *sender,
3290 const gchar *interface_name,
3291 const gchar *member,
3292 const gchar *object_path,
3294 GDBusSignalFlags flags)
3298 rule = g_string_new ("type='signal'");
3299 if (flags & G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE)
3300 g_string_prepend_c (rule, '-');
3302 g_string_append_printf (rule, ",sender='%s'", sender);
3303 if (interface_name != NULL)
3304 g_string_append_printf (rule, ",interface='%s'", interface_name);
3306 g_string_append_printf (rule, ",member='%s'", member);
3307 if (object_path != NULL)
3308 g_string_append_printf (rule, ",path='%s'", object_path);
3312 if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3313 g_string_append_printf (rule, ",arg0path='%s'", arg0);
3314 else if (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3315 g_string_append_printf (rule, ",arg0namespace='%s'", arg0);
3317 g_string_append_printf (rule, ",arg0='%s'", arg0);
3320 return g_string_free (rule, FALSE);
3323 static guint _global_subscriber_id = 1;
3324 static guint _global_registration_id = 1;
3325 static guint _global_subtree_registration_id = 1;
3327 /* ---------------------------------------------------------------------------------------------------- */
3329 /* Called in a user thread, lock is held */
3331 add_match_rule (GDBusConnection *connection,
3332 const gchar *match_rule)
3335 GDBusMessage *message;
3337 if (match_rule[0] == '-')
3340 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3341 "/org/freedesktop/DBus", /* path */
3342 "org.freedesktop.DBus", /* interface */
3344 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3346 if (!g_dbus_connection_send_message_unlocked (connection,
3348 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3352 g_critical ("Error while sending AddMatch() message: %s", error->message);
3353 g_error_free (error);
3355 g_object_unref (message);
3358 /* ---------------------------------------------------------------------------------------------------- */
3360 /* Called in a user thread, lock is held */
3362 remove_match_rule (GDBusConnection *connection,
3363 const gchar *match_rule)
3366 GDBusMessage *message;
3368 if (match_rule[0] == '-')
3371 message = g_dbus_message_new_method_call ("org.freedesktop.DBus", /* name */
3372 "/org/freedesktop/DBus", /* path */
3373 "org.freedesktop.DBus", /* interface */
3375 g_dbus_message_set_body (message, g_variant_new ("(s)", match_rule));
3378 if (!g_dbus_connection_send_message_unlocked (connection,
3380 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
3384 /* If we could get G_IO_ERROR_CLOSED here, it wouldn't be reasonable to
3385 * critical; but we're holding the lock, and our caller checked whether
3386 * we were already closed, so we can't get that error.
3388 g_critical ("Error while sending RemoveMatch() message: %s", error->message);
3389 g_error_free (error);
3391 g_object_unref (message);
3394 /* ---------------------------------------------------------------------------------------------------- */
3397 is_signal_data_for_name_lost_or_acquired (SignalData *signal_data)
3399 return g_strcmp0 (signal_data->sender_unique_name, "org.freedesktop.DBus") == 0 &&
3400 g_strcmp0 (signal_data->interface_name, "org.freedesktop.DBus") == 0 &&
3401 g_strcmp0 (signal_data->object_path, "/org/freedesktop/DBus") == 0 &&
3402 (g_strcmp0 (signal_data->member, "NameLost") == 0 ||
3403 g_strcmp0 (signal_data->member, "NameAcquired") == 0);
3406 /* ---------------------------------------------------------------------------------------------------- */
3409 * g_dbus_connection_signal_subscribe:
3410 * @connection: A #GDBusConnection.
3411 * @sender: (allow-none): Sender name to match on (unique or well-known name)
3412 * or %NULL to listen from all senders.
3413 * @interface_name: (allow-none): D-Bus interface name to match on or %NULL to
3414 * match on all interfaces.
3415 * @member: (allow-none): D-Bus signal name to match on or %NULL to match on all signals.
3416 * @object_path: (allow-none): Object path to match on or %NULL to match on all object paths.
3417 * @arg0: (allow-none): Contents of first string argument to match on or %NULL
3418 * to match on all kinds of arguments.
3419 * @flags: Flags describing how to subscribe to the signal (currently unused).
3420 * @callback: Callback to invoke when there is a signal matching the requested data.
3421 * @user_data: User data to pass to @callback.
3422 * @user_data_free_func: (allow-none): Function to free @user_data with when
3423 * subscription is removed or %NULL.
3425 * Subscribes to signals on @connection and invokes @callback with a
3426 * whenever the signal is received. Note that @callback
3427 * will be invoked in the <link
3428 * linkend="g-main-context-push-thread-default">thread-default main
3429 * loop</link> of the thread you are calling this method from.
3431 * If @connection is not a message bus connection, @sender must be
3434 * If @sender is a well-known name note that @callback is invoked with
3435 * the unique name for the owner of @sender, not the well-known name
3436 * as one would expect. This is because the message bus rewrites the
3437 * name. As such, to avoid certain race conditions, users should be
3438 * tracking the name owner of the well-known name and use that when
3439 * processing the received signal.
3441 * If one of %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE or
3442 * %G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH are given, @arg0 is
3443 * interpreted as part of a namespace or path. The first argument
3444 * of a signal is matched against that part as specified by D-Bus.
3446 * Returns: A subscription identifier that can be used with g_dbus_connection_signal_unsubscribe().
3451 g_dbus_connection_signal_subscribe (GDBusConnection *connection,
3452 const gchar *sender,
3453 const gchar *interface_name,
3454 const gchar *member,
3455 const gchar *object_path,
3457 GDBusSignalFlags flags,
3458 GDBusSignalCallback callback,
3460 GDestroyNotify user_data_free_func)
3463 SignalData *signal_data;
3464 SignalSubscriber subscriber;
3465 GPtrArray *signal_data_array;
3466 const gchar *sender_unique_name;
3468 /* Right now we abort if AddMatch() fails since it can only fail with the bus being in
3469 * an OOM condition. We might want to change that but that would involve making
3470 * g_dbus_connection_signal_subscribe() asynchronous and having the call sites
3471 * handle that. And there's really no sensible way of handling this short of retrying
3472 * to add the match rule... and then there's the little thing that, hey, maybe there's
3473 * a reason the bus in an OOM condition.
3475 * Doable, but not really sure it's worth it...
3478 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
3479 g_return_val_if_fail (sender == NULL || (g_dbus_is_name (sender) && (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)), 0);
3480 g_return_val_if_fail (interface_name == NULL || g_dbus_is_interface_name (interface_name), 0);
3481 g_return_val_if_fail (member == NULL || g_dbus_is_member_name (member), 0);
3482 g_return_val_if_fail (object_path == NULL || g_variant_is_object_path (object_path), 0);
3483 g_return_val_if_fail (callback != NULL, 0);
3484 g_return_val_if_fail (check_initialized (connection), 0);
3485 g_return_val_if_fail (!((flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH) && (flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)), 0);
3486 g_return_val_if_fail (!(arg0 == NULL && (flags & (G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH | G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE))), 0);
3488 CONNECTION_LOCK (connection);
3490 /* If G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE was specified, we will end up
3491 * with a '-' character to prefix the rule (which will otherwise be
3494 * This allows us to hash the rule and do our lifecycle tracking in
3495 * the usual way, but the '-' prevents the match rule from ever
3496 * actually being send to the bus (either for add or remove).
3498 rule = args_to_rule (sender, interface_name, member, object_path, arg0, flags);
3500 if (sender != NULL && (g_dbus_is_unique_name (sender) || g_strcmp0 (sender, "org.freedesktop.DBus") == 0))
3501 sender_unique_name = sender;
3503 sender_unique_name = "";
3505 subscriber.callback = callback;
3506 subscriber.user_data = user_data;
3507 subscriber.user_data_free_func = user_data_free_func;
3508 subscriber.id = _global_subscriber_id++; /* TODO: overflow etc. */
3509 subscriber.context = g_main_context_ref_thread_default ();
3511 /* see if we've already have this rule */
3512 signal_data = g_hash_table_lookup (connection->map_rule_to_signal_data, rule);
3513 if (signal_data != NULL)
3515 g_array_append_val (signal_data->subscribers, subscriber);
3520 signal_data = g_new0 (SignalData, 1);
3521 signal_data->rule = rule;
3522 signal_data->sender = g_strdup (sender);
3523 signal_data->sender_unique_name = g_strdup (sender_unique_name);
3524 signal_data->interface_name = g_strdup (interface_name);
3525 signal_data->member = g_strdup (member);
3526 signal_data->object_path = g_strdup (object_path);
3527 signal_data->arg0 = g_strdup (arg0);
3528 signal_data->flags = flags;
3529 signal_data->subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3530 g_array_append_val (signal_data->subscribers, subscriber);
3532 g_hash_table_insert (connection->map_rule_to_signal_data,
3536 /* Add the match rule to the bus...
3538 * Avoid adding match rules for NameLost and NameAcquired messages - the bus will
3539 * always send such messages to us.
3541 if (connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION)
3543 if (!is_signal_data_for_name_lost_or_acquired (signal_data))
3544 add_match_rule (connection, signal_data->rule);
3547 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3548 signal_data->sender_unique_name);
3549 if (signal_data_array == NULL)
3551 signal_data_array = g_ptr_array_new ();
3552 g_hash_table_insert (connection->map_sender_unique_name_to_signal_data_array,
3553 g_strdup (signal_data->sender_unique_name),
3556 g_ptr_array_add (signal_data_array, signal_data);
3559 g_hash_table_insert (connection->map_id_to_signal_data,
3560 GUINT_TO_POINTER (subscriber.id),
3563 CONNECTION_UNLOCK (connection);
3565 return subscriber.id;
3568 /* ---------------------------------------------------------------------------------------------------- */
3570 /* called in any thread */
3571 /* must hold lock when calling this (except if connection->finalizing is TRUE) */
3573 unsubscribe_id_internal (GDBusConnection *connection,
3574 guint subscription_id,
3575 GArray *out_removed_subscribers)
3577 SignalData *signal_data;
3578 GPtrArray *signal_data_array;
3581 signal_data = g_hash_table_lookup (connection->map_id_to_signal_data,
3582 GUINT_TO_POINTER (subscription_id));
3583 if (signal_data == NULL)
3585 /* Don't warn here, we may have thrown all subscriptions out when the connection was closed */
3589 for (n = 0; n < signal_data->subscribers->len; n++)
3591 SignalSubscriber *subscriber;
3593 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, n));
3594 if (subscriber->id != subscription_id)
3597 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_signal_data,
3598 GUINT_TO_POINTER (subscription_id)));
3599 g_array_append_val (out_removed_subscribers, *subscriber);
3600 g_array_remove_index (signal_data->subscribers, n);
3602 if (signal_data->subscribers->len == 0)
3604 g_warn_if_fail (g_hash_table_remove (connection->map_rule_to_signal_data, signal_data->rule));
3606 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array,
3607 signal_data->sender_unique_name);
3608 g_warn_if_fail (signal_data_array != NULL);
3609 g_warn_if_fail (g_ptr_array_remove (signal_data_array, signal_data));
3611 if (signal_data_array->len == 0)
3613 g_warn_if_fail (g_hash_table_remove (connection->map_sender_unique_name_to_signal_data_array,
3614 signal_data->sender_unique_name));
3617 /* remove the match rule from the bus unless NameLost or NameAcquired (see subscribe()) */
3618 if ((connection->flags & G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION) &&
3619 !is_signal_data_for_name_lost_or_acquired (signal_data) &&
3620 !g_dbus_connection_is_closed (connection) &&
3621 !connection->finalizing)
3623 /* The check for g_dbus_connection_is_closed() means that
3624 * sending the RemoveMatch message can't fail with
3625 * G_IO_ERROR_CLOSED, because we're holding the lock,
3626 * so on_worker_closed() can't happen between the check we just
3627 * did, and releasing the lock later.
3629 remove_match_rule (connection, signal_data->rule);
3632 signal_data_free (signal_data);
3638 g_assert_not_reached ();
3645 * g_dbus_connection_signal_unsubscribe:
3646 * @connection: A #GDBusConnection.
3647 * @subscription_id: A subscription id obtained from g_dbus_connection_signal_subscribe().
3649 * Unsubscribes from signals.
3654 g_dbus_connection_signal_unsubscribe (GDBusConnection *connection,
3655 guint subscription_id)
3657 GArray *subscribers;
3660 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
3661 g_return_if_fail (check_initialized (connection));
3663 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3665 CONNECTION_LOCK (connection);
3666 unsubscribe_id_internal (connection,
3669 CONNECTION_UNLOCK (connection);
3672 g_assert (subscribers->len == 0 || subscribers->len == 1);
3674 /* call GDestroyNotify without lock held */
3675 for (n = 0; n < subscribers->len; n++)
3677 SignalSubscriber *subscriber;
3678 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3679 call_destroy_notify (subscriber->context,
3680 subscriber->user_data_free_func,
3681 subscriber->user_data);
3682 g_main_context_unref (subscriber->context);
3685 g_array_free (subscribers, TRUE);
3688 /* ---------------------------------------------------------------------------------------------------- */
3692 guint subscription_id;
3693 GDBusSignalCallback callback;
3695 GDBusMessage *message;
3696 GDBusConnection *connection;
3697 const gchar *sender;
3699 const gchar *interface;
3700 const gchar *member;
3703 /* called on delivery thread (e.g. where g_dbus_connection_signal_subscribe() was called) with
3707 emit_signal_instance_in_idle_cb (gpointer data)
3709 SignalInstance *signal_instance = data;
3710 GVariant *parameters;
3711 gboolean has_subscription;
3713 parameters = g_dbus_message_get_body (signal_instance->message);
3714 if (parameters == NULL)
3716 parameters = g_variant_new ("()");
3717 g_variant_ref_sink (parameters);
3721 g_variant_ref_sink (parameters);
3725 g_print ("in emit_signal_instance_in_idle_cb (id=%d sender=%s path=%s interface=%s member=%s params=%s)\n",
3726 signal_instance->subscription_id,
3727 signal_instance->sender,
3728 signal_instance->path,
3729 signal_instance->interface,
3730 signal_instance->member,
3731 g_variant_print (parameters, TRUE));
3734 /* Careful here, don't do the callback if we no longer has the subscription */
3735 CONNECTION_LOCK (signal_instance->connection);
3736 has_subscription = FALSE;
3737 if (g_hash_table_lookup (signal_instance->connection->map_id_to_signal_data,
3738 GUINT_TO_POINTER (signal_instance->subscription_id)) != NULL)
3739 has_subscription = TRUE;
3740 CONNECTION_UNLOCK (signal_instance->connection);
3742 if (has_subscription)
3743 signal_instance->callback (signal_instance->connection,
3744 signal_instance->sender,
3745 signal_instance->path,
3746 signal_instance->interface,
3747 signal_instance->member,
3749 signal_instance->user_data);
3751 g_variant_unref (parameters);
3757 signal_instance_free (SignalInstance *signal_instance)
3759 g_object_unref (signal_instance->message);
3760 g_object_unref (signal_instance->connection);
3761 g_free (signal_instance);
3765 namespace_rule_matches (const gchar *namespace,
3771 len_namespace = strlen (namespace);
3772 len_name = strlen (name);
3774 if (len_name < len_namespace)
3777 if (memcmp (namespace, name, len_namespace) != 0)
3780 return len_namespace == len_name || name[len_namespace] == '.';
3784 path_rule_matches (const gchar *path_a,
3785 const gchar *path_b)
3789 len_a = strlen (path_a);
3790 len_b = strlen (path_b);
3792 if (len_a < len_b && path_a[len_a - 1] != '/')
3795 if (len_b < len_a && path_b[len_b - 1] != '/')
3798 return memcmp (path_a, path_b, MIN (len_a, len_b)) == 0;
3801 /* called in GDBusWorker thread WITH lock held */
3803 schedule_callbacks (GDBusConnection *connection,
3804 GPtrArray *signal_data_array,
3805 GDBusMessage *message,
3806 const gchar *sender)
3809 const gchar *interface;
3810 const gchar *member;
3819 interface = g_dbus_message_get_interface (message);
3820 member = g_dbus_message_get_member (message);
3821 path = g_dbus_message_get_path (message);
3822 arg0 = g_dbus_message_get_arg0 (message);
3825 g_print ("In schedule_callbacks:\n"
3827 " interface = '%s'\n"
3838 /* TODO: if this is slow, then we can change signal_data_array into
3839 * map_object_path_to_signal_data_array or something.
3841 for (n = 0; n < signal_data_array->len; n++)
3843 SignalData *signal_data = signal_data_array->pdata[n];
3845 if (signal_data->interface_name != NULL && g_strcmp0 (signal_data->interface_name, interface) != 0)
3848 if (signal_data->member != NULL && g_strcmp0 (signal_data->member, member) != 0)
3851 if (signal_data->object_path != NULL && g_strcmp0 (signal_data->object_path, path) != 0)
3854 if (signal_data->arg0 != NULL)
3859 if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_NAMESPACE)
3861 if (!namespace_rule_matches (signal_data->arg0, arg0))
3864 else if (signal_data->flags & G_DBUS_SIGNAL_FLAGS_MATCH_ARG0_PATH)
3866 if (!path_rule_matches (signal_data->arg0, arg0))
3869 else if (!g_str_equal (signal_data->arg0, arg0))
3873 for (m = 0; m < signal_data->subscribers->len; m++)
3875 SignalSubscriber *subscriber;
3876 GSource *idle_source;
3877 SignalInstance *signal_instance;
3879 subscriber = &(g_array_index (signal_data->subscribers, SignalSubscriber, m));
3881 signal_instance = g_new0 (SignalInstance, 1);
3882 signal_instance->subscription_id = subscriber->id;
3883 signal_instance->callback = subscriber->callback;
3884 signal_instance->user_data = subscriber->user_data;
3885 signal_instance->message = g_object_ref (message);
3886 signal_instance->connection = g_object_ref (connection);
3887 signal_instance->sender = sender;
3888 signal_instance->path = path;
3889 signal_instance->interface = interface;
3890 signal_instance->member = member;
3892 idle_source = g_idle_source_new ();
3893 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
3894 g_source_set_callback (idle_source,
3895 emit_signal_instance_in_idle_cb,
3897 (GDestroyNotify) signal_instance_free);
3898 g_source_attach (idle_source, subscriber->context);
3899 g_source_unref (idle_source);
3904 /* called in GDBusWorker thread with lock held */
3906 distribute_signals (GDBusConnection *connection,
3907 GDBusMessage *message)
3909 GPtrArray *signal_data_array;
3910 const gchar *sender;
3912 sender = g_dbus_message_get_sender (message);
3914 if (G_UNLIKELY (_g_dbus_debug_signal ()))
3916 _g_dbus_debug_print_lock ();
3917 g_print ("========================================================================\n"
3918 "GDBus-debug:Signal:\n"
3919 " <<<< RECEIVED SIGNAL %s.%s\n"
3921 " sent by name %s\n",
3922 g_dbus_message_get_interface (message),
3923 g_dbus_message_get_member (message),
3924 g_dbus_message_get_path (message),
3925 sender != NULL ? sender : "(none)");
3926 _g_dbus_debug_print_unlock ();
3929 /* collect subscribers that match on sender */
3932 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, sender);
3933 if (signal_data_array != NULL)
3934 schedule_callbacks (connection, signal_data_array, message, sender);
3937 /* collect subscribers not matching on sender */
3938 signal_data_array = g_hash_table_lookup (connection->map_sender_unique_name_to_signal_data_array, "");
3939 if (signal_data_array != NULL)
3940 schedule_callbacks (connection, signal_data_array, message, sender);
3943 /* ---------------------------------------------------------------------------------------------------- */
3945 /* only called from finalize(), removes all subscriptions */
3947 purge_all_signal_subscriptions (GDBusConnection *connection)
3949 GHashTableIter iter;
3952 GArray *subscribers;
3955 ids = g_array_new (FALSE, FALSE, sizeof (guint));
3956 g_hash_table_iter_init (&iter, connection->map_id_to_signal_data);
3957 while (g_hash_table_iter_next (&iter, &key, NULL))
3959 guint subscription_id = GPOINTER_TO_UINT (key);
3960 g_array_append_val (ids, subscription_id);
3963 subscribers = g_array_new (FALSE, FALSE, sizeof (SignalSubscriber));
3964 for (n = 0; n < ids->len; n++)
3966 guint subscription_id = g_array_index (ids, guint, n);
3967 unsubscribe_id_internal (connection,
3971 g_array_free (ids, TRUE);
3973 /* call GDestroyNotify without lock held */
3974 for (n = 0; n < subscribers->len; n++)
3976 SignalSubscriber *subscriber;
3977 subscriber = &(g_array_index (subscribers, SignalSubscriber, n));
3978 call_destroy_notify (subscriber->context,
3979 subscriber->user_data_free_func,
3980 subscriber->user_data);
3981 g_main_context_unref (subscriber->context);
3984 g_array_free (subscribers, TRUE);
3987 /* ---------------------------------------------------------------------------------------------------- */
3989 static GDBusInterfaceVTable *
3990 _g_dbus_interface_vtable_copy (const GDBusInterfaceVTable *vtable)
3992 /* Don't waste memory by copying padding - remember to update this
3993 * when changing struct _GDBusInterfaceVTable in gdbusconnection.h
3995 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
3999 _g_dbus_interface_vtable_free (GDBusInterfaceVTable *vtable)
4004 /* ---------------------------------------------------------------------------------------------------- */
4006 static GDBusSubtreeVTable *
4007 _g_dbus_subtree_vtable_copy (const GDBusSubtreeVTable *vtable)
4009 /* Don't waste memory by copying padding - remember to update this
4010 * when changing struct _GDBusSubtreeVTable in gdbusconnection.h
4012 return g_memdup ((gconstpointer) vtable, 3 * sizeof (gpointer));
4016 _g_dbus_subtree_vtable_free (GDBusSubtreeVTable *vtable)
4021 /* ---------------------------------------------------------------------------------------------------- */
4023 struct ExportedObject
4026 GDBusConnection *connection;
4028 /* maps gchar* -> ExportedInterface* */
4029 GHashTable *map_if_name_to_ei;
4032 /* only called with lock held */
4034 exported_object_free (ExportedObject *eo)
4036 g_free (eo->object_path);
4037 g_hash_table_unref (eo->map_if_name_to_ei);
4046 gchar *interface_name;
4047 GDBusInterfaceVTable *vtable;
4048 GDBusInterfaceInfo *interface_info;
4050 GMainContext *context;
4052 GDestroyNotify user_data_free_func;
4053 } ExportedInterface;
4055 /* called with lock held */
4057 exported_interface_free (ExportedInterface *ei)
4059 g_dbus_interface_info_cache_release (ei->interface_info);
4060 g_dbus_interface_info_unref ((GDBusInterfaceInfo *) ei->interface_info);
4062 call_destroy_notify (ei->context,
4063 ei->user_data_free_func,
4066 g_main_context_unref (ei->context);
4068 g_free (ei->interface_name);
4069 _g_dbus_interface_vtable_free (ei->vtable);
4073 /* ---------------------------------------------------------------------------------------------------- */
4075 /* Convenience function to check if @registration_id (if not zero) or
4076 * @subtree_registration_id (if not zero) has been unregistered. If
4077 * so, returns %TRUE.
4079 * May be called by any thread. Caller must *not* hold lock.
4082 has_object_been_unregistered (GDBusConnection *connection,
4083 guint registration_id,
4084 guint subtree_registration_id)
4088 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
4092 CONNECTION_LOCK (connection);
4093 if (registration_id != 0 && g_hash_table_lookup (connection->map_id_to_ei,
4094 GUINT_TO_POINTER (registration_id)) == NULL)
4098 else if (subtree_registration_id != 0 && g_hash_table_lookup (connection->map_id_to_es,
4099 GUINT_TO_POINTER (subtree_registration_id)) == NULL)
4103 CONNECTION_UNLOCK (connection);
4108 /* ---------------------------------------------------------------------------------------------------- */
4112 GDBusConnection *connection;
4113 GDBusMessage *message;
4115 const gchar *property_name;
4116 const GDBusInterfaceVTable *vtable;
4117 GDBusInterfaceInfo *interface_info;
4118 const GDBusPropertyInfo *property_info;
4119 guint registration_id;
4120 guint subtree_registration_id;
4124 property_data_free (PropertyData *data)
4126 g_object_unref (data->connection);
4127 g_object_unref (data->message);
4131 /* called in thread where object was registered - no locks held */
4133 invoke_get_property_in_idle_cb (gpointer _data)
4135 PropertyData *data = _data;
4138 GDBusMessage *reply;
4140 if (has_object_been_unregistered (data->connection,
4141 data->registration_id,
4142 data->subtree_registration_id))
4144 reply = g_dbus_message_new_method_error (data->message,
4145 "org.freedesktop.DBus.Error.UnknownMethod",
4146 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4147 g_dbus_message_get_path (data->message));
4148 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4149 g_object_unref (reply);
4154 value = data->vtable->get_property (data->connection,
4155 g_dbus_message_get_sender (data->message),
4156 g_dbus_message_get_path (data->message),
4157 data->interface_info->name,
4158 data->property_name,
4165 g_assert_no_error (error);
4167 g_variant_take_ref (value);
4168 reply = g_dbus_message_new_method_reply (data->message);
4169 g_dbus_message_set_body (reply, g_variant_new ("(v)", value));
4170 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4171 g_variant_unref (value);
4172 g_object_unref (reply);
4176 gchar *dbus_error_name;
4177 g_assert (error != NULL);
4178 dbus_error_name = g_dbus_error_encode_gerror (error);
4179 reply = g_dbus_message_new_method_error_literal (data->message,
4182 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4183 g_free (dbus_error_name);
4184 g_error_free (error);
4185 g_object_unref (reply);
4192 /* called in thread where object was registered - no locks held */
4194 invoke_set_property_in_idle_cb (gpointer _data)
4196 PropertyData *data = _data;
4198 GDBusMessage *reply;
4204 g_variant_get (g_dbus_message_get_body (data->message),
4210 if (!data->vtable->set_property (data->connection,
4211 g_dbus_message_get_sender (data->message),
4212 g_dbus_message_get_path (data->message),
4213 data->interface_info->name,
4214 data->property_name,
4219 gchar *dbus_error_name;
4220 g_assert (error != NULL);
4221 dbus_error_name = g_dbus_error_encode_gerror (error);
4222 reply = g_dbus_message_new_method_error_literal (data->message,
4225 g_free (dbus_error_name);
4226 g_error_free (error);
4230 reply = g_dbus_message_new_method_reply (data->message);
4233 g_assert (reply != NULL);
4234 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4235 g_object_unref (reply);
4236 g_variant_unref (value);
4241 /* called in any thread with connection's lock held */
4243 validate_and_maybe_schedule_property_getset (GDBusConnection *connection,
4244 GDBusMessage *message,
4245 guint registration_id,
4246 guint subtree_registration_id,
4248 GDBusInterfaceInfo *interface_info,
4249 const GDBusInterfaceVTable *vtable,
4250 GMainContext *main_context,
4254 const char *interface_name;
4255 const char *property_name;
4256 const GDBusPropertyInfo *property_info;
4257 GSource *idle_source;
4258 PropertyData *property_data;
4259 GDBusMessage *reply;
4264 g_variant_get (g_dbus_message_get_body (message),
4269 g_variant_get (g_dbus_message_get_body (message),
4278 if (vtable == NULL || vtable->get_property == NULL)
4283 if (vtable == NULL || vtable->set_property == NULL)
4287 /* Check that the property exists - if not fail with org.freedesktop.DBus.Error.InvalidArgs
4289 property_info = NULL;
4291 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4292 property_info = g_dbus_interface_info_lookup_property (interface_info, property_name);
4293 if (property_info == NULL)
4295 reply = g_dbus_message_new_method_error (message,
4296 "org.freedesktop.DBus.Error.InvalidArgs",
4297 _("No such property '%s'"),
4299 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4300 g_object_unref (reply);
4305 if (is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4307 reply = g_dbus_message_new_method_error (message,
4308 "org.freedesktop.DBus.Error.InvalidArgs",
4309 _("Property '%s' is not readable"),
4311 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4312 g_object_unref (reply);
4316 else if (!is_get && !(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
4318 reply = g_dbus_message_new_method_error (message,
4319 "org.freedesktop.DBus.Error.InvalidArgs",
4320 _("Property '%s' is not writable"),
4322 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4323 g_object_unref (reply);
4332 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the type
4333 * of the given value is wrong
4335 g_variant_get_child (g_dbus_message_get_body (message), 2, "v", &value);
4336 if (g_strcmp0 (g_variant_get_type_string (value), property_info->signature) != 0)
4338 reply = g_dbus_message_new_method_error (message,
4339 "org.freedesktop.DBus.Error.InvalidArgs",
4340 _("Error setting property '%s': Expected type '%s' but got '%s'"),
4341 property_name, property_info->signature,
4342 g_variant_get_type_string (value));
4343 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4344 g_variant_unref (value);
4345 g_object_unref (reply);
4350 g_variant_unref (value);
4353 /* ok, got the property info - call user code in an idle handler */
4354 property_data = g_new0 (PropertyData, 1);
4355 property_data->connection = g_object_ref (connection);
4356 property_data->message = g_object_ref (message);
4357 property_data->user_data = user_data;
4358 property_data->property_name = property_name;
4359 property_data->vtable = vtable;
4360 property_data->interface_info = interface_info;
4361 property_data->property_info = property_info;
4362 property_data->registration_id = registration_id;
4363 property_data->subtree_registration_id = subtree_registration_id;
4365 idle_source = g_idle_source_new ();
4366 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4367 g_source_set_callback (idle_source,
4368 is_get ? invoke_get_property_in_idle_cb : invoke_set_property_in_idle_cb,
4370 (GDestroyNotify) property_data_free);
4371 g_source_attach (idle_source, main_context);
4372 g_source_unref (idle_source);
4380 /* called in GDBusWorker thread with connection's lock held */
4382 handle_getset_property (GDBusConnection *connection,
4384 GDBusMessage *message,
4387 ExportedInterface *ei;
4389 const char *interface_name;
4390 const char *property_name;
4395 g_variant_get (g_dbus_message_get_body (message),
4400 g_variant_get (g_dbus_message_get_body (message),
4406 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4407 * no such interface registered
4409 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4412 GDBusMessage *reply;
4413 reply = g_dbus_message_new_method_error (message,
4414 "org.freedesktop.DBus.Error.InvalidArgs",
4415 _("No such interface '%s'"),
4417 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4418 g_object_unref (reply);
4423 handled = validate_and_maybe_schedule_property_getset (eo->connection,
4436 /* ---------------------------------------------------------------------------------------------------- */
4440 GDBusConnection *connection;
4441 GDBusMessage *message;
4443 const GDBusInterfaceVTable *vtable;
4444 GDBusInterfaceInfo *interface_info;
4445 guint registration_id;
4446 guint subtree_registration_id;
4447 } PropertyGetAllData;
4450 property_get_all_data_free (PropertyData *data)
4452 g_object_unref (data->connection);
4453 g_object_unref (data->message);
4457 /* called in thread where object was registered - no locks held */
4459 invoke_get_all_properties_in_idle_cb (gpointer _data)
4461 PropertyGetAllData *data = _data;
4462 GVariantBuilder builder;
4463 GDBusMessage *reply;
4466 if (has_object_been_unregistered (data->connection,
4467 data->registration_id,
4468 data->subtree_registration_id))
4470 reply = g_dbus_message_new_method_error (data->message,
4471 "org.freedesktop.DBus.Error.UnknownMethod",
4472 _("No such interface 'org.freedesktop.DBus.Properties' on object at path %s"),
4473 g_dbus_message_get_path (data->message));
4474 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4475 g_object_unref (reply);
4479 /* TODO: Right now we never fail this call - we just omit values if
4480 * a get_property() call is failing.
4482 * We could fail the whole call if just a single get_property() call
4483 * returns an error. We need clarification in the D-Bus spec about this.
4485 g_variant_builder_init (&builder, G_VARIANT_TYPE ("(a{sv})"));
4486 g_variant_builder_open (&builder, G_VARIANT_TYPE ("a{sv}"));
4487 for (n = 0; data->interface_info->properties != NULL && data->interface_info->properties[n] != NULL; n++)
4489 const GDBusPropertyInfo *property_info = data->interface_info->properties[n];
4492 if (!(property_info->flags & G_DBUS_PROPERTY_INFO_FLAGS_READABLE))
4495 value = data->vtable->get_property (data->connection,
4496 g_dbus_message_get_sender (data->message),
4497 g_dbus_message_get_path (data->message),
4498 data->interface_info->name,
4499 property_info->name,
4506 g_variant_take_ref (value);
4507 g_variant_builder_add (&builder,
4509 property_info->name,
4511 g_variant_unref (value);
4513 g_variant_builder_close (&builder);
4515 reply = g_dbus_message_new_method_reply (data->message);
4516 g_dbus_message_set_body (reply, g_variant_builder_end (&builder));
4517 g_dbus_connection_send_message (data->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4518 g_object_unref (reply);
4524 /* called in any thread with connection's lock held */
4526 validate_and_maybe_schedule_property_get_all (GDBusConnection *connection,
4527 GDBusMessage *message,
4528 guint registration_id,
4529 guint subtree_registration_id,
4530 GDBusInterfaceInfo *interface_info,
4531 const GDBusInterfaceVTable *vtable,
4532 GMainContext *main_context,
4536 GSource *idle_source;
4537 PropertyGetAllData *property_get_all_data;
4541 if (vtable == NULL || vtable->get_property == NULL)
4544 /* ok, got the property info - call user in an idle handler */
4545 property_get_all_data = g_new0 (PropertyGetAllData, 1);
4546 property_get_all_data->connection = g_object_ref (connection);
4547 property_get_all_data->message = g_object_ref (message);
4548 property_get_all_data->user_data = user_data;
4549 property_get_all_data->vtable = vtable;
4550 property_get_all_data->interface_info = interface_info;
4551 property_get_all_data->registration_id = registration_id;
4552 property_get_all_data->subtree_registration_id = subtree_registration_id;
4554 idle_source = g_idle_source_new ();
4555 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4556 g_source_set_callback (idle_source,
4557 invoke_get_all_properties_in_idle_cb,
4558 property_get_all_data,
4559 (GDestroyNotify) property_get_all_data_free);
4560 g_source_attach (idle_source, main_context);
4561 g_source_unref (idle_source);
4569 /* called in GDBusWorker thread with connection's lock held */
4571 handle_get_all_properties (GDBusConnection *connection,
4573 GDBusMessage *message)
4575 ExportedInterface *ei;
4577 const char *interface_name;
4581 g_variant_get (g_dbus_message_get_body (message),
4585 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if there is
4586 * no such interface registered
4588 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4591 GDBusMessage *reply;
4592 reply = g_dbus_message_new_method_error (message,
4593 "org.freedesktop.DBus.Error.InvalidArgs",
4594 _("No such interface"),
4596 g_dbus_connection_send_message_unlocked (eo->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4597 g_object_unref (reply);
4602 handled = validate_and_maybe_schedule_property_get_all (eo->connection,
4614 /* ---------------------------------------------------------------------------------------------------- */
4616 static const gchar introspect_header[] =
4617 "<!DOCTYPE node PUBLIC \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"\n"
4618 " \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">\n"
4619 "<!-- GDBus " PACKAGE_VERSION " -->\n"
4622 static const gchar introspect_tail[] =
4625 static const gchar introspect_properties_interface[] =
4626 " <interface name=\"org.freedesktop.DBus.Properties\">\n"
4627 " <method name=\"Get\">\n"
4628 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4629 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4630 " <arg type=\"v\" name=\"value\" direction=\"out\"/>\n"
4632 " <method name=\"GetAll\">\n"
4633 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4634 " <arg type=\"a{sv}\" name=\"properties\" direction=\"out\"/>\n"
4636 " <method name=\"Set\">\n"
4637 " <arg type=\"s\" name=\"interface_name\" direction=\"in\"/>\n"
4638 " <arg type=\"s\" name=\"property_name\" direction=\"in\"/>\n"
4639 " <arg type=\"v\" name=\"value\" direction=\"in\"/>\n"
4641 " <signal name=\"PropertiesChanged\">\n"
4642 " <arg type=\"s\" name=\"interface_name\"/>\n"
4643 " <arg type=\"a{sv}\" name=\"changed_properties\"/>\n"
4644 " <arg type=\"as\" name=\"invalidated_properties\"/>\n"
4648 static const gchar introspect_introspectable_interface[] =
4649 " <interface name=\"org.freedesktop.DBus.Introspectable\">\n"
4650 " <method name=\"Introspect\">\n"
4651 " <arg type=\"s\" name=\"xml_data\" direction=\"out\"/>\n"
4654 " <interface name=\"org.freedesktop.DBus.Peer\">\n"
4655 " <method name=\"Ping\"/>\n"
4656 " <method name=\"GetMachineId\">\n"
4657 " <arg type=\"s\" name=\"machine_uuid\" direction=\"out\"/>\n"
4662 introspect_append_header (GString *s)
4664 g_string_append (s, introspect_header);
4668 maybe_add_path (const gchar *path, gsize path_len, const gchar *object_path, GHashTable *set)
4670 if (g_str_has_prefix (object_path, path) && strlen (object_path) > path_len && object_path[path_len-1] == '/')
4676 begin = object_path + path_len;
4677 end = strchr (begin, '/');
4679 s = g_strndup (begin, end - begin);
4681 s = g_strdup (begin);
4683 if (g_hash_table_lookup (set, s) == NULL)
4684 g_hash_table_insert (set, s, GUINT_TO_POINTER (1));
4690 /* TODO: we want a nicer public interface for this */
4691 /* called in any thread with connection's lock held */
4693 g_dbus_connection_list_registered_unlocked (GDBusConnection *connection,
4698 GHashTableIter hash_iter;
4699 const gchar *object_path;
4705 CONNECTION_ENSURE_LOCK (connection);
4707 path_len = strlen (path);
4711 set = g_hash_table_new (g_str_hash, g_str_equal);
4713 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_eo);
4714 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4715 maybe_add_path (path, path_len, object_path, set);
4717 g_hash_table_iter_init (&hash_iter, connection->map_object_path_to_es);
4718 while (g_hash_table_iter_next (&hash_iter, (gpointer) &object_path, NULL))
4719 maybe_add_path (path, path_len, object_path, set);
4721 p = g_ptr_array_new ();
4722 keys = g_hash_table_get_keys (set);
4723 for (l = keys; l != NULL; l = l->next)
4724 g_ptr_array_add (p, l->data);
4725 g_hash_table_unref (set);
4728 g_ptr_array_add (p, NULL);
4729 ret = (gchar **) g_ptr_array_free (p, FALSE);
4733 /* called in any thread with connection's lock not held */
4735 g_dbus_connection_list_registered (GDBusConnection *connection,
4739 CONNECTION_LOCK (connection);
4740 ret = g_dbus_connection_list_registered_unlocked (connection, path);
4741 CONNECTION_UNLOCK (connection);
4745 /* called in GDBusWorker thread with connection's lock held */
4747 handle_introspect (GDBusConnection *connection,
4749 GDBusMessage *message)
4753 GDBusMessage *reply;
4754 GHashTableIter hash_iter;
4755 ExportedInterface *ei;
4758 /* first the header with the standard interfaces */
4759 s = g_string_sized_new (sizeof (introspect_header) +
4760 sizeof (introspect_properties_interface) +
4761 sizeof (introspect_introspectable_interface) +
4762 sizeof (introspect_tail));
4763 introspect_append_header (s);
4764 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4765 "org.freedesktop.DBus.Properties"))
4766 g_string_append (s, introspect_properties_interface);
4768 if (!g_hash_table_lookup (eo->map_if_name_to_ei,
4769 "org.freedesktop.DBus.Introspectable"))
4770 g_string_append (s, introspect_introspectable_interface);
4772 /* then include the registered interfaces */
4773 g_hash_table_iter_init (&hash_iter, eo->map_if_name_to_ei);
4774 while (g_hash_table_iter_next (&hash_iter, NULL, (gpointer) &ei))
4775 g_dbus_interface_info_generate_xml (ei->interface_info, 2, s);
4777 /* finally include nodes registered below us */
4778 registered = g_dbus_connection_list_registered_unlocked (connection, eo->object_path);
4779 for (n = 0; registered != NULL && registered[n] != NULL; n++)
4780 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
4781 g_strfreev (registered);
4782 g_string_append (s, introspect_tail);
4784 reply = g_dbus_message_new_method_reply (message);
4785 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
4786 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4787 g_object_unref (reply);
4788 g_string_free (s, TRUE);
4793 /* called in thread where object was registered - no locks held */
4795 call_in_idle_cb (gpointer user_data)
4797 GDBusMethodInvocation *invocation = G_DBUS_METHOD_INVOCATION (user_data);
4798 GDBusInterfaceVTable *vtable;
4799 guint registration_id;
4800 guint subtree_registration_id;
4802 registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-registration-id"));
4803 subtree_registration_id = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id"));
4805 if (has_object_been_unregistered (g_dbus_method_invocation_get_connection (invocation),
4807 subtree_registration_id))
4809 GDBusMessage *reply;
4810 reply = g_dbus_message_new_method_error (g_dbus_method_invocation_get_message (invocation),
4811 "org.freedesktop.DBus.Error.UnknownMethod",
4812 _("No such interface '%s' on object at path %s"),
4813 g_dbus_method_invocation_get_interface_name (invocation),
4814 g_dbus_method_invocation_get_object_path (invocation));
4815 g_dbus_connection_send_message (g_dbus_method_invocation_get_connection (invocation), reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4816 g_object_unref (reply);
4820 vtable = g_object_get_data (G_OBJECT (invocation), "g-dbus-interface-vtable");
4821 g_assert (vtable != NULL && vtable->method_call != NULL);
4823 vtable->method_call (g_dbus_method_invocation_get_connection (invocation),
4824 g_dbus_method_invocation_get_sender (invocation),
4825 g_dbus_method_invocation_get_object_path (invocation),
4826 g_dbus_method_invocation_get_interface_name (invocation),
4827 g_dbus_method_invocation_get_method_name (invocation),
4828 g_dbus_method_invocation_get_parameters (invocation),
4829 g_object_ref (invocation),
4830 g_dbus_method_invocation_get_user_data (invocation));
4836 /* called in GDBusWorker thread with connection's lock held */
4838 schedule_method_call (GDBusConnection *connection,
4839 GDBusMessage *message,
4840 guint registration_id,
4841 guint subtree_registration_id,
4842 const GDBusInterfaceInfo *interface_info,
4843 const GDBusMethodInfo *method_info,
4844 const GDBusPropertyInfo *property_info,
4845 GVariant *parameters,
4846 const GDBusInterfaceVTable *vtable,
4847 GMainContext *main_context,
4850 GDBusMethodInvocation *invocation;
4851 GSource *idle_source;
4853 invocation = _g_dbus_method_invocation_new (g_dbus_message_get_sender (message),
4854 g_dbus_message_get_path (message),
4855 g_dbus_message_get_interface (message),
4856 g_dbus_message_get_member (message),
4864 /* TODO: would be nicer with a real MethodData like we already
4865 * have PropertyData and PropertyGetAllData... */
4866 g_object_set_data (G_OBJECT (invocation), "g-dbus-interface-vtable", (gpointer) vtable);
4867 g_object_set_data (G_OBJECT (invocation), "g-dbus-registration-id", GUINT_TO_POINTER (registration_id));
4868 g_object_set_data (G_OBJECT (invocation), "g-dbus-subtree-registration-id", GUINT_TO_POINTER (subtree_registration_id));
4870 idle_source = g_idle_source_new ();
4871 g_source_set_priority (idle_source, G_PRIORITY_DEFAULT);
4872 g_source_set_callback (idle_source,
4876 g_source_attach (idle_source, main_context);
4877 g_source_unref (idle_source);
4880 /* called in GDBusWorker thread with connection's lock held */
4882 validate_and_maybe_schedule_method_call (GDBusConnection *connection,
4883 GDBusMessage *message,
4884 guint registration_id,
4885 guint subtree_registration_id,
4886 GDBusInterfaceInfo *interface_info,
4887 const GDBusInterfaceVTable *vtable,
4888 GMainContext *main_context,
4891 GDBusMethodInfo *method_info;
4892 GDBusMessage *reply;
4893 GVariant *parameters;
4895 GVariantType *in_type;
4899 /* TODO: the cost of this is O(n) - it might be worth caching the result */
4900 method_info = g_dbus_interface_info_lookup_method (interface_info, g_dbus_message_get_member (message));
4902 /* if the method doesn't exist, return the org.freedesktop.DBus.Error.UnknownMethod
4903 * error to the caller
4905 if (method_info == NULL)
4907 reply = g_dbus_message_new_method_error (message,
4908 "org.freedesktop.DBus.Error.UnknownMethod",
4909 _("No such method '%s'"),
4910 g_dbus_message_get_member (message));
4911 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4912 g_object_unref (reply);
4917 parameters = g_dbus_message_get_body (message);
4918 if (parameters == NULL)
4920 parameters = g_variant_new ("()");
4921 g_variant_ref_sink (parameters);
4925 g_variant_ref (parameters);
4928 /* Check that the incoming args are of the right type - if they are not, return
4929 * the org.freedesktop.DBus.Error.InvalidArgs error to the caller
4931 in_type = _g_dbus_compute_complete_signature (method_info->in_args);
4932 if (!g_variant_is_of_type (parameters, in_type))
4936 type_string = g_variant_type_dup_string (in_type);
4938 reply = g_dbus_message_new_method_error (message,
4939 "org.freedesktop.DBus.Error.InvalidArgs",
4940 _("Type of message, '%s', does not match expected type '%s'"),
4941 g_variant_get_type_string (parameters),
4943 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
4944 g_variant_type_free (in_type);
4945 g_variant_unref (parameters);
4946 g_object_unref (reply);
4947 g_free (type_string);
4951 g_variant_type_free (in_type);
4953 /* schedule the call in idle */
4954 schedule_method_call (connection, message, registration_id, subtree_registration_id,
4955 interface_info, method_info, NULL, parameters,
4956 vtable, main_context, user_data);
4957 g_variant_unref (parameters);
4964 /* ---------------------------------------------------------------------------------------------------- */
4966 /* called in GDBusWorker thread with connection's lock held */
4968 obj_message_func (GDBusConnection *connection,
4970 GDBusMessage *message)
4972 const gchar *interface_name;
4973 const gchar *member;
4974 const gchar *signature;
4979 interface_name = g_dbus_message_get_interface (message);
4980 member = g_dbus_message_get_member (message);
4981 signature = g_dbus_message_get_signature (message);
4983 /* see if we have an interface for handling this call */
4984 if (interface_name != NULL)
4986 ExportedInterface *ei;
4987 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_name);
4990 /* we do - invoke the handler in idle in the right thread */
4992 /* handle no vtable or handler being present */
4993 if (ei->vtable == NULL || ei->vtable->method_call == NULL)
4996 handled = validate_and_maybe_schedule_method_call (connection,
5008 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
5009 g_strcmp0 (member, "Introspect") == 0 &&
5010 g_strcmp0 (signature, "") == 0)
5012 handled = handle_introspect (connection, eo, message);
5015 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5016 g_strcmp0 (member, "Get") == 0 &&
5017 g_strcmp0 (signature, "ss") == 0)
5019 handled = handle_getset_property (connection, eo, message, TRUE);
5022 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5023 g_strcmp0 (member, "Set") == 0 &&
5024 g_strcmp0 (signature, "ssv") == 0)
5026 handled = handle_getset_property (connection, eo, message, FALSE);
5029 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0 &&
5030 g_strcmp0 (member, "GetAll") == 0 &&
5031 g_strcmp0 (signature, "s") == 0)
5033 handled = handle_get_all_properties (connection, eo, message);
5042 * g_dbus_connection_register_object:
5043 * @connection: A #GDBusConnection.
5044 * @object_path: The object path to register at.
5045 * @interface_info: Introspection data for the interface.
5046 * @vtable: (allow-none): A #GDBusInterfaceVTable to call into or %NULL.
5047 * @user_data: (allow-none): Data to pass to functions in @vtable.
5048 * @user_data_free_func: Function to call when the object path is unregistered.
5049 * @error: Return location for error or %NULL.
5051 * Registers callbacks for exported objects at @object_path with the
5052 * D-Bus interface that is described in @interface_info.
5054 * Calls to functions in @vtable (and @user_data_free_func) will
5055 * happen in the <link linkend="g-main-context-push-thread-default">thread-default main
5056 * loop</link> of the thread you are calling this method from.
5058 * Note that all #GVariant values passed to functions in @vtable will match
5059 * the signature given in @interface_info - if a remote caller passes
5060 * incorrect values, the <literal>org.freedesktop.DBus.Error.InvalidArgs</literal>
5061 * is returned to the remote caller.
5063 * Additionally, if the remote caller attempts to invoke methods or
5064 * access properties not mentioned in @interface_info the
5065 * <literal>org.freedesktop.DBus.Error.UnknownMethod</literal> resp.
5066 * <literal>org.freedesktop.DBus.Error.InvalidArgs</literal> errors
5067 * are returned to the caller.
5069 * It is considered a programming error if the
5070 * #GDBusInterfaceGetPropertyFunc function in @vtable returns a
5071 * #GVariant of incorrect type.
5073 * If an existing callback is already registered at @object_path and
5074 * @interface_name, then @error is set to #G_IO_ERROR_EXISTS.
5076 * GDBus automatically implements the standard D-Bus interfaces
5077 * org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable
5078 * and org.freedesktop.Peer, so you don't have to implement those for
5079 * the objects you export. You <emphasis>can</emphasis> implement
5080 * org.freedesktop.DBus.Properties yourself, e.g. to handle getting
5081 * and setting of properties asynchronously.
5083 * Note that the reference count on @interface_info will be
5084 * incremented by 1 (unless allocated statically, e.g. if the
5085 * reference count is -1, see g_dbus_interface_info_ref()) for as long
5086 * as the object is exported. Also note that @vtable will be copied.
5088 * See <xref linkend="gdbus-server"/> for an example of how to use this method.
5090 * Returns: 0 if @error is set, otherwise a registration id (never 0)
5091 * that can be used with g_dbus_connection_unregister_object() .
5096 g_dbus_connection_register_object (GDBusConnection *connection,
5097 const gchar *object_path,
5098 GDBusInterfaceInfo *interface_info,
5099 const GDBusInterfaceVTable *vtable,
5101 GDestroyNotify user_data_free_func,
5105 ExportedInterface *ei;
5108 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
5109 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
5110 g_return_val_if_fail (interface_info != NULL, 0);
5111 g_return_val_if_fail (g_dbus_is_interface_name (interface_info->name), 0);
5112 g_return_val_if_fail (error == NULL || *error == NULL, 0);
5113 g_return_val_if_fail (check_initialized (connection), 0);
5117 CONNECTION_LOCK (connection);
5119 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
5122 eo = g_new0 (ExportedObject, 1);
5123 eo->object_path = g_strdup (object_path);
5124 eo->connection = connection;
5125 eo->map_if_name_to_ei = g_hash_table_new_full (g_str_hash,
5128 (GDestroyNotify) exported_interface_free);
5129 g_hash_table_insert (connection->map_object_path_to_eo, eo->object_path, eo);
5132 ei = g_hash_table_lookup (eo->map_if_name_to_ei, interface_info->name);
5138 _("An object is already exported for the interface %s at %s"),
5139 interface_info->name,
5144 ei = g_new0 (ExportedInterface, 1);
5145 ei->id = _global_registration_id++; /* TODO: overflow etc. */
5147 ei->user_data = user_data;
5148 ei->user_data_free_func = user_data_free_func;
5149 ei->vtable = _g_dbus_interface_vtable_copy (vtable);
5150 ei->interface_info = g_dbus_interface_info_ref (interface_info);
5151 g_dbus_interface_info_cache_build (ei->interface_info);
5152 ei->interface_name = g_strdup (interface_info->name);
5153 ei->context = g_main_context_ref_thread_default ();
5155 g_hash_table_insert (eo->map_if_name_to_ei,
5156 (gpointer) ei->interface_name,
5158 g_hash_table_insert (connection->map_id_to_ei,
5159 GUINT_TO_POINTER (ei->id),
5165 CONNECTION_UNLOCK (connection);
5171 * g_dbus_connection_unregister_object:
5172 * @connection: A #GDBusConnection.
5173 * @registration_id: A registration id obtained from g_dbus_connection_register_object().
5175 * Unregisters an object.
5177 * Returns: %TRUE if the object was unregistered, %FALSE otherwise.
5182 g_dbus_connection_unregister_object (GDBusConnection *connection,
5183 guint registration_id)
5185 ExportedInterface *ei;
5189 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5190 g_return_val_if_fail (check_initialized (connection), FALSE);
5194 CONNECTION_LOCK (connection);
5196 ei = g_hash_table_lookup (connection->map_id_to_ei,
5197 GUINT_TO_POINTER (registration_id));
5203 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_ei, GUINT_TO_POINTER (ei->id)));
5204 g_warn_if_fail (g_hash_table_remove (eo->map_if_name_to_ei, ei->interface_name));
5205 /* unregister object path if we have no more exported interfaces */
5206 if (g_hash_table_size (eo->map_if_name_to_ei) == 0)
5207 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_eo,
5213 CONNECTION_UNLOCK (connection);
5218 /* ---------------------------------------------------------------------------------------------------- */
5221 * g_dbus_connection_emit_signal:
5222 * @connection: A #GDBusConnection.
5223 * @destination_bus_name: (allow-none): The unique bus name for the destination
5224 * for the signal or %NULL to emit to all listeners.
5225 * @object_path: Path of remote object.
5226 * @interface_name: D-Bus interface to emit a signal on.
5227 * @signal_name: The name of the signal to emit.
5228 * @parameters: (allow-none): A #GVariant tuple with parameters for the signal
5229 * or %NULL if not passing parameters.
5230 * @error: Return location for error or %NULL.
5234 * If the parameters GVariant is floating, it is consumed.
5236 * This can only fail if @parameters is not compatible with the D-Bus protocol.
5238 * Returns: %TRUE unless @error is set.
5243 g_dbus_connection_emit_signal (GDBusConnection *connection,
5244 const gchar *destination_bus_name,
5245 const gchar *object_path,
5246 const gchar *interface_name,
5247 const gchar *signal_name,
5248 GVariant *parameters,
5251 GDBusMessage *message;
5257 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
5258 g_return_val_if_fail (destination_bus_name == NULL || g_dbus_is_name (destination_bus_name), FALSE);
5259 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), FALSE);
5260 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), FALSE);
5261 g_return_val_if_fail (signal_name != NULL && g_dbus_is_member_name (signal_name), FALSE);
5262 g_return_val_if_fail (parameters == NULL || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), FALSE);
5263 g_return_val_if_fail (check_initialized (connection), FALSE);
5265 if (G_UNLIKELY (_g_dbus_debug_emission ()))
5267 _g_dbus_debug_print_lock ();
5268 g_print ("========================================================================\n"
5269 "GDBus-debug:Emission:\n"
5270 " >>>> SIGNAL EMISSION %s.%s()\n"
5272 " destination %s\n",
5273 interface_name, signal_name,
5275 destination_bus_name != NULL ? destination_bus_name : "(none)");
5276 _g_dbus_debug_print_unlock ();
5279 message = g_dbus_message_new_signal (object_path,
5283 if (destination_bus_name != NULL)
5284 g_dbus_message_set_header (message,
5285 G_DBUS_MESSAGE_HEADER_FIELD_DESTINATION,
5286 g_variant_new_string (destination_bus_name));
5288 if (parameters != NULL)
5289 g_dbus_message_set_body (message, parameters);
5291 ret = g_dbus_connection_send_message (connection, message, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, error);
5292 g_object_unref (message);
5298 add_call_flags (GDBusMessage *message,
5299 GDBusCallFlags flags)
5301 if (flags & G_DBUS_CALL_FLAGS_NO_AUTO_START)
5302 g_dbus_message_set_flags (message, G_DBUS_MESSAGE_FLAGS_NO_AUTO_START);
5306 decode_method_reply (GDBusMessage *reply,
5307 const gchar *method_name,
5308 const GVariantType *reply_type,
5309 GUnixFDList **out_fd_list,
5315 switch (g_dbus_message_get_message_type (reply))
5317 case G_DBUS_MESSAGE_TYPE_METHOD_RETURN:
5318 result = g_dbus_message_get_body (reply);
5321 result = g_variant_new ("()");
5322 g_variant_ref_sink (result);
5326 g_variant_ref (result);
5329 if (!g_variant_is_of_type (result, reply_type))
5331 gchar *type_string = g_variant_type_dup_string (reply_type);
5335 G_IO_ERROR_INVALID_ARGUMENT,
5336 _("Method '%s' returned type '%s', but expected '%s'"),
5337 method_name, g_variant_get_type_string (result), type_string);
5339 g_variant_unref (result);
5340 g_free (type_string);
5347 if (out_fd_list != NULL)
5349 *out_fd_list = g_dbus_message_get_unix_fd_list (reply);
5350 if (*out_fd_list != NULL)
5351 g_object_ref (*out_fd_list);
5357 case G_DBUS_MESSAGE_TYPE_ERROR:
5358 g_dbus_message_to_gerror (reply, error);
5362 g_assert_not_reached ();
5372 GSimpleAsyncResult *simple;
5373 GVariantType *reply_type;
5374 gchar *method_name; /* for error message */
5378 GUnixFDList *fd_list;
5382 call_state_free (CallState *state)
5384 g_variant_type_free (state->reply_type);
5385 g_free (state->method_name);
5387 if (state->value != NULL)
5388 g_variant_unref (state->value);
5389 if (state->fd_list != NULL)
5390 g_object_unref (state->fd_list);
5391 g_slice_free (CallState, state);
5394 /* called in any thread, with the connection's lock not held */
5396 g_dbus_connection_call_done (GObject *source,
5397 GAsyncResult *result,
5400 GSimpleAsyncResult *simple;
5401 GDBusConnection *connection = G_DBUS_CONNECTION (source);
5402 CallState *state = user_data;
5404 GDBusMessage *reply;
5407 reply = g_dbus_connection_send_message_with_reply_finish (connection,
5411 if (G_UNLIKELY (_g_dbus_debug_call ()))
5413 _g_dbus_debug_print_lock ();
5414 g_print ("========================================================================\n"
5415 "GDBus-debug:Call:\n"
5416 " <<<< ASYNC COMPLETE %s() (serial %d)\n"
5422 g_print ("SUCCESS\n");
5426 g_print ("FAILED: %s\n",
5429 _g_dbus_debug_print_unlock ();
5433 state->value = decode_method_reply (reply, state->method_name, state->reply_type, &state->fd_list, &error);
5435 simple = state->simple; /* why? because state is freed before we unref simple.. */
5438 g_simple_async_result_take_error (state->simple, error);
5439 g_simple_async_result_complete (state->simple);
5440 call_state_free (state);
5444 g_simple_async_result_set_op_res_gpointer (state->simple, state, (GDestroyNotify) call_state_free);
5445 g_simple_async_result_complete (state->simple);
5447 g_clear_object (&reply);
5448 g_object_unref (simple);
5451 /* called in any thread, with the connection's lock not held */
5453 g_dbus_connection_call_internal (GDBusConnection *connection,
5454 const gchar *bus_name,
5455 const gchar *object_path,
5456 const gchar *interface_name,
5457 const gchar *method_name,
5458 GVariant *parameters,
5459 const GVariantType *reply_type,
5460 GDBusCallFlags flags,
5462 GUnixFDList *fd_list,
5463 GCancellable *cancellable,
5464 GAsyncReadyCallback callback,
5467 GDBusMessage *message;
5470 g_return_if_fail (G_IS_DBUS_CONNECTION (connection));
5471 g_return_if_fail (bus_name == NULL || g_dbus_is_name (bus_name));
5472 g_return_if_fail (object_path != NULL && g_variant_is_object_path (object_path));
5473 g_return_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name));
5474 g_return_if_fail (method_name != NULL && g_dbus_is_member_name (method_name));
5475 g_return_if_fail (timeout_msec >= 0 || timeout_msec == -1);
5476 g_return_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE));
5477 g_return_if_fail (check_initialized (connection));
5479 g_return_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list));
5481 g_return_if_fail (fd_list == NULL);
5484 message = g_dbus_message_new_method_call (bus_name,
5488 add_call_flags (message, flags);
5489 if (parameters != NULL)
5490 g_dbus_message_set_body (message, parameters);
5493 if (fd_list != NULL)
5494 g_dbus_message_set_unix_fd_list (message, fd_list);
5497 /* If the user has no callback then we can just send the message with
5498 * the G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set and skip all
5499 * the logic for processing the reply. If the service sends the reply
5500 * anyway then it will just be ignored.
5502 if (callback != NULL)
5506 state = g_slice_new0 (CallState);
5507 state->simple = g_simple_async_result_new (G_OBJECT (connection),
5508 callback, user_data,
5509 g_dbus_connection_call_internal);
5510 g_simple_async_result_set_check_cancellable (state->simple, cancellable);
5511 state->method_name = g_strjoin (".", interface_name, method_name, NULL);
5513 if (reply_type == NULL)
5514 reply_type = G_VARIANT_TYPE_ANY;
5516 state->reply_type = g_variant_type_copy (reply_type);
5518 g_dbus_connection_send_message_with_reply (connection,
5520 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5524 g_dbus_connection_call_done,
5526 serial = state->serial;
5530 GDBusMessageFlags flags;
5532 flags = g_dbus_message_get_flags (message);
5533 flags |= G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED;
5534 g_dbus_message_set_flags (message, flags);
5536 g_dbus_connection_send_message (connection,
5538 G_DBUS_SEND_MESSAGE_FLAGS_NONE,
5542 if (G_UNLIKELY (_g_dbus_debug_call ()))
5544 _g_dbus_debug_print_lock ();
5545 g_print ("========================================================================\n"
5546 "GDBus-debug:Call:\n"
5547 " >>>> ASYNC %s.%s()\n"
5549 " owned by name %s (serial %d)\n",
5553 bus_name != NULL ? bus_name : "(none)",
5555 _g_dbus_debug_print_unlock ();
5558 if (message != NULL)
5559 g_object_unref (message);
5562 /* called in any thread, with the connection's lock not held */
5564 g_dbus_connection_call_finish_internal (GDBusConnection *connection,
5565 GUnixFDList **out_fd_list,
5569 GSimpleAsyncResult *simple;
5572 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5573 g_return_val_if_fail (g_simple_async_result_is_valid (res, G_OBJECT (connection),
5574 g_dbus_connection_call_internal), NULL);
5575 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5577 simple = G_SIMPLE_ASYNC_RESULT (res);
5579 if (g_simple_async_result_propagate_error (simple, error))
5582 state = g_simple_async_result_get_op_res_gpointer (simple);
5583 if (out_fd_list != NULL)
5584 *out_fd_list = state->fd_list != NULL ? g_object_ref (state->fd_list) : NULL;
5585 return g_variant_ref (state->value);
5588 /* called in any user thread, with the connection's lock not held */
5590 g_dbus_connection_call_sync_internal (GDBusConnection *connection,
5591 const gchar *bus_name,
5592 const gchar *object_path,
5593 const gchar *interface_name,
5594 const gchar *method_name,
5595 GVariant *parameters,
5596 const GVariantType *reply_type,
5597 GDBusCallFlags flags,
5599 GUnixFDList *fd_list,
5600 GUnixFDList **out_fd_list,
5601 GCancellable *cancellable,
5604 GDBusMessage *message;
5605 GDBusMessage *reply;
5607 GError *local_error;
5608 GDBusSendMessageFlags send_flags;
5614 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
5615 g_return_val_if_fail (bus_name == NULL || g_dbus_is_name (bus_name), NULL);
5616 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), NULL);
5617 g_return_val_if_fail (interface_name != NULL && g_dbus_is_interface_name (interface_name), NULL);
5618 g_return_val_if_fail (method_name != NULL && g_dbus_is_member_name (method_name), NULL);
5619 g_return_val_if_fail (timeout_msec >= 0 || timeout_msec == -1, NULL);
5620 g_return_val_if_fail ((parameters == NULL) || g_variant_is_of_type (parameters, G_VARIANT_TYPE_TUPLE), NULL);
5622 g_return_val_if_fail (fd_list == NULL || G_IS_UNIX_FD_LIST (fd_list), NULL);
5624 g_return_val_if_fail (fd_list == NULL, NULL);
5626 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
5628 if (!(flags & CALL_FLAGS_INITIALIZING))
5629 g_return_val_if_fail (check_initialized (connection), FALSE);
5631 if (reply_type == NULL)
5632 reply_type = G_VARIANT_TYPE_ANY;
5634 message = g_dbus_message_new_method_call (bus_name,
5638 add_call_flags (message, flags);
5639 if (parameters != NULL)
5640 g_dbus_message_set_body (message, parameters);
5643 if (fd_list != NULL)
5644 g_dbus_message_set_unix_fd_list (message, fd_list);
5647 if (G_UNLIKELY (_g_dbus_debug_call ()))
5649 _g_dbus_debug_print_lock ();
5650 g_print ("========================================================================\n"
5651 "GDBus-debug:Call:\n"
5652 " >>>> SYNC %s.%s()\n"
5654 " owned by name %s\n",
5658 bus_name != NULL ? bus_name : "(none)");
5659 _g_dbus_debug_print_unlock ();
5664 send_flags = G_DBUS_SEND_MESSAGE_FLAGS_NONE;
5666 /* translate from one flavour of flags to another... */
5667 if (flags & CALL_FLAGS_INITIALIZING)
5668 send_flags |= SEND_MESSAGE_FLAGS_INITIALIZING;
5670 reply = g_dbus_connection_send_message_with_reply_sync (connection,
5674 NULL, /* volatile guint32 *out_serial */
5678 if (G_UNLIKELY (_g_dbus_debug_call ()))
5680 _g_dbus_debug_print_lock ();
5681 g_print ("========================================================================\n"
5682 "GDBus-debug:Call:\n"
5683 " <<<< SYNC COMPLETE %s.%s()\n"
5689 g_print ("SUCCESS\n");
5693 g_print ("FAILED: %s\n",
5694 local_error->message);
5696 _g_dbus_debug_print_unlock ();
5702 *error = local_error;
5704 g_error_free (local_error);
5708 result = decode_method_reply (reply, method_name, reply_type, out_fd_list, error);
5711 if (message != NULL)
5712 g_object_unref (message);
5714 g_object_unref (reply);
5719 /* ---------------------------------------------------------------------------------------------------- */
5722 * g_dbus_connection_call:
5723 * @connection: A #GDBusConnection.
5724 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5725 * @connection is not a message bus connection.
5726 * @object_path: Path of remote object.
5727 * @interface_name: D-Bus interface to invoke method on.
5728 * @method_name: The name of the method to invoke.
5729 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5730 * or %NULL if not passing parameters.
5731 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5732 * @flags: Flags from the #GDBusCallFlags enumeration.
5733 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5734 * timeout or %G_MAXINT for no timeout.
5735 * @cancellable: (allow-none): A #GCancellable or %NULL.
5736 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5737 * satisfied or %NULL if you don't care about the result of the
5738 * method invocation.
5739 * @user_data: The data to pass to @callback.
5741 * Asynchronously invokes the @method_name method on the
5742 * @interface_name D-Bus interface on the remote object at
5743 * @object_path owned by @bus_name.
5745 * If @connection is closed then the operation will fail with
5746 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the operation will
5747 * fail with %G_IO_ERROR_CANCELLED. If @parameters contains a value
5748 * not compatible with the D-Bus protocol, the operation fails with
5749 * %G_IO_ERROR_INVALID_ARGUMENT.
5751 * If @reply_type is non-%NULL then the reply will be checked for having this type and an
5752 * error will be raised if it does not match. Said another way, if you give a @reply_type
5753 * then any non-%NULL return value will be of this type.
5755 * If the @parameters #GVariant is floating, it is consumed. This allows
5756 * convenient 'inline' use of g_variant_new(), e.g.:
5758 * g_dbus_connection_call (connection,
5759 * "org.freedesktop.StringThings",
5760 * "/org/freedesktop/StringThings",
5761 * "org.freedesktop.StringThings",
5763 * g_variant_new ("(ss)",
5767 * G_DBUS_CALL_FLAGS_NONE,
5770 * (GAsyncReadyCallback) two_strings_done,
5774 * This is an asynchronous method. When the operation is finished, @callback will be invoked
5775 * in the <link linkend="g-main-context-push-thread-default">thread-default main loop</link>
5776 * of the thread you are calling this method from. You can then call
5777 * g_dbus_connection_call_finish() to get the result of the operation.
5778 * See g_dbus_connection_call_sync() for the synchronous version of this
5781 * If @callback is %NULL then the D-Bus method call message will be sent with
5782 * the %G_DBUS_MESSAGE_FLAGS_NO_REPLY_EXPECTED flag set.
5787 g_dbus_connection_call (GDBusConnection *connection,
5788 const gchar *bus_name,
5789 const gchar *object_path,
5790 const gchar *interface_name,
5791 const gchar *method_name,
5792 GVariant *parameters,
5793 const GVariantType *reply_type,
5794 GDBusCallFlags flags,
5796 GCancellable *cancellable,
5797 GAsyncReadyCallback callback,
5800 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);
5804 * g_dbus_connection_call_finish:
5805 * @connection: A #GDBusConnection.
5806 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call().
5807 * @error: Return location for error or %NULL.
5809 * Finishes an operation started with g_dbus_connection_call().
5811 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5812 * return values. Free with g_variant_unref().
5817 g_dbus_connection_call_finish (GDBusConnection *connection,
5821 return g_dbus_connection_call_finish_internal (connection, NULL, res, error);
5825 * g_dbus_connection_call_sync:
5826 * @connection: A #GDBusConnection.
5827 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5828 * @connection is not a message bus connection.
5829 * @object_path: Path of remote object.
5830 * @interface_name: D-Bus interface to invoke method on.
5831 * @method_name: The name of the method to invoke.
5832 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5833 * or %NULL if not passing parameters.
5834 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5835 * @flags: Flags from the #GDBusCallFlags enumeration.
5836 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5837 * timeout or %G_MAXINT for no timeout.
5838 * @cancellable: (allow-none): A #GCancellable or %NULL.
5839 * @error: Return location for error or %NULL.
5841 * Synchronously invokes the @method_name method on the
5842 * @interface_name D-Bus interface on the remote object at
5843 * @object_path owned by @bus_name.
5845 * If @connection is closed then the operation will fail with
5846 * %G_IO_ERROR_CLOSED. If @cancellable is canceled, the
5847 * operation will fail with %G_IO_ERROR_CANCELLED. If @parameters
5848 * contains a value not compatible with the D-Bus protocol, the operation
5849 * fails with %G_IO_ERROR_INVALID_ARGUMENT.
5851 * If @reply_type is non-%NULL then the reply will be checked for having
5852 * this type and an error will be raised if it does not match. Said
5853 * another way, if you give a @reply_type then any non-%NULL return
5854 * value will be of this type.
5856 * If the @parameters #GVariant is floating, it is consumed.
5857 * This allows convenient 'inline' use of g_variant_new(), e.g.:
5859 * g_dbus_connection_call_sync (connection,
5860 * "org.freedesktop.StringThings",
5861 * "/org/freedesktop/StringThings",
5862 * "org.freedesktop.StringThings",
5864 * g_variant_new ("(ss)",
5868 * G_DBUS_CALL_FLAGS_NONE,
5874 * The calling thread is blocked until a reply is received. See
5875 * g_dbus_connection_call() for the asynchronous version of
5878 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5879 * return values. Free with g_variant_unref().
5884 g_dbus_connection_call_sync (GDBusConnection *connection,
5885 const gchar *bus_name,
5886 const gchar *object_path,
5887 const gchar *interface_name,
5888 const gchar *method_name,
5889 GVariant *parameters,
5890 const GVariantType *reply_type,
5891 GDBusCallFlags flags,
5893 GCancellable *cancellable,
5896 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);
5899 /* ---------------------------------------------------------------------------------------------------- */
5904 * g_dbus_connection_call_with_unix_fd_list:
5905 * @connection: A #GDBusConnection.
5906 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5907 * @connection is not a message bus connection.
5908 * @object_path: Path of remote object.
5909 * @interface_name: D-Bus interface to invoke method on.
5910 * @method_name: The name of the method to invoke.
5911 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5912 * or %NULL if not passing parameters.
5913 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5914 * @flags: Flags from the #GDBusCallFlags enumeration.
5915 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5916 * timeout or %G_MAXINT for no timeout.
5917 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5918 * @cancellable: (allow-none): A #GCancellable or %NULL.
5919 * @callback: (allow-none): A #GAsyncReadyCallback to call when the request is
5920 * satisfied or %NULL if you don't * care about the result of the
5921 * method invocation.
5922 * @user_data: The data to pass to @callback.
5924 * Like g_dbus_connection_call() but also takes a #GUnixFDList object.
5926 * This method is only available on UNIX.
5931 g_dbus_connection_call_with_unix_fd_list (GDBusConnection *connection,
5932 const gchar *bus_name,
5933 const gchar *object_path,
5934 const gchar *interface_name,
5935 const gchar *method_name,
5936 GVariant *parameters,
5937 const GVariantType *reply_type,
5938 GDBusCallFlags flags,
5940 GUnixFDList *fd_list,
5941 GCancellable *cancellable,
5942 GAsyncReadyCallback callback,
5945 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);
5949 * g_dbus_connection_call_with_unix_fd_list_finish:
5950 * @connection: A #GDBusConnection.
5951 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5952 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_dbus_connection_call_with_unix_fd_list().
5953 * @error: Return location for error or %NULL.
5955 * Finishes an operation started with g_dbus_connection_call_with_unix_fd_list().
5957 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5958 * return values. Free with g_variant_unref().
5963 g_dbus_connection_call_with_unix_fd_list_finish (GDBusConnection *connection,
5964 GUnixFDList **out_fd_list,
5968 return g_dbus_connection_call_finish_internal (connection, out_fd_list, res, error);
5972 * g_dbus_connection_call_with_unix_fd_list_sync:
5973 * @connection: A #GDBusConnection.
5974 * @bus_name: (allow-none): A unique or well-known bus name or %NULL if
5975 * @connection is not a message bus connection.
5976 * @object_path: Path of remote object.
5977 * @interface_name: D-Bus interface to invoke method on.
5978 * @method_name: The name of the method to invoke.
5979 * @parameters: (allow-none): A #GVariant tuple with parameters for the method
5980 * or %NULL if not passing parameters.
5981 * @reply_type: (allow-none): The expected type of the reply, or %NULL.
5982 * @flags: Flags from the #GDBusCallFlags enumeration.
5983 * @timeout_msec: The timeout in milliseconds, -1 to use the default
5984 * timeout or %G_MAXINT for no timeout.
5985 * @fd_list: (allow-none): A #GUnixFDList or %NULL.
5986 * @out_fd_list: (out) (allow-none): Return location for a #GUnixFDList or %NULL.
5987 * @cancellable: (allow-none): A #GCancellable or %NULL.
5988 * @error: Return location for error or %NULL.
5990 * Like g_dbus_connection_call_sync() but also takes and returns #GUnixFDList objects.
5992 * This method is only available on UNIX.
5994 * Returns: %NULL if @error is set. Otherwise a #GVariant tuple with
5995 * return values. Free with g_variant_unref().
6000 g_dbus_connection_call_with_unix_fd_list_sync (GDBusConnection *connection,
6001 const gchar *bus_name,
6002 const gchar *object_path,
6003 const gchar *interface_name,
6004 const gchar *method_name,
6005 GVariant *parameters,
6006 const GVariantType *reply_type,
6007 GDBusCallFlags flags,
6009 GUnixFDList *fd_list,
6010 GUnixFDList **out_fd_list,
6011 GCancellable *cancellable,
6014 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);
6017 #endif /* G_OS_UNIX */
6019 /* ---------------------------------------------------------------------------------------------------- */
6021 struct ExportedSubtree
6025 GDBusConnection *connection;
6026 GDBusSubtreeVTable *vtable;
6027 GDBusSubtreeFlags flags;
6029 GMainContext *context;
6031 GDestroyNotify user_data_free_func;
6035 exported_subtree_free (ExportedSubtree *es)
6037 call_destroy_notify (es->context,
6038 es->user_data_free_func,
6041 g_main_context_unref (es->context);
6043 _g_dbus_subtree_vtable_free (es->vtable);
6044 g_free (es->object_path);
6048 /* called without lock held in the thread where the caller registered
6052 handle_subtree_introspect (GDBusConnection *connection,
6053 ExportedSubtree *es,
6054 GDBusMessage *message)
6058 GDBusMessage *reply;
6061 const gchar *sender;
6062 const gchar *requested_object_path;
6063 const gchar *requested_node;
6064 GDBusInterfaceInfo **interfaces;
6066 gchar **subnode_paths;
6067 gboolean has_properties_interface;
6068 gboolean has_introspectable_interface;
6072 requested_object_path = g_dbus_message_get_path (message);
6073 sender = g_dbus_message_get_sender (message);
6074 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6076 s = g_string_new (NULL);
6077 introspect_append_header (s);
6079 /* Strictly we don't need the children in dynamic mode, but we avoid the
6080 * conditionals to preserve code clarity
6082 children = es->vtable->enumerate (es->connection,
6089 requested_node = strrchr (requested_object_path, '/') + 1;
6091 /* Assert existence of object if we are not dynamic */
6092 if (!(es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES) &&
6093 !_g_strv_has_string ((const gchar * const *) children, requested_node))
6098 requested_node = NULL;
6101 interfaces = es->vtable->introspect (es->connection,
6106 if (interfaces != NULL)
6108 has_properties_interface = FALSE;
6109 has_introspectable_interface = FALSE;
6111 for (n = 0; interfaces[n] != NULL; n++)
6113 if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Properties") == 0)
6114 has_properties_interface = TRUE;
6115 else if (strcmp (interfaces[n]->name, "org.freedesktop.DBus.Introspectable") == 0)
6116 has_introspectable_interface = TRUE;
6118 if (!has_properties_interface)
6119 g_string_append (s, introspect_properties_interface);
6120 if (!has_introspectable_interface)
6121 g_string_append (s, introspect_introspectable_interface);
6123 for (n = 0; interfaces[n] != NULL; n++)
6125 g_dbus_interface_info_generate_xml (interfaces[n], 2, s);
6126 g_dbus_interface_info_unref (interfaces[n]);
6128 g_free (interfaces);
6131 /* then include <node> entries from the Subtree for the root */
6134 for (n = 0; children != NULL && children[n] != NULL; n++)
6135 g_string_append_printf (s, " <node name=\"%s\"/>\n", children[n]);
6138 /* finally include nodes registered below us */
6139 subnode_paths = g_dbus_connection_list_registered (es->connection, requested_object_path);
6140 for (n = 0; subnode_paths != NULL && subnode_paths[n] != NULL; n++)
6141 g_string_append_printf (s, " <node name=\"%s\"/>\n", subnode_paths[n]);
6142 g_strfreev (subnode_paths);
6144 g_string_append (s, "</node>\n");
6146 reply = g_dbus_message_new_method_reply (message);
6147 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6148 g_dbus_connection_send_message (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6149 g_object_unref (reply);
6154 g_string_free (s, TRUE);
6155 g_strfreev (children);
6159 /* called without lock held in the thread where the caller registered
6163 handle_subtree_method_invocation (GDBusConnection *connection,
6164 ExportedSubtree *es,
6165 GDBusMessage *message)
6168 const gchar *sender;
6169 const gchar *interface_name;
6170 const gchar *member;
6171 const gchar *signature;
6172 const gchar *requested_object_path;
6173 const gchar *requested_node;
6175 GDBusInterfaceInfo *interface_info;
6176 const GDBusInterfaceVTable *interface_vtable;
6177 gpointer interface_user_data;
6179 GDBusInterfaceInfo **interfaces;
6180 gboolean is_property_get;
6181 gboolean is_property_set;
6182 gboolean is_property_get_all;
6187 requested_object_path = g_dbus_message_get_path (message);
6188 sender = g_dbus_message_get_sender (message);
6189 interface_name = g_dbus_message_get_interface (message);
6190 member = g_dbus_message_get_member (message);
6191 signature = g_dbus_message_get_signature (message);
6192 is_root = (g_strcmp0 (requested_object_path, es->object_path) == 0);
6194 is_property_get = FALSE;
6195 is_property_set = FALSE;
6196 is_property_get_all = FALSE;
6197 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Properties") == 0)
6199 if (g_strcmp0 (member, "Get") == 0 && g_strcmp0 (signature, "ss") == 0)
6200 is_property_get = TRUE;
6201 else if (g_strcmp0 (member, "Set") == 0 && g_strcmp0 (signature, "ssv") == 0)
6202 is_property_set = TRUE;
6203 else if (g_strcmp0 (member, "GetAll") == 0 && g_strcmp0 (signature, "s") == 0)
6204 is_property_get_all = TRUE;
6209 requested_node = strrchr (requested_object_path, '/') + 1;
6211 if (~es->flags & G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES)
6213 /* We don't want to dispatch to unenumerated
6214 * nodes, so ensure that the child exists.
6219 children = es->vtable->enumerate (es->connection,
6224 exists = _g_strv_has_string ((const gchar * const *) children, requested_node);
6225 g_strfreev (children);
6233 requested_node = NULL;
6236 /* get introspection data for the node */
6237 interfaces = es->vtable->introspect (es->connection,
6239 requested_object_path,
6243 if (interfaces == NULL)
6246 interface_info = NULL;
6247 for (n = 0; interfaces[n] != NULL; n++)
6249 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6250 interface_info = interfaces[n];
6253 /* dispatch the call if the user wants to handle it */
6254 if (interface_info != NULL)
6256 /* figure out where to dispatch the method call */
6257 interface_user_data = NULL;
6258 interface_vtable = es->vtable->dispatch (es->connection,
6263 &interface_user_data,
6265 if (interface_vtable == NULL)
6268 CONNECTION_LOCK (connection);
6269 handled = validate_and_maybe_schedule_method_call (es->connection,
6276 interface_user_data);
6277 CONNECTION_UNLOCK (connection);
6279 /* handle org.freedesktop.DBus.Properties interface if not explicitly handled */
6280 else if (is_property_get || is_property_set || is_property_get_all)
6282 if (is_property_get)
6283 g_variant_get (g_dbus_message_get_body (message), "(&s&s)", &interface_name, NULL);
6284 else if (is_property_set)
6285 g_variant_get (g_dbus_message_get_body (message), "(&s&sv)", &interface_name, NULL, NULL);
6286 else if (is_property_get_all)
6287 g_variant_get (g_dbus_message_get_body (message), "(&s)", &interface_name, NULL, NULL);
6289 g_assert_not_reached ();
6291 /* see if the object supports this interface at all */
6292 for (n = 0; interfaces[n] != NULL; n++)
6294 if (g_strcmp0 (interfaces[n]->name, interface_name) == 0)
6295 interface_info = interfaces[n];
6298 /* Fail with org.freedesktop.DBus.Error.InvalidArgs if the user-code
6299 * claims it won't support the interface
6301 if (interface_info == NULL)
6303 GDBusMessage *reply;
6304 reply = g_dbus_message_new_method_error (message,
6305 "org.freedesktop.DBus.Error.InvalidArgs",
6306 _("No such interface '%s'"),
6308 g_dbus_connection_send_message (es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6309 g_object_unref (reply);
6314 /* figure out where to dispatch the property get/set/getall calls */
6315 interface_user_data = NULL;
6316 interface_vtable = es->vtable->dispatch (es->connection,
6321 &interface_user_data,
6323 if (interface_vtable == NULL)
6325 g_warning ("The subtree introspection function indicates that '%s' "
6326 "is a valid interface name, but calling the dispatch "
6327 "function on that interface gave us NULL", interface_name);
6331 if (is_property_get || is_property_set)
6333 CONNECTION_LOCK (connection);
6334 handled = validate_and_maybe_schedule_property_getset (es->connection,
6342 interface_user_data);
6343 CONNECTION_UNLOCK (connection);
6345 else if (is_property_get_all)
6347 CONNECTION_LOCK (connection);
6348 handled = validate_and_maybe_schedule_property_get_all (es->connection,
6355 interface_user_data);
6356 CONNECTION_UNLOCK (connection);
6361 if (interfaces != NULL)
6363 for (n = 0; interfaces[n] != NULL; n++)
6364 g_dbus_interface_info_unref (interfaces[n]);
6365 g_free (interfaces);
6373 GDBusMessage *message;
6374 ExportedSubtree *es;
6375 } SubtreeDeferredData;
6378 subtree_deferred_data_free (SubtreeDeferredData *data)
6380 g_object_unref (data->message);
6384 /* called without lock held in the thread where the caller registered the subtree */
6386 process_subtree_vtable_message_in_idle_cb (gpointer _data)
6388 SubtreeDeferredData *data = _data;
6393 if (g_strcmp0 (g_dbus_message_get_interface (data->message), "org.freedesktop.DBus.Introspectable") == 0 &&
6394 g_strcmp0 (g_dbus_message_get_member (data->message), "Introspect") == 0 &&
6395 g_strcmp0 (g_dbus_message_get_signature (data->message), "") == 0)
6396 handled = handle_subtree_introspect (data->es->connection,
6400 handled = handle_subtree_method_invocation (data->es->connection,
6406 CONNECTION_LOCK (data->es->connection);
6407 handled = handle_generic_unlocked (data->es->connection, data->message);
6408 CONNECTION_UNLOCK (data->es->connection);
6411 /* if we couldn't handle the request, just bail with the UnknownMethod error */
6414 GDBusMessage *reply;
6415 reply = g_dbus_message_new_method_error (data->message,
6416 "org.freedesktop.DBus.Error.UnknownMethod",
6417 _("Method '%s' on interface '%s' with signature '%s' does not exist"),
6418 g_dbus_message_get_member (data->message),
6419 g_dbus_message_get_interface (data->message),
6420 g_dbus_message_get_signature (data->message));
6421 g_dbus_connection_send_message (data->es->connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6422 g_object_unref (reply);
6428 /* called in GDBusWorker thread with connection's lock held */
6430 subtree_message_func (GDBusConnection *connection,
6431 ExportedSubtree *es,
6432 GDBusMessage *message)
6434 GSource *idle_source;
6435 SubtreeDeferredData *data;
6437 data = g_new0 (SubtreeDeferredData, 1);
6438 data->message = g_object_ref (message);
6441 /* defer this call to an idle handler in the right thread */
6442 idle_source = g_idle_source_new ();
6443 g_source_set_priority (idle_source, G_PRIORITY_HIGH);
6444 g_source_set_callback (idle_source,
6445 process_subtree_vtable_message_in_idle_cb,
6447 (GDestroyNotify) subtree_deferred_data_free);
6448 g_source_attach (idle_source, es->context);
6449 g_source_unref (idle_source);
6451 /* since we own the entire subtree, handlers for objects not in the subtree have been
6452 * tried already by libdbus-1 - so we just need to ensure that we're always going
6453 * to reply to the message
6459 * g_dbus_connection_register_subtree:
6460 * @connection: A #GDBusConnection.
6461 * @object_path: The object path to register the subtree at.
6462 * @vtable: A #GDBusSubtreeVTable to enumerate, introspect and dispatch nodes in the subtree.
6463 * @flags: Flags used to fine tune the behavior of the subtree.
6464 * @user_data: Data to pass to functions in @vtable.
6465 * @user_data_free_func: Function to call when the subtree is unregistered.
6466 * @error: Return location for error or %NULL.
6468 * Registers a whole subtree of <quote>dynamic</quote> objects.
6470 * The @enumerate and @introspection functions in @vtable are used to
6471 * convey, to remote callers, what nodes exist in the subtree rooted
6474 * When handling remote calls into any node in the subtree, first the
6475 * @enumerate function is used to check if the node exists. If the node exists
6476 * or the #G_DBUS_SUBTREE_FLAGS_DISPATCH_TO_UNENUMERATED_NODES flag is set
6477 * the @introspection function is used to check if the node supports the
6478 * requested method. If so, the @dispatch function is used to determine
6479 * where to dispatch the call. The collected #GDBusInterfaceVTable and
6480 * #gpointer will be used to call into the interface vtable for processing
6483 * All calls into user-provided code will be invoked in the <link
6484 * linkend="g-main-context-push-thread-default">thread-default main
6485 * loop</link> of the thread you are calling this method from.
6487 * If an existing subtree is already registered at @object_path or
6488 * then @error is set to #G_IO_ERROR_EXISTS.
6490 * Note that it is valid to register regular objects (using
6491 * g_dbus_connection_register_object()) in a subtree registered with
6492 * g_dbus_connection_register_subtree() - if so, the subtree handler
6493 * is tried as the last resort. One way to think about a subtree
6494 * handler is to consider it a <quote>fallback handler</quote>
6495 * for object paths not registered via g_dbus_connection_register_object()
6496 * or other bindings.
6498 * Note that @vtable will be copied so you cannot change it after
6501 * See <xref linkend="gdbus-subtree-server"/> for an example of how to use this method.
6503 * Returns: 0 if @error is set, otherwise a subtree registration id (never 0)
6504 * that can be used with g_dbus_connection_unregister_subtree() .
6509 g_dbus_connection_register_subtree (GDBusConnection *connection,
6510 const gchar *object_path,
6511 const GDBusSubtreeVTable *vtable,
6512 GDBusSubtreeFlags flags,
6514 GDestroyNotify user_data_free_func,
6518 ExportedSubtree *es;
6520 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
6521 g_return_val_if_fail (object_path != NULL && g_variant_is_object_path (object_path), 0);
6522 g_return_val_if_fail (vtable != NULL, 0);
6523 g_return_val_if_fail (error == NULL || *error == NULL, 0);
6524 g_return_val_if_fail (check_initialized (connection), 0);
6528 CONNECTION_LOCK (connection);
6530 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6536 _("A subtree is already exported for %s"),
6541 es = g_new0 (ExportedSubtree, 1);
6542 es->object_path = g_strdup (object_path);
6543 es->connection = connection;
6545 es->vtable = _g_dbus_subtree_vtable_copy (vtable);
6547 es->id = _global_subtree_registration_id++; /* TODO: overflow etc. */
6548 es->user_data = user_data;
6549 es->user_data_free_func = user_data_free_func;
6550 es->context = g_main_context_ref_thread_default ();
6552 g_hash_table_insert (connection->map_object_path_to_es, es->object_path, es);
6553 g_hash_table_insert (connection->map_id_to_es,
6554 GUINT_TO_POINTER (es->id),
6560 CONNECTION_UNLOCK (connection);
6565 /* ---------------------------------------------------------------------------------------------------- */
6568 * g_dbus_connection_unregister_subtree:
6569 * @connection: A #GDBusConnection.
6570 * @registration_id: A subtree registration id obtained from g_dbus_connection_register_subtree().
6572 * Unregisters a subtree.
6574 * Returns: %TRUE if the subtree was unregistered, %FALSE otherwise.
6579 g_dbus_connection_unregister_subtree (GDBusConnection *connection,
6580 guint registration_id)
6582 ExportedSubtree *es;
6585 g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), FALSE);
6586 g_return_val_if_fail (check_initialized (connection), FALSE);
6590 CONNECTION_LOCK (connection);
6592 es = g_hash_table_lookup (connection->map_id_to_es,
6593 GUINT_TO_POINTER (registration_id));
6597 g_warn_if_fail (g_hash_table_remove (connection->map_id_to_es, GUINT_TO_POINTER (es->id)));
6598 g_warn_if_fail (g_hash_table_remove (connection->map_object_path_to_es, es->object_path));
6603 CONNECTION_UNLOCK (connection);
6608 /* ---------------------------------------------------------------------------------------------------- */
6610 /* may be called in any thread, with connection's lock held */
6612 handle_generic_ping_unlocked (GDBusConnection *connection,
6613 const gchar *object_path,
6614 GDBusMessage *message)
6616 GDBusMessage *reply;
6617 reply = g_dbus_message_new_method_reply (message);
6618 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6619 g_object_unref (reply);
6622 /* may be called in any thread, with connection's lock held */
6624 handle_generic_get_machine_id_unlocked (GDBusConnection *connection,
6625 const gchar *object_path,
6626 GDBusMessage *message)
6628 GDBusMessage *reply;
6631 if (connection->machine_id == NULL)
6636 connection->machine_id = _g_dbus_get_machine_id (&error);
6637 if (connection->machine_id == NULL)
6639 reply = g_dbus_message_new_method_error_literal (message,
6640 "org.freedesktop.DBus.Error.Failed",
6642 g_error_free (error);
6648 reply = g_dbus_message_new_method_reply (message);
6649 g_dbus_message_set_body (reply, g_variant_new ("(s)", connection->machine_id));
6651 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6652 g_object_unref (reply);
6655 /* may be called in any thread, with connection's lock held */
6657 handle_generic_introspect_unlocked (GDBusConnection *connection,
6658 const gchar *object_path,
6659 GDBusMessage *message)
6664 GDBusMessage *reply;
6666 /* first the header */
6667 s = g_string_new (NULL);
6668 introspect_append_header (s);
6670 registered = g_dbus_connection_list_registered_unlocked (connection, object_path);
6671 for (n = 0; registered != NULL && registered[n] != NULL; n++)
6672 g_string_append_printf (s, " <node name=\"%s\"/>\n", registered[n]);
6673 g_strfreev (registered);
6674 g_string_append (s, "</node>\n");
6676 reply = g_dbus_message_new_method_reply (message);
6677 g_dbus_message_set_body (reply, g_variant_new ("(s)", s->str));
6678 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6679 g_object_unref (reply);
6680 g_string_free (s, TRUE);
6683 /* may be called in any thread, with connection's lock held */
6685 handle_generic_unlocked (GDBusConnection *connection,
6686 GDBusMessage *message)
6689 const gchar *interface_name;
6690 const gchar *member;
6691 const gchar *signature;
6694 CONNECTION_ENSURE_LOCK (connection);
6698 interface_name = g_dbus_message_get_interface (message);
6699 member = g_dbus_message_get_member (message);
6700 signature = g_dbus_message_get_signature (message);
6701 path = g_dbus_message_get_path (message);
6703 if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Introspectable") == 0 &&
6704 g_strcmp0 (member, "Introspect") == 0 &&
6705 g_strcmp0 (signature, "") == 0)
6707 handle_generic_introspect_unlocked (connection, path, message);
6710 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6711 g_strcmp0 (member, "Ping") == 0 &&
6712 g_strcmp0 (signature, "") == 0)
6714 handle_generic_ping_unlocked (connection, path, message);
6717 else if (g_strcmp0 (interface_name, "org.freedesktop.DBus.Peer") == 0 &&
6718 g_strcmp0 (member, "GetMachineId") == 0 &&
6719 g_strcmp0 (signature, "") == 0)
6721 handle_generic_get_machine_id_unlocked (connection, path, message);
6728 /* ---------------------------------------------------------------------------------------------------- */
6730 /* called in GDBusWorker thread with connection's lock held */
6732 distribute_method_call (GDBusConnection *connection,
6733 GDBusMessage *message)
6735 GDBusMessage *reply;
6737 ExportedSubtree *es;
6738 const gchar *object_path;
6739 const gchar *interface_name;
6740 const gchar *member;
6742 gchar *subtree_path;
6745 g_assert (g_dbus_message_get_message_type (message) == G_DBUS_MESSAGE_TYPE_METHOD_CALL);
6747 interface_name = g_dbus_message_get_interface (message);
6748 member = g_dbus_message_get_member (message);
6749 path = g_dbus_message_get_path (message);
6750 subtree_path = g_strdup (path);
6751 needle = strrchr (subtree_path, '/');
6752 if (needle != NULL && needle != subtree_path)
6758 g_free (subtree_path);
6759 subtree_path = NULL;
6763 if (G_UNLIKELY (_g_dbus_debug_incoming ()))
6765 _g_dbus_debug_print_lock ();
6766 g_print ("========================================================================\n"
6767 "GDBus-debug:Incoming:\n"
6768 " <<<< METHOD INVOCATION %s.%s()\n"
6770 " invoked by name %s\n"
6772 interface_name, member,
6774 g_dbus_message_get_sender (message) != NULL ? g_dbus_message_get_sender (message) : "(none)",
6775 g_dbus_message_get_serial (message));
6776 _g_dbus_debug_print_unlock ();
6779 object_path = g_dbus_message_get_path (message);
6780 g_assert (object_path != NULL);
6782 eo = g_hash_table_lookup (connection->map_object_path_to_eo, object_path);
6785 if (obj_message_func (connection, eo, message))
6789 es = g_hash_table_lookup (connection->map_object_path_to_es, object_path);
6792 if (subtree_message_func (connection, es, message))
6796 if (subtree_path != NULL)
6798 es = g_hash_table_lookup (connection->map_object_path_to_es, subtree_path);
6801 if (subtree_message_func (connection, es, message))
6806 if (handle_generic_unlocked (connection, message))
6809 /* if we end up here, the message has not been not handled - so return an error saying this */
6810 reply = g_dbus_message_new_method_error (message,
6811 "org.freedesktop.DBus.Error.UnknownMethod",
6812 _("No such interface '%s' on object at path %s"),
6815 g_dbus_connection_send_message_unlocked (connection, reply, G_DBUS_SEND_MESSAGE_FLAGS_NONE, NULL, NULL);
6816 g_object_unref (reply);
6819 g_free (subtree_path);
6822 /* ---------------------------------------------------------------------------------------------------- */
6824 /* Called in any user thread, with the message_bus_lock held. */
6826 message_bus_get_singleton (GBusType bus_type,
6830 const gchar *starter_bus;
6836 case G_BUS_TYPE_SESSION:
6837 ret = &the_session_bus;
6840 case G_BUS_TYPE_SYSTEM:
6841 ret = &the_system_bus;
6844 case G_BUS_TYPE_STARTER:
6845 starter_bus = g_getenv ("DBUS_STARTER_BUS_TYPE");
6846 if (g_strcmp0 (starter_bus, "session") == 0)
6848 ret = message_bus_get_singleton (G_BUS_TYPE_SESSION, error);
6851 else if (g_strcmp0 (starter_bus, "system") == 0)
6853 ret = message_bus_get_singleton (G_BUS_TYPE_SYSTEM, error);
6858 if (starter_bus != NULL)
6862 G_IO_ERROR_INVALID_ARGUMENT,
6863 _("Cannot determine bus address from DBUS_STARTER_BUS_TYPE environment variable"
6864 " - unknown value '%s'"),
6869 g_set_error_literal (error,
6871 G_IO_ERROR_INVALID_ARGUMENT,
6872 _("Cannot determine bus address because the DBUS_STARTER_BUS_TYPE environment "
6873 "variable is not set"));
6879 g_assert_not_reached ();
6887 /* Called in any user thread, without holding locks. */
6888 static GDBusConnection *
6889 get_uninitialized_connection (GBusType bus_type,
6890 GCancellable *cancellable,
6893 GWeakRef *singleton;
6894 GDBusConnection *ret;
6898 G_LOCK (message_bus_lock);
6899 singleton = message_bus_get_singleton (bus_type, error);
6900 if (singleton == NULL)
6903 ret = g_weak_ref_get (singleton);
6908 address = g_dbus_address_get_for_bus_sync (bus_type, cancellable, error);
6909 if (address == NULL)
6911 ret = g_object_new (G_TYPE_DBUS_CONNECTION,
6913 "flags", G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT |
6914 G_DBUS_CONNECTION_FLAGS_MESSAGE_BUS_CONNECTION,
6915 "exit-on-close", TRUE,
6918 g_weak_ref_set (singleton, ret);
6922 g_assert (ret != NULL);
6925 G_UNLOCK (message_bus_lock);
6929 /* May be called from any thread. Must not hold message_bus_lock. */
6931 _g_bus_get_singleton_if_exists (GBusType bus_type)
6933 GWeakRef *singleton;
6934 GDBusConnection *ret = NULL;
6936 G_LOCK (message_bus_lock);
6937 singleton = message_bus_get_singleton (bus_type, NULL);
6938 if (singleton == NULL)
6941 ret = g_weak_ref_get (singleton);
6944 G_UNLOCK (message_bus_lock);
6950 * @bus_type: A #GBusType.
6951 * @cancellable: (allow-none): A #GCancellable or %NULL.
6952 * @error: Return location for error or %NULL.
6954 * Synchronously connects to the message bus specified by @bus_type.
6955 * Note that the returned object may shared with other callers,
6956 * e.g. if two separate parts of a process calls this function with
6957 * the same @bus_type, they will share the same object.
6959 * This is a synchronous failable function. See g_bus_get() and
6960 * g_bus_get_finish() for the asynchronous version.
6962 * The returned object is a singleton, that is, shared with other
6963 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
6964 * event that you need a private message bus connection, use
6965 * g_dbus_address_get_for_bus_sync() and
6966 * g_dbus_connection_new_for_address().
6968 * Note that the returned #GDBusConnection object will (usually) have
6969 * the #GDBusConnection:exit-on-close property set to %TRUE.
6971 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
6976 g_bus_get_sync (GBusType bus_type,
6977 GCancellable *cancellable,
6980 GDBusConnection *connection;
6982 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
6984 connection = get_uninitialized_connection (bus_type, cancellable, error);
6985 if (connection == NULL)
6988 if (!g_initable_init (G_INITABLE (connection), cancellable, error))
6990 g_object_unref (connection);
6999 bus_get_async_initable_cb (GObject *source_object,
7003 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (user_data);
7007 if (!g_async_initable_init_finish (G_ASYNC_INITABLE (source_object),
7011 g_assert (error != NULL);
7012 g_simple_async_result_take_error (simple, error);
7013 g_object_unref (source_object);
7017 g_simple_async_result_set_op_res_gpointer (simple,
7021 g_simple_async_result_complete_in_idle (simple);
7022 g_object_unref (simple);
7027 * @bus_type: A #GBusType.
7028 * @cancellable: (allow-none): A #GCancellable or %NULL.
7029 * @callback: A #GAsyncReadyCallback to call when the request is satisfied.
7030 * @user_data: The data to pass to @callback.
7032 * Asynchronously connects to the message bus specified by @bus_type.
7034 * When the operation is finished, @callback will be invoked. You can
7035 * then call g_bus_get_finish() to get the result of the operation.
7037 * This is a asynchronous failable function. See g_bus_get_sync() for
7038 * the synchronous version.
7043 g_bus_get (GBusType bus_type,
7044 GCancellable *cancellable,
7045 GAsyncReadyCallback callback,
7048 GDBusConnection *connection;
7049 GSimpleAsyncResult *simple;
7052 simple = g_simple_async_result_new (NULL,
7056 g_simple_async_result_set_check_cancellable (simple, cancellable);
7059 connection = get_uninitialized_connection (bus_type, cancellable, &error);
7060 if (connection == NULL)
7062 g_assert (error != NULL);
7063 g_simple_async_result_take_error (simple, error);
7064 g_simple_async_result_complete_in_idle (simple);
7065 g_object_unref (simple);
7069 g_async_initable_init_async (G_ASYNC_INITABLE (connection),
7072 bus_get_async_initable_cb,
7079 * @res: A #GAsyncResult obtained from the #GAsyncReadyCallback passed to g_bus_get().
7080 * @error: Return location for error or %NULL.
7082 * Finishes an operation started with g_bus_get().
7084 * The returned object is a singleton, that is, shared with other
7085 * callers of g_bus_get() and g_bus_get_sync() for @bus_type. In the
7086 * event that you need a private message bus connection, use
7087 * g_dbus_address_get_for_bus_sync() and
7088 * g_dbus_connection_new_for_address().
7090 * Note that the returned #GDBusConnection object will (usually) have
7091 * the #GDBusConnection:exit-on-close property set to %TRUE.
7093 * Returns: (transfer full): A #GDBusConnection or %NULL if @error is set. Free with g_object_unref().
7098 g_bus_get_finish (GAsyncResult *res,
7101 GSimpleAsyncResult *simple = G_SIMPLE_ASYNC_RESULT (res);
7103 GDBusConnection *ret;
7105 g_return_val_if_fail (error == NULL || *error == NULL, NULL);
7107 g_warn_if_fail (g_simple_async_result_get_source_tag (simple) == g_bus_get);
7111 if (g_simple_async_result_propagate_error (simple, error))
7114 object = g_simple_async_result_get_op_res_gpointer (simple);
7115 g_assert (object != NULL);
7116 ret = g_object_ref (G_DBUS_CONNECTION (object));
7122 /* ---------------------------------------------------------------------------------------------------- */